Example usage for android.database Cursor moveToPosition

List of usage examples for android.database Cursor moveToPosition

Introduction

In this page you can find the example usage for android.database Cursor moveToPosition.

Prototype

boolean moveToPosition(int position);

Source Link

Document

Move the cursor to an absolute position.

Usage

From source file:com.aero2.android.DefaultActivities.SmogMapActivity.java

public List<WeightedLatLng> getListForHeatMap(Cursor cursor) {
    Log.v(LOG_TAG, "Entered the getListFotHeatMap Fuction");
    List<WeightedLatLng> list = new ArrayList<WeightedLatLng>();
    WeightedLatLng[] weightedLatLng = new WeightedLatLng[cursor.getCount()];
    Log.v("CusorLength:", " cursor length is " + cursor.getCount());
    if (cursor.moveToFirst()) {

        for (int i = 0; i < cursor.getCount(); i++) {

            cursor.moveToPosition(i);
            weightedLatLng[i] = new WeightedLatLng(
                    new LatLng(Double.valueOf(cursor.getString(1)), Double.valueOf(cursor.getString(2))),
                    Double.valueOf(cursor.getString(0)));
            //Log.v("RandomValue", "random smog value: " + random);
            Log.v("Cursor", cursor.getString(0) + " " + cursor.getString(1) + " " + cursor.getString(2));
            list.add(weightedLatLng[i]);

        }/*from  ww  w.  j  a  va 2 s .  c o  m*/
    }
    return list;
}

From source file:edu.umbc.cs.ebiquity.mithril.parserapp.contentparsers.contacts.ContactsListFragment.java

@Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
    // Gets the Cursor object currently bound to the ListView
    final Cursor cursor = mAdapter.getCursor();

    // Moves to the Cursor row corresponding to the ListView item that was clicked
    cursor.moveToPosition(position);

    /**//  w  w  w . jav a 2  s.  com
     * An item click here signifies that the uri has to be passed on to the detail 
     * fragment to get it to display the correct data
     */
    /**
     * TODO Prajit Have to change this in order to ensure that the right Contact URI is being accessed
     * WE HAVE A DEPENDENCY HERE ON SPRIVACY! Let's try to remove it...
     */
    // Creates a contact lookup Uri from contact ID and lookup_key
    final Uri uri =
            //              ContentUris.withAppendedId(
            //                       Uri.withAppendedPath(
            //                             Uri.withAppendedPath(ContactsQuery.CONTENT_URI, "lookup"), 
            //                                cursor.getString(ContactsQuery.LOOKUP_KEY)),
            //                                cursor.getLong(ContactsQuery.ID)
            //                                ); 
            Contacts.getLookupUri(cursor.getLong(ContactsQuery.ID), cursor.getString(ContactsQuery.LOOKUP_KEY));
    //         Uri.parse("content://com.prajitdas.sprivacy.contentprovider.Content/contacts/John Doe/1");
    //         ConstantsManager.getLookupUri(getActivity().getApplicationContext(),
    //                 cursor.getLong(ContactsQuery.ID),
    //                 cursor.getString(ContactsQuery.LOOKUP_KEY));

    // Notifies the parent activity that the user selected a contact. In a two-pane layout, the
    // parent activity loads a ContactDetailFragment that displays the details for the selected
    // contact. In a single-pane layout, the parent activity starts a new activity that
    // displays contact details in its own Fragment.
    mOnContactSelectedListener.onContactSelected(uri);

    // If two-pane layout sets the selected item to checked so it remains highlighted. In a
    // single-pane layout a new activity is started so this is not needed.
    if (mIsTwoPaneLayout) {
        getListView().setItemChecked(position, true);
    }
}

From source file:com.awesome.byunghwa.app.mytvapplication.fragment.MainFragment.java

