Example usage for android.content CursorLoader loadInBackground

List of usage examples for android.content CursorLoader loadInBackground

Introduction

In this page you can find the example usage for android.content CursorLoader loadInBackground.

Prototype

@Override
    public Cursor loadInBackground() 

Source Link

Usage

From source file:Main.java

@SuppressLint("NewApi")
public static String getRealPathFromURI_API11to18(Context context, Uri contentUri) {
    String[] proj = { MediaStore.Images.Media.DATA };
    String result = null;//ww  w . jav  a 2 s  . c  o m

    CursorLoader cursorLoader = new CursorLoader(context, contentUri, proj, null, null, null);
    Cursor cursor = cursorLoader.loadInBackground();

    if (cursor != null) {
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        result = cursor.getString(column_index);
    }
    return result;
}

From source file:Main.java

@SuppressLint("NewApi")
public static String getRealPathFromUriApi11to18(Context context, Uri contentUri) {
    String[] projection = { MediaStore.Images.Media.DATA };
    String result = null;//from  w  ww. j a  v a2  s .  c  om

    CursorLoader cursorLoader = new CursorLoader(context, contentUri, projection, null, null, null);
    Cursor cursor = cursorLoader.loadInBackground();

    if (cursor != null) {
        int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        result = cursor.getString(columnIndex);
    }
    return result;
}

From source file:Main.java

/**
 * Using code from this link: http://hmkcode.com/android-display-selected-image-and-its-real-path/
 * This method will return the absolute path Android.net.Uri.
 * NOTE!!! THIS DOES NOT SUPPORT API 10 OR BELOW!!! IF YOU NEED TO WORK WITH THAT, CHECK LINK ABOVE
 * @param context Context//from w ww .ja  v  a2s. c  o  m
 * @param uri Uri to check
 * @return String for the absolute path
 */
public static String getAbsolutePath(Context context, android.net.Uri uri) {
    if (Build.VERSION.SDK_INT >= 19) {
        try {
            String filePath = "";
            String wholeID = DocumentsContract.getDocumentId(uri);

            // Split at colon, use second item in the array
            String id = wholeID.split(":")[1];

            String[] column = { MediaStore.Images.Media.DATA };

            // where id is equal to
            String sel = MediaStore.Images.Media._ID + "=?";

            Cursor cursor = context.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                    column, sel, new String[] { id }, null);

            int columnIndex = cursor.getColumnIndex(column[0]);

            if (cursor.moveToFirst()) {
                filePath = cursor.getString(columnIndex);
            }
            cursor.close();
            return filePath;

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    } else {
        try {
            String[] proj = { MediaStore.Images.Media.DATA };
            String result = null;

            CursorLoader cursorLoader = new CursorLoader(context, uri, proj, null, null, null);
            Cursor cursor = cursorLoader.loadInBackground();

            if (cursor != null) {
                int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                cursor.moveToFirst();
                result = cursor.getString(column_index);
            }
            return result;

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}

From source file:Main.java

/**
 * Get the real file path from URI registered in media store 
 * @param contentUri URI registered in media store 
 *///  w  w w  .j  a va 2 s  .c  om
public static String getRealPathFromURI(Activity activity, Uri contentUri) {

    String releaseNumber = Build.VERSION.RELEASE;

    if (releaseNumber != null) {
        /* ICS Version */
        if (releaseNumber.length() > 0 && releaseNumber.charAt(0) == '4') {
            String[] proj = { MediaStore.Images.Media.DATA };
            String strFileName = "";
            CursorLoader cursorLoader = new CursorLoader(activity, contentUri, proj, null, null, null);
            Cursor cursor = cursorLoader.loadInBackground();
            if (cursor != null) {
                int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                cursor.moveToFirst();
                if (cursor.getCount() > 0)
                    strFileName = cursor.getString(column_index);

                cursor.close();
            }
            return strFileName;
        }
        /* GB Version */
        else if (releaseNumber.startsWith("2.3")) {
            String[] proj = { MediaStore.Images.Media.DATA };
            String strFileName = "";
            Cursor cursor = activity.managedQuery(contentUri, proj, null, null, null);
            if (cursor != null) {
                int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);

                cursor.moveToFirst();
                if (cursor.getCount() > 0)
                    strFileName = cursor.getString(column_index);

                cursor.close();
            }
            return strFileName;
        }
    }

    //---------------------
    // Undefined Version
    //---------------------
    /* GB, ICS Common */
    String[] proj = { MediaStore.Images.Media.DATA };
    String strFileName = "";
    Cursor cursor = activity.managedQuery(contentUri, proj, null, null, null);
    if (cursor != null) {
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);

        // Use the Cursor manager in ICS         
        activity.startManagingCursor(cursor);

        cursor.moveToFirst();
        if (cursor.getCount() > 0)
            strFileName = cursor.getString(column_index);

        //cursor.close(); // If the cursor close use , This application is terminated .(In ICS Version)
        activity.stopManagingCursor(cursor);
    }
    return strFileName;
}