@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {

    switch (loader.getId()) {
    case MY_LOADER_ID_MOVIE_LIST_POPULARITY:
        LogUtil.log_i(TAG, "onLoadFinished pop entry gets called...");
        LogUtil.log_i(TAG, "cursor id: " + cursor.toString());
        LogUtil.log_i(TAG, "cursor row count pop entry: " + cursor.getCount());

        if (cursor.moveToFirst()) {
            LogUtil.log_i(TAG, "load pop rows gets called!");

            mCardPresenter = new CardPresenter();

            ArrayObjectAdapter listRowAdapter = new ArrayObjectAdapter(mCardPresenter);

            for (int j = 0; j < cursor.getCount(); j++) {
                cursor.moveToPosition(j);
                mMovie = new Movie();
                mMovie.setTitle(cursor.getString(MoviesLoader.Query.ORIGINAL_TITLE));

                String urlNotComplete = cursor.getString(MoviesLoader.Query.POSTER_THUMBNAIL);
                String urlComplete = "http://image.tmdb.org/t/p/w185/" + urlNotComplete;

                mMovie.setCardImageUrl(urlComplete);
                mMovie.setDescription(cursor.getString(MoviesLoader.Query.OVERVIEW));
                mMovie.setBackgroundImageUrl(urlComplete);
                mMovie.setId(cursor.getLong(MoviesLoader.Query.MOVIE_ID));
                listRowAdapter.add(mMovie);
            }/*  w  ww  .jav  a2 s. c o  m*/

            long headerId = 0;

            HeaderItem header = new HeaderItem(headerId, sortOrderArrayList[((int) headerId)]);
            mRowsAdapter.add(new ListRow(header, listRowAdapter));

            setAdapter(mRowsAdapter);
        }
        getLoaderManager().destroyLoader(loader.getId());
        break;
    case MY_LOADER_ID_MOVIE_LIST_VOTE_AVERAGE:
        LogUtil.log_i(TAG, "onLoadFinished top rated entry gets called...");
        LogUtil.log_i(TAG, "cursor id: " + cursor.toString());
        LogUtil.log_i(TAG, "cursor row count top rated entry: " + cursor.getCount());

        if (cursor.moveToFirst()) {
            LogUtil.log_i(TAG, "load top rated rows gets called!");

            mCardPresenter = new CardPresenter();

            ArrayObjectAdapter listRowAdapter = new ArrayObjectAdapter(mCardPresenter);

            for (int j = 0; j < cursor.getCount(); j++) {
                cursor.moveToPosition(j);
                mMovie = new Movie();
                mMovie.setTitle(cursor.getString(MoviesLoader.Query.ORIGINAL_TITLE));

                String urlNotComplete = cursor.getString(MoviesLoader.Query.POSTER_THUMBNAIL);
                String urlComplete = "http://image.tmdb.org/t/p/w185/" + urlNotComplete;

                mMovie.setCardImageUrl(urlComplete);
                mMovie.setDescription(cursor.getString(MoviesLoader.Query.OVERVIEW));
                mMovie.setBackgroundImageUrl(urlComplete);
                mMovie.setId(cursor.getLong(MoviesLoader.Query.MOVIE_ID));
                listRowAdapter.add(mMovie);
            }

            long headerId = 1;

            HeaderItem header = new HeaderItem(headerId, sortOrderArrayList[((int) headerId)]);
            mRowsAdapter.add(new ListRow(header, listRowAdapter));

            setAdapter(mRowsAdapter);
        }
        getLoaderManager().destroyLoader(loader.getId());
        break;
    case MY_LOADER_ID_MOVIE_LIST_FAVORITES:
        LogUtil.log_i(TAG, "onLoadFinished favorites entry gets called...");
        LogUtil.log_i(TAG, "cursor id: " + cursor.toString());
        LogUtil.log_i(TAG, "cursor row count fav entry: " + cursor.getCount());

        if (cursor.moveToFirst()) {
            LogUtil.log_i(TAG, "load fav rated rows gets called!");

            mCardPresenter = new CardPresenter();

            ArrayObjectAdapter listRowAdapter = new ArrayObjectAdapter(mCardPresenter);

            for (int j = 0; j < cursor.getCount(); j++) {
                cursor.moveToPosition(j);
                mMovie = new Movie();
                mMovie.setTitle(cursor.getString(MoviesLoader.Query.ORIGINAL_TITLE));

                String urlNotComplete = cursor.getString(MoviesLoader.Query.POSTER_THUMBNAIL);
                String urlComplete = "http://image.tmdb.org/t/p/w185/" + urlNotComplete;

                mMovie.setCardImageUrl(urlComplete);
                mMovie.setDescription(cursor.getString(MoviesLoader.Query.OVERVIEW));
                mMovie.setBackgroundImageUrl(urlComplete);
                mMovie.setId(cursor.getLong(MoviesLoader.Query.MOVIE_ID));
                listRowAdapter.add(mMovie);
            }

            long headerId = 2;

            HeaderItem header = new HeaderItem(headerId, sortOrderArrayList[((int) headerId)]);
            mRowsAdapter.add(new ListRow(header, listRowAdapter));

            setAdapter(mRowsAdapter);

        }
        getLoaderManager().destroyLoader(loader.getId());
        break;

    }
}

From source file:com.MustacheMonitor.MustacheMonitor.StacheCam.java

/**
 * Called when the camera view exits.//from   w w w  . jav a  2  s  .co m
 *
 * @param requestCode       The request code originally supplied to startActivityForResult(),
 *                          allowing you to identify who this result came from.
 * @param resultCode        The integer result code returned by the child activity through its setResult().
 * @param intent            An Intent, which can return result data to the caller (various data can be attached to Intent "extras").
 */
public void onActivityResult(int requestCode, int resultCode, Intent intent) {

    // Get src and dest types from request code
    int srcType = (requestCode / 16) - 1;
    int destType = (requestCode % 16) - 1;
    int rotate = 0;

    // If CAMERA
    if (srcType == CAMERA) {
        // If image available
        if (resultCode == Activity.RESULT_OK) {
            try {
                // Create an ExifHelper to save the exif data that is lost during compression
                ExifHelper exif = new ExifHelper();
                try {
                    if (this.encodingType == JPEG) {
                        exif.createInFile(DirectoryManager.getTempDirectoryPath(this.cordova.getActivity())
                                + "/.Pic.jpg");
                        exif.readExifData();
                        rotate = exif.getOrientation();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }

                Bitmap bitmap = null;
                Uri uri = null;

                // If sending base64 image back
                if (destType == DATA_URL) {
                    bitmap = getScaledBitmap(FileUtils.stripFileProtocol(imageUri.toString()));

                    if (rotate != 0 && this.correctOrientation) {
                        bitmap = getRotatedBitmap(rotate, bitmap, exif);
                    }

                    this.processPicture(bitmap);
                    checkForDuplicateImage(DATA_URL);
                }

                // If sending filename back
                else if (destType == FILE_URI) {
                    if (!this.saveToPhotoAlbum) {
                        uri = Uri.fromFile(
                                new File(DirectoryManager.getTempDirectoryPath(this.cordova.getActivity()),
                                        System.currentTimeMillis() + ".jpg"));
                    } else {
                        uri = getUriFromMediaStore();
                    }

                    if (uri == null) {
                        this.failPicture("Error capturing image - no media storage found.");
                    }

                    // If all this is true we shouldn't compress the image.
                    if (this.targetHeight == -1 && this.targetWidth == -1 && this.mQuality == 100
                            && rotate == 0) {
                        writeUncompressedImage(uri);

                        this.success(new PluginResult(PluginResult.Status.OK, uri.toString()), this.callbackId);
                    } else {
                        bitmap = getScaledBitmap(FileUtils.stripFileProtocol(imageUri.toString()));

                        if (rotate != 0 && this.correctOrientation) {
                            bitmap = getRotatedBitmap(rotate, bitmap, exif);
                        }

                        // Add compressed version of captured image to returned media store Uri
                        OutputStream os = this.cordova.getActivity().getContentResolver().openOutputStream(uri);
                        bitmap.compress(Bitmap.CompressFormat.JPEG, this.mQuality, os);
                        os.close();

                        // Restore exif data to file
                        if (this.encodingType == JPEG) {
                            String exifPath;
                            if (this.saveToPhotoAlbum) {
                                exifPath = FileUtils.getRealPathFromURI(uri, this.cordova);
                            } else {
                                exifPath = uri.getPath();
                            }
                            exif.createOutFile(exifPath);
                            exif.writeExifData();
                        }

                    }
                    // Send Uri back to JavaScript for viewing image
                    this.success(new PluginResult(PluginResult.Status.OK, uri.toString()), this.callbackId);
                }

                this.cleanup(FILE_URI, this.imageUri, uri, bitmap);
                bitmap = null;

            } catch (IOException e) {
                e.printStackTrace();
                this.failPicture("Error capturing image.");
            }
        }

        // If cancelled
        else if (resultCode == Activity.RESULT_CANCELED) {
            this.failPicture("Camera cancelled.");
        }

        // If something else
        else {
            this.failPicture("Did not complete!");
        }
    }

    // If retrieving photo from library
    else if ((srcType == PHOTOLIBRARY) || (srcType == SAVEDPHOTOALBUM)) {
        if (resultCode == Activity.RESULT_OK) {
            Uri uri = intent.getData();

            // If you ask for video or all media type you will automatically get back a file URI
            // and there will be no attempt to resize any returned data
            if (this.mediaType != PICTURE) {
                this.success(new PluginResult(PluginResult.Status.OK, uri.toString()), this.callbackId);
            } else {
                // This is a special case to just return the path as no scaling,
                // rotating or compression needs to be done
                if (this.targetHeight == -1 && this.targetWidth == -1 && this.mQuality == 100
                        && destType == FILE_URI && !this.correctOrientation) {
                    this.success(new PluginResult(PluginResult.Status.OK, uri.toString()), this.callbackId);
                } else {
                    // Get the path to the image. Makes loading so much easier.
                    String imagePath = FileUtils.getRealPathFromURI(uri, this.cordova);
                    Log.d(LOG_TAG, "Real path = " + imagePath);
                    // If we don't have a valid image so quit.
                    if (imagePath == null) {
                        Log.d(LOG_TAG, "I either have a null image path or bitmap");
                        this.failPicture("Unable to retreive path to picture!");
                        return;
                    }
                    Bitmap bitmap = getScaledBitmap(imagePath);
                    if (bitmap == null) {
                        Log.d(LOG_TAG, "I either have a null image path or bitmap");
                        this.failPicture("Unable to create bitmap!");
                        return;
                    }

                    if (this.correctOrientation) {
                        String[] cols = { MediaStore.Images.Media.ORIENTATION };
                        Cursor cursor = this.cordova.getActivity().getContentResolver().query(intent.getData(),
                                cols, null, null, null);
                        if (cursor != null) {
                            cursor.moveToPosition(0);
                            rotate = cursor.getInt(0);
                            cursor.close();
                        }
                        if (rotate != 0) {
                            Matrix matrix = new Matrix();
                            matrix.setRotate(rotate);
                            bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(),
                                    matrix, true);
                        }
                    }

                    // If sending base64 image back
                    if (destType == DATA_URL) {
                        this.processPicture(bitmap);
                    }

                    // If sending filename back
                    else if (destType == FILE_URI) {
                        // Do we need to scale the returned file
                        if (this.targetHeight > 0 && this.targetWidth > 0) {
                            try {
                                // Create an ExifHelper to save the exif data that is lost during compression
                                String resizePath = DirectoryManager
                                        .getTempDirectoryPath(this.cordova.getActivity()) + "/resize.jpg";
                                ExifHelper exif = new ExifHelper();
                                try {
                                    if (this.encodingType == JPEG) {
                                        exif.createInFile(resizePath);
                                        exif.readExifData();
                                        rotate = exif.getOrientation();
                                    }
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }

                                OutputStream os = new FileOutputStream(resizePath);
                                bitmap.compress(Bitmap.CompressFormat.JPEG, this.mQuality, os);
                                os.close();

                                // Restore exif data to file
                                if (this.encodingType == JPEG) {
                                    exif.createOutFile(FileUtils.getRealPathFromURI(uri, this.cordova));
                                    exif.writeExifData();
                                }

                                // The resized image is cached by the app in order to get around this and not have to delete you
                                // application cache I'm adding the current system time to the end of the file url.
                                this.success(
                                        new PluginResult(PluginResult.Status.OK,
                                                ("file://" + resizePath + "?" + System.currentTimeMillis())),
                                        this.callbackId);
                            } catch (Exception e) {
                                e.printStackTrace();
                                this.failPicture("Error retrieving image.");
                            }
                        } else {
                            this.success(new PluginResult(PluginResult.Status.OK, uri.toString()),
                                    this.callbackId);
                        }
                    }
                    if (bitmap != null) {
                        bitmap.recycle();
                        bitmap = null;
                    }
                    System.gc();
                }
            }
        } else if (resultCode == Activity.RESULT_CANCELED) {
            this.failPicture("Selection cancelled.");
        } else {
            this.failPicture("Selection did not complete!");
        }
    }
}