From source file:Main.java

/**
 * Get the real file path from URI registered in media store 
 * @param contentUri URI registered in media store 
 *//*w w w  .j a  va 2s  .c o  m*/
public static String getRealPathFromURI(Activity activity, Uri contentUri) {

    String releaseNumber = Build.VERSION.RELEASE;

    if (releaseNumber != null) {
        /* ICS, JB Version */
        if (releaseNumber.length() > 0 && releaseNumber.charAt(0) == '4') {
            // URI from Gallery(MediaStore)
            String[] proj = { MediaStore.Images.Media.DATA };
            String strFileName = "";
            CursorLoader cursorLoader = new CursorLoader(activity, contentUri, proj, null, null, null);
            Cursor cursor = cursorLoader.loadInBackground();
            if (cursor != null) {
                int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                cursor.moveToFirst();
                if (cursor.getCount() > 0)
                    strFileName = cursor.getString(column_index);

                cursor.close();
            }
            // URI from Others(Dropbox, etc.) 
            if (strFileName == null || strFileName.isEmpty()) {
                if (contentUri.getScheme().compareTo("file") == 0)
                    strFileName = contentUri.getPath();
            }
            return strFileName;
        }
        /* GB Version */
        else if (releaseNumber.startsWith("2.3")) {
            // URI from Gallery(MediaStore)
            String[] proj = { MediaStore.Images.Media.DATA };
            String strFileName = "";
            Cursor cursor = activity.managedQuery(contentUri, proj, null, null, null);
            if (cursor != null) {
                int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);

                cursor.moveToFirst();
                if (cursor.getCount() > 0)
                    strFileName = cursor.getString(column_index);

                cursor.close();
            }
            // URI from Others(Dropbox, etc.) 
            if (strFileName == null || strFileName.isEmpty()) {
                if (contentUri.getScheme().compareTo("file") == 0)
                    strFileName = contentUri.getPath();
            }
            return strFileName;
        }
    }

    //---------------------
    // Undefined Version
    //---------------------
    /* GB, ICS Common */
    String[] proj = { MediaStore.Images.Media.DATA };
    String strFileName = "";
    Cursor cursor = activity.managedQuery(contentUri, proj, null, null, null);
    if (cursor != null) {
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);

        // Use the Cursor manager in ICS         
        activity.startManagingCursor(cursor);

        cursor.moveToFirst();
        if (cursor.getCount() > 0)
            strFileName = cursor.getString(column_index);

        //cursor.close(); // If the cursor close use , This application is terminated .(In ICS Version)
        activity.stopManagingCursor(cursor);
    }
    return strFileName;
}

From source file:Main.java

/**
 * Get the real file path from URI registered in media store 
 * @param contentUri URI registered in media store 
 *///from  w w w. j av a  2  s.c o  m
@SuppressWarnings("deprecation")
public static String getRealPathFromURI(Activity activity, Uri contentUri) {

    String releaseNumber = Build.VERSION.RELEASE;

    if (releaseNumber != null) {
        /* ICS, JB Version */
        if (releaseNumber.length() > 0 && releaseNumber.charAt(0) == '4') {
            // URI from Gallery(MediaStore)
            String[] proj = { MediaStore.Images.Media.DATA };
            String strFileName = "";
            CursorLoader cursorLoader = new CursorLoader(activity, contentUri, proj, null, null, null);
            Cursor cursor = cursorLoader.loadInBackground();
            if (cursor != null) {
                int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                cursor.moveToFirst();
                if (cursor.getCount() > 0)
                    strFileName = cursor.getString(column_index);

                cursor.close();
            }
            // URI from Others(Dropbox, etc.) 
            if (strFileName == null || strFileName.isEmpty()) {
                if (contentUri.getScheme().compareTo("file") == 0)
                    strFileName = contentUri.getPath();
            }
            return strFileName;
        }
        /* GB Version */
        else if (releaseNumber.startsWith("2.3")) {
            // URI from Gallery(MediaStore)
            String[] proj = { MediaStore.Images.Media.DATA };
            String strFileName = "";
            Cursor cursor = activity.managedQuery(contentUri, proj, null, null, null);
            if (cursor != null) {
                int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);

                cursor.moveToFirst();
                if (cursor.getCount() > 0)
                    strFileName = cursor.getString(column_index);

                cursor.close();
            }
            // URI from Others(Dropbox, etc.) 
            if (strFileName == null || strFileName.isEmpty()) {
                if (contentUri.getScheme().compareTo("file") == 0)
                    strFileName = contentUri.getPath();
            }
            return strFileName;
        }
    }

    //---------------------
    // Undefined Version
    //---------------------
    /* GB, ICS Common */
    String[] proj = { MediaStore.Images.Media.DATA };
    String strFileName = "";
    Cursor cursor = activity.managedQuery(contentUri, proj, null, null, null);
    if (cursor != null) {
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);

        // Use the Cursor manager in ICS         
        activity.startManagingCursor(cursor);

        cursor.moveToFirst();
        if (cursor.getCount() > 0)
            strFileName = cursor.getString(column_index);

        //cursor.close(); // If the cursor close use , This application is terminated .(In ICS Version)
        activity.stopManagingCursor(cursor);
    }
    return strFileName;
}