From source file:org.apache.cordova.ForegroundCameraLauncher.java

/**
 * Called when the camera view exits./*from   w ww.j  a  v a 2 s  .c om*/
 *
 * @param requestCode       The request code originally supplied to startActivityForResult(),
 *                          allowing you to identify who this result came from.
 * @param resultCode        The integer result code returned by the child activity through its setResult().
 * @param intent            An Intent, which can return result data to the caller (various data can be attached to Intent "extras").
 */
public void onActivityResult(int requestCode, int resultCode, Intent intent) {

    // Get src and dest types from request code
    int srcType = (requestCode / 16) - 1;
    int destType = (requestCode % 16) - 1;
    int rotate = 0;

    // If CAMERA
    if (srcType == CAMERA) {
        // If image available
        if (resultCode == Activity.RESULT_OK) {
            try {
                // Create an ExifHelper to save the exif data that is lost during compression
                ExifHelper exif = new ExifHelper();
                try {
                    if (this.encodingType == JPEG) {
                        exif.createInFile(DirectoryManager.getTempDirectoryPath(this.cordova.getActivity())
                                + "/.Pic.jpg");
                        exif.readExifData();
                        rotate = exif.getOrientation();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }

                Bitmap bitmap = null;
                Uri uri = null;

                // If sending base64 image back
                if (destType == DATA_URL) {
                    bitmap = getScaledBitmap(FileUtils.stripFileProtocol(imageUri.toString()));

                    if (rotate != 0 && this.correctOrientation) {
                        bitmap = getRotatedBitmap(rotate, bitmap, exif);
                    }

                    this.processPicture(bitmap);
                    checkForDuplicateImage(DATA_URL);
                }

                // If sending filename back
                else if (destType == FILE_URI) {
                    if (!this.saveToPhotoAlbum) {
                        uri = Uri.fromFile(
                                new File(DirectoryManager.getTempDirectoryPath(this.cordova.getActivity()),
                                        System.currentTimeMillis() + ".jpg"));
                    } else {
                        uri = getUriFromMediaStore();
                    }

                    if (uri == null) {
                        this.failPicture("Error capturing image - no media storage found.");
                    }

                    // If all this is true we shouldn't compress the image.
                    if (this.targetHeight == -1 && this.targetWidth == -1 && this.mQuality == 100
                            && rotate == 0) {
                        writeUncompressedImage(uri);

                        this.callbackContext.success(uri.toString());
                    } else {
                        bitmap = getScaledBitmap(FileUtils.stripFileProtocol(imageUri.toString()));

                        if (rotate != 0 && this.correctOrientation) {
                            bitmap = getRotatedBitmap(rotate, bitmap, exif);
                        }

                        // Add compressed version of captured image to returned media store Uri
                        OutputStream os = this.cordova.getActivity().getContentResolver().openOutputStream(uri);
                        bitmap.compress(Bitmap.CompressFormat.JPEG, this.mQuality, os);
                        os.close();

                        // Restore exif data to file
                        if (this.encodingType == JPEG) {
                            String exifPath;
                            if (this.saveToPhotoAlbum) {
                                exifPath = FileUtils.getRealPathFromURI(uri, this.cordova);
                            } else {
                                exifPath = uri.getPath();
                            }
                            exif.createOutFile(exifPath);
                            exif.writeExifData();
                        }

                    }
                    // Send Uri back to JavaScript for viewing image
                    this.callbackContext.success(uri.toString());
                }

                this.cleanup(FILE_URI, this.imageUri, uri, bitmap);
                bitmap = null;

            } catch (IOException e) {
                e.printStackTrace();
                this.failPicture("Error capturing image.");
            }
        }

        // If cancelled
        else if (resultCode == Activity.RESULT_CANCELED) {
            this.failPicture("Camera cancelled.");
        }

        // If something else
        else {
            this.failPicture("Did not complete!");
        }
    }

    // If retrieving photo from library
    else if ((srcType == PHOTOLIBRARY) || (srcType == SAVEDPHOTOALBUM)) {
        if (resultCode == Activity.RESULT_OK) {
            Uri uri = intent.getData();

            // If you ask for video or all media type you will automatically get back a file URI
            // and there will be no attempt to resize any returned data
            if (this.mediaType != PICTURE) {
                this.callbackContext.success(uri.toString());
            } else {
                // This is a special case to just return the path as no scaling,
                // rotating or compression needs to be done
                if (this.targetHeight == -1 && this.targetWidth == -1 && this.mQuality == 100
                        && destType == FILE_URI && !this.correctOrientation) {
                    this.callbackContext.success(uri.toString());
                } else {
                    // Get the path to the image. Makes loading so much easier.
                    String imagePath = FileUtils.getRealPathFromURI(uri, this.cordova);
                    String mimeType = FileUtils.getMimeType(imagePath);
                    // Log.d(LOG_TAG, "Real path = " + imagePath);
                    // Log.d(LOG_TAG, "mime type = " + mimeType);
                    // If we don't have a valid image so quit.
                    if (imagePath == null || mimeType == null || !(mimeType.equalsIgnoreCase("image/jpeg")
                            || mimeType.equalsIgnoreCase("image/png"))) {
                        Log.d(LOG_TAG, "I either have a null image path or bitmap");
                        this.failPicture("Unable to retrieve path to picture!");
                        return;
                    }
                    Bitmap bitmap = getScaledBitmap(imagePath);
                    if (bitmap == null) {
                        Log.d(LOG_TAG, "I either have a null image path or bitmap");
                        this.failPicture("Unable to create bitmap!");
                        return;
                    }

                    if (this.correctOrientation) {
                        String[] cols = { MediaStore.Images.Media.ORIENTATION };
                        Cursor cursor = this.cordova.getActivity().getContentResolver().query(intent.getData(),
                                cols, null, null, null);
                        if (cursor != null) {
                            cursor.moveToPosition(0);
                            rotate = cursor.getInt(0);
                            cursor.close();
                        }
                        if (rotate != 0) {
                            Matrix matrix = new Matrix();
                            matrix.setRotate(rotate);
                            bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(),
                                    matrix, true);
                        }
                    }

                    // If sending base64 image back
                    if (destType == DATA_URL) {
                        this.processPicture(bitmap);
                    }

                    // If sending filename back
                    else if (destType == FILE_URI) {
                        // Do we need to scale the returned file
                        if (this.targetHeight > 0 && this.targetWidth > 0) {
                            try {
                                // Create an ExifHelper to save the exif data that is lost during compression
                                String resizePath = DirectoryManager
                                        .getTempDirectoryPath(this.cordova.getActivity()) + "/resize.jpg";
                                ExifHelper exif = new ExifHelper();
                                try {
                                    if (this.encodingType == JPEG) {
                                        exif.createInFile(resizePath);
                                        exif.readExifData();
                                        rotate = exif.getOrientation();
                                    }
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }

                                OutputStream os = new FileOutputStream(resizePath);
                                bitmap.compress(Bitmap.CompressFormat.JPEG, this.mQuality, os);
                                os.close();

                                // Restore exif data to file
                                if (this.encodingType == JPEG) {
                                    exif.createOutFile(FileUtils.getRealPathFromURI(uri, this.cordova));
                                    exif.writeExifData();
                                }

                                // The resized image is cached by the app in order to get around this and not have to delete you
                                // application cache I'm adding the current system time to the end of the file url.
                                this.callbackContext
                                        .success("file://" + resizePath + "?" + System.currentTimeMillis());
                            } catch (Exception e) {
                                e.printStackTrace();
                                this.failPicture("Error retrieving image.");
                            }
                        } else {
                            this.callbackContext.success(uri.toString());
                        }
                    }
                    if (bitmap != null) {
                        bitmap.recycle();
                        bitmap = null;
                    }
                    System.gc();
                }
            }
        } else if (resultCode == Activity.RESULT_CANCELED) {
            this.failPicture("Selection cancelled.");
        } else {
            this.failPicture("Selection did not complete!");
        }
    }
}

From source file:com.tavant.droid.womensecurity.fragments.ContactsListFragment.java

@Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {

    CheckBox checkbox = (CheckBox) v.findViewWithTag(position);
    if (checkbox.isChecked())
        checkbox.setChecked(false);/*from w  w w  .  j  a  va  2 s  .c o m*/
    else
        checkbox.setChecked(true);

    // Gets the Cursor object currently bound to the ListView
    final Cursor cursor = mAdapter.getCursor();

    // Moves to the Cursor row corresponding to the ListView item that was
    // clicked
    cursor.moveToPosition(position);

    // Creates a contact lookup Uri from contact ID and lookup_key
    final Uri uri = Contacts.getLookupUri(cursor.getLong(ContactsQuery.ID),
            cursor.getString(ContactsQuery.LOOKUP_KEY));

    // Notifies the parent activity that the user selected a contact. In a
    // two-pane layout, the
    // parent activity loads a ContactDetailFragment that displays the
    // details for the selected
    // contact. In a single-pane layout, the parent activity starts a new
    // activity that
    // displays contact details in its own Fragment.
    mOnContactSelectedListener.onContactSelected(uri);

    // If two-pane layout sets the selected item to checked so it remains
    // highlighted. In a
    // single-pane layout a new activity is started so this is not needed.

}