From source file:com.mantz_it.rfanalyzer.SettingsFragment.java

/**
 * Extract the path from an uri//from   w w  w.  j  av  a 2 s  .c  o  m
 * This code was published on StackOverflow by dextor
 *
 * @param contentUri      uri that contains the file path
 * @return absolute file path as string
 */
private String getRealPathFromURI(Uri contentUri) {
    String[] proj = { MediaStore.Images.Media.DATA };
    CursorLoader loader = new CursorLoader(this.getActivity(), contentUri, proj, null, null, null);
    Cursor cursor = loader.loadInBackground();
    int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
    cursor.moveToFirst();
    return cursor.getString(column_index);
}

From source file:com.hackensack.umc.activity.ProfileActivity.java

private String getPath(Uri uri) {
    String[] data = { MediaStore.Images.Media.DATA };
    CursorLoader loader = new CursorLoader(ProfileActivity.this, uri, data, null, null, null);
    Cursor cursor = loader.loadInBackground();
    int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
    cursor.moveToFirst();/*from w w w.  ja  v  a2 s .  c o  m*/
    return cursor.getString(column_index);
}

From source file:spring16.cs442.com.obtchat_10.BluetoothChatFragment.java

public void onActivityResult(int requestCode, int resultCode, Intent data) {
    switch (requestCode) {
    case REQUEST_CONNECT_DEVICE_SECURE:
        // When DeviceListActivity returns with a device to connect
        if (resultCode == Activity.RESULT_OK) {
            connectDevice(data, true);/*from   w w w .j  av a2s.c  om*/
        }
        break;
    case REQUEST_CONNECT_DEVICE_INSECURE:
        // When DeviceListActivity returns with a device to connect
        if (resultCode == Activity.RESULT_OK) {
            connectDevice(data, false);
        }
        break;
    case REQUEST_ENABLE_BT:
        // When the request to enable Bluetooth returns
        if (resultCode == Activity.RESULT_OK) {
            // Bluetooth is now enabled, so set up a chat session
            setupChat();
        } else {
            // User did not enable Bluetooth or an error occurred
            //Log.d(TAG, "BT not enabled");
            Toast.makeText(self, R.string.bt_not_enabled_leaving, Toast.LENGTH_SHORT).show();
            //getActivity().finish();
        }
        break;
    case 44:
        if (resultCode == Activity.RESULT_OK && data != null) {
            String realPath;
            // SDK < API11
            if (Build.VERSION.SDK_INT < 11)
                realPath = RealPathUtil.getRealPathFromURI_BelowAPI11(this, data.getData());

            // SDK >= 11 && SDK < 19
            else if (Build.VERSION.SDK_INT < 19)
                realPath = RealPathUtil.getRealPathFromURI_API11to18(this, data.getData());

            // SDK > 19 (Android 4.4)
            else
                realPath = RealPathUtil.getRealPathFromURI_API19(this, data.getData());

            //setTextViews(Build.VERSION.SDK_INT, data.getData().getPath(),realPath);

            //Toast.makeText(MainActivity.this, file.toString(), Toast.LENGTH_LONG).show();

            Uri uritoSend = Uri.fromFile(new File(realPath));
            Intent intent = new Intent();
            intent.setAction(Intent.ACTION_SEND);
            intent.setType("image/*");

            //String uri = uritoSend;
            intent.putExtra(Intent.EXTRA_STREAM, uritoSend);
            startActivity(intent);

        }
    }
    LinearLayout layout = (LinearLayout) findViewById(R.id.chatFragment);
    if (resultCode == RESULT_OK) {
        if (requestCode == 1888) {
            Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
            ByteArrayOutputStream bytes = new ByteArrayOutputStream();
            thumbnail.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
            File destination = new File(Environment.getExternalStorageDirectory(),
                    System.currentTimeMillis() + ".jpg");
            FileOutputStream fo;
            try {
                destination.createNewFile();
                fo = new FileOutputStream(destination);
                fo.write(bytes.toByteArray());
                fo.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            Drawable d = Drawable.createFromPath(destination.getPath());
            layout.setBackgroundDrawable(d);

            //ivImage.setImageBitmap(thumbnail);
        } else if (requestCode == 79) {
            Uri selectedImageUri = data.getData();
            String[] projection = { MediaStore.MediaColumns.DATA };
            CursorLoader cursorLoader = new CursorLoader(this, selectedImageUri, projection, null, null, null);
            Cursor cursor = cursorLoader.loadInBackground();
            int column_index = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
            cursor.moveToFirst();
            String selectedImagePath = cursor.getString(column_index);
            Bitmap bm;
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = true;
            BitmapFactory.decodeFile(selectedImagePath, options);
            final int REQUIRED_SIZE = 200;
            int scale = 1;
            while (options.outWidth / scale / 2 >= REQUIRED_SIZE
                    && options.outHeight / scale / 2 >= REQUIRED_SIZE)
                scale *= 2;
            options.inSampleSize = scale;
            options.inJustDecodeBounds = false;
            bm = BitmapFactory.decodeFile(selectedImagePath, options);

            Drawable d = Drawable.createFromPath(selectedImagePath);
            layout.setBackgroundDrawable(d);

        }
    }
}

From source file:com.caju.uheer.app.services.infrastructure.ContactablesLoaderCallbacks.java

@Override
public Loader<Cursor> onCreateLoader(int loaderIndex, Bundle args) {
    String query = "";
    JSONArray nearbyUsers = new JSONArray();

    Uri uri = Uri.withAppendedPath(CommonDataKinds.Contactables.CONTENT_FILTER_URI, query);

    // Sort results such that rows for the same contact stay together.
    String sortBy = CommonDataKinds.Contactables.LOOKUP_KEY;

    CursorLoader cursorLoader = new CursorLoader(mContext, // Context
            uri, // URI representing the table/resource to be queried
            null, // projection - the list of columns to return.  Null means "all"
            null, // selection - Which rows to return (condition rows must match)
            null, // selection args - can be provided separately and subbed into selection.
            sortBy); // string specifying sort order

    try {/*from  w  w w .j  a va2 s .  co  m*/
        // Parsing the JSON received from server.
        String nearbyUsersString = args.getString("jsonString");
        nearbyUsers = new JSONObject(nearbyUsersString).getJSONArray("nearbyUsers");
    } catch (JSONException e) {
        e.printStackTrace();
    }

    for (int i = 0; i < nearbyUsers.length(); i++) {
        //            Log.d("json", "" + nearbyUsers.getJSONObject(0).get("email"));
        try {
            query = nearbyUsers.getJSONObject(i).getString("email");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        //            query = args.getString("query");

        uri = Uri.withAppendedPath(CommonDataKinds.Contactables.CONTENT_FILTER_URI, query);

        cursorLoader = new CursorLoader(mContext, // Context
                uri, // URI representing the table/resource to be queried
                null, // projection - the list of columns to return.  Null means "all"
                null, // selection - Which rows to return (condition rows must match)
                null, // selection args - can be provided separately and subbed into selection.
                sortBy); // string specifying sort order

        Cursor cursor = cursorLoader.loadInBackground();

        Toast.makeText(mContext, "entrei no cursorLoader", Toast.LENGTH_LONG).show();
        if (cursor.getCount() == 0) {
            return cursorLoader;
        }

        int nameColumnIndex = cursor.getColumnIndex(CommonDataKinds.Contactables.DISPLAY_NAME);
        int lookupColumnIndex = cursor.getColumnIndex(CommonDataKinds.Contactables.LOOKUP_KEY);

        cursor.moveToFirst();

        String lookupKey = "";
        String displayName = "";
        do {
            String currentLookupKey = cursor.getString(lookupColumnIndex);
            if (!lookupKey.equals(currentLookupKey)) {
                displayName = cursor.getString(nameColumnIndex);
                lookupKey = currentLookupKey;
            }
        } while (cursor.moveToNext());

        Toast.makeText(mContext, displayName, Toast.LENGTH_LONG).show();
        try {
            JSONObject jobj = new JSONObject().put("name", displayName);
            if (!nearbyUsers.getJSONObject(i).has("channel")) {
                double[] geoPoint = new double[2];
                geoPoint[0] = nearbyUsers.getJSONObject(i).getJSONObject("geoPoint").getDouble("latitude");
                geoPoint[1] = nearbyUsers.getJSONObject(i).getJSONObject("geoPoint").getDouble("longitude");
                jobj.put("lat", geoPoint[0]);
                jobj.put("lon", geoPoint[1]);
            } else {
                String channel = nearbyUsers.getJSONObject(i).getString("channel");
                jobj.put("channel", channel);
            }
            usersFound.put(jobj);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    return cursorLoader;
}