From source file:com.example.android.contactslist.ui.groupsEditor.GroupsEditorFragment.java

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);

    mActionModeCallback = new ActionMode.Callback() {

        // Called when the action mode is created; startActionMode() was called
        @Override//from w  w w  .j a  v  a  2s  .co m
        public boolean onCreateActionMode(ActionMode mode, Menu menu) {
            // Inflate a menu resource providing context menu items
            //MenuInflater inflater = mode.getMenuInflater();
            //inflater.inflate(R.menu.contextual_actionbar, menu);
            mode.getMenuInflater().inflate(R.menu.contextual_actionbar, menu);
            return true;
        }

        // Called each time the action mode is shown. Always called after onCreateActionMode, but
        // may be called multiple times if the mode is invalidated.
        @Override
        public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
            return false; // Return false if nothing is done
        }

        // Called when the user selects a contextual menu item
        @Override
        public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
            switch (item.getItemId()) {

            case R.id.menu_remove_contact:
                GoogleGroupMaker googleGroupMaker = new GoogleGroupMaker(getActivity());
                googleGroupMaker.removeGoogleGroup(mDeleteGroupID);

                // method to remove group from app DB
                final ContactStatsContract statsDb = new ContactStatsContract(getActivity());
                final GroupStatsHelper groupStatsHelper = new GroupStatsHelper(getActivity());

                // delete group from the app Database
                final int records_updated = groupStatsHelper.removeGroupFromDB(mDeleteGroupID, statsDb);

                Toast.makeText(getActivity(), Long.toString(records_updated) + " Record(s) Updated",
                        Toast.LENGTH_SHORT).show();

                mode.finish(); // Action picked, so close the CAB
                return true;
            default:
                mode.finish(); // Action picked, so close the CAB
                Toast.makeText(getActivity(), "End Action Mode", Toast.LENGTH_SHORT).show();
                return false;
            }
        }

        // Called when the user exits the action mode
        @Override
        public void onDestroyActionMode(ActionMode mode) {
            mActionMode = null;
        }
    };

    getListView().setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {

        @Override
        public boolean onItemLongClick(AdapterView<?> arg0, View view, int position, long id) {
            if (mActionMode != null) {
                return false;
            }

            // Gets the Cursor object currently bound to the ListView
            final Cursor cursor = mAdapter.getCursor();

            // Moves to the Cursor row corresponding to the ListView item that was clicked
            cursor.moveToPosition(position);

            // Using the lookupKey because the wrong ID was being returned
            mDeleteGroupID = cursor.getLong(GroupsListStatsQuery.GROUP_ID);
            // Start the CAB using the ActionMode.Callback defined above
            mActionMode = getActivity().startActionMode(mActionModeCallback);
            view.setSelected(true);
            return true;
        }
    });

}

From source file:com.tct.fw.ex.photo.fragments.PhotoViewFragment.java

@Override
public void onCursorChanged(Cursor cursor) {
    if (mAdapter == null) {
        // The adapter is set in onAttach(), and is guaranteed to be non-null. We have magically
        // received an onCursorChanged without attaching to an activity. Ignore this cursor
        // change.
        return;/*from   ww  w  .  j  av a2  s. c o m*/
    }
    // FLAG: There is a problem here:
    // If the cursor changes, and new items are added at an earlier position than
    // the current item, we will switch photos here. Really we should probably
    // try to find a photo with the same url and move the cursor to that position.
    if (cursor.moveToPosition(mPosition) && !isPhotoBound()) {
        mCallback.onCursorChanged(this, cursor);

        final LoaderManager manager = getLoaderManager();

        final Loader<BitmapResult> fakePhotoLoader = manager.getLoader(PhotoViewCallbacks.BITMAP_LOADER_PHOTO);
        if (fakePhotoLoader != null) {
            final PhotoBitmapLoaderInterface loader = (PhotoBitmapLoaderInterface) fakePhotoLoader;
            mResolvedPhotoUri = mAdapter.getPhotoUri(cursor);
            loader.setPhotoUri(mResolvedPhotoUri);
            loader.forceLoad();
        }

        if (!mThumbnailShown) {
            final Loader<BitmapResult> fakeThumbnailLoader = manager
                    .getLoader(PhotoViewCallbacks.BITMAP_LOADER_THUMBNAIL);
            if (fakeThumbnailLoader != null) {
                final PhotoBitmapLoaderInterface loader = (PhotoBitmapLoaderInterface) fakeThumbnailLoader;
                mThumbnailUri = mAdapter.getThumbnailUri(cursor);
                loader.setPhotoUri(mThumbnailUri);
                loader.forceLoad();
            }
        }
    }
}

From source file:com.android.contacts.group.GroupMembersFragment.java

private void sendToGroup(long[] ids, String sendScheme, String title) {
    if (ids == null || ids.length == 0)
        return;//from  w w  w .j av  a  2s . c o m

    // Get emails or phone numbers
    // contactMap <contact_id, contact_data>
    final Map<String, ContactDataHelperClass> contactMap = new HashMap<>();
    // itemList <item_data>
    final List<String> itemList = new ArrayList<>();
    final String sIds = GroupUtil.convertArrayToString(ids);
    final String select = (ContactsUtils.SCHEME_MAILTO.equals(sendScheme) ? Query.EMAIL_SELECTION
            : Query.PHONE_SELECTION) + " AND " + ContactsContract.Data.CONTACT_ID + " IN (" + sIds + ")";
    final ContentResolver contentResolver = getContext().getContentResolver();
    final Cursor cursor = contentResolver.query(ContactsContract.Data.CONTENT_URI,
            ContactsUtils.SCHEME_MAILTO.equals(sendScheme) ? Query.EMAIL_PROJECTION : Query.PHONE_PROJECTION,
            select, null, null);

    if (cursor == null) {
        return;
    }

    try {
        cursor.moveToPosition(-1);
        while (cursor.moveToNext()) {
            final String contactId = cursor.getString(Query.CONTACT_ID);
            final String itemId = cursor.getString(Query.ITEM_ID);
            final boolean isPrimary = cursor.getInt(Query.PRIMARY) != 0;
            final int timesUsed = cursor.getInt(Query.TIMES_USED);
            final String data = cursor.getString(Query.DATA1);

            if (!TextUtils.isEmpty(data)) {
                final ContactDataHelperClass contact;
                if (!contactMap.containsKey(contactId)) {
                    contact = new ContactDataHelperClass();
                    contactMap.put(contactId, contact);
                } else {
                    contact = contactMap.get(contactId);
                }
                contact.addItem(itemId, timesUsed, isPrimary);
                itemList.add(data);
            }
        }
    } finally {
        cursor.close();
    }

    // Start picker if a contact does not have a default
    for (ContactDataHelperClass i : contactMap.values()) {
        if (!i.hasDefaultItem()) {
            // Build list of default selected item ids
            final List<Long> defaultSelection = new ArrayList<>();
            for (ContactDataHelperClass j : contactMap.values()) {
                final String selectionItemId = j.getDefaultSelectionItemId();
                if (selectionItemId != null) {
                    defaultSelection.add(Long.parseLong(selectionItemId));
                }
            }
            final long[] defaultSelectionArray = Longs.toArray(defaultSelection);
            startSendToSelectionPickerActivity(ids, defaultSelectionArray, sendScheme, title);
            return;
        }
    }

    if (itemList.size() == 0 || contactMap.size() < ids.length) {
        Toast.makeText(getContext(),
                ContactsUtils.SCHEME_MAILTO.equals(sendScheme)
                        ? getString(R.string.groupSomeContactsNoEmailsToast)
                        : getString(R.string.groupSomeContactsNoPhonesToast),
                Toast.LENGTH_LONG).show();
    }

    if (itemList.size() == 0) {
        return;
    }

    final String itemsString = TextUtils.join(",", itemList);
    GroupUtil.startSendToSelectionActivity(this, itemsString, sendScheme, title);
}

From source file:com.alley.android.ppi.app.OverviewFragment.java

private void paintHousesOnMap(Cursor cursor) {
    int count = 0;
    if (cursor != null) {
        Log.i(LOG_TAG, "Cursor had " + cursor.getCount() + " entries, current position" + cursor.getPosition());
        if (mMap == null) {
            // Log.e(LOG_TAG, "Camera was null - ");
            return;
        }//from   w w w .  j  av  a 2 s .  c o  m
        mMap.clear();
        int cursorCount = cursor.getCount();
        Log.i(LOG_TAG, "After movetoFirst Cursor had " + cursor.getCount() + " entries, current position"
                + cursor.getPosition());
        LatLng house = null;
        ArrayList<MarkerOptions> markers = new ArrayList<MarkerOptions>();
        while (count < cursorCount) { // this sucks but moveToFirst loses first entry so cant use cursor.moveToNext
            cursor.moveToPosition(count);
            float lat = cursor.getFloat(COL_COORD_LAT);
            float lon = cursor.getFloat(COL_COORD_LONG);
            if (lat != 0 && lon != 0) {
                house = new LatLng(lat, lon);
                if (latitude == 0 && longitude == 0 && zoom == 0 && lat != 0 && lon != 0) {
                    if (house != null) {
                        Log.i(LOG_TAG, " moving to house " + house.toString());
                        latitude = lat;
                        longitude = lon;
                        zoom = 15;
                        CameraUpdate center = CameraUpdateFactory.newLatLngZoom(house, zoom);
                        mMap.moveCamera(center);
                    }
                }
                MarkerOptions marker = new MarkerOptions().position(house)
                        .title(cursor.getString(OverviewFragment.COL_PRICE))
                        .snippet(cursor.getString(OverviewFragment.COL_SEARCH_STRING_USED) + "/"
                                + cursor.getString(OverviewFragment.COL_DESCRIPTION))
                        .icon(getBitmap(cursor.getString(OverviewFragment.COLUMN_NUM_BEDS),
                                cursor.getString(OverviewFragment.COL_APARTMENT_HOUSE)));
                mMap.addMarker(marker);
                markers.add(marker);
                Log.i(LOG_TAG,
                        count + " " + cursor.getString(OverviewFragment.COL_PRICE) + " " + house.toString());
            } else {
                Log.i(LOG_TAG, count + " lat " + lat + " long " + lon);
            }
            count++;
        }
        zoomToViewableObjects(markers);
    }
}