简体   繁体   中英

How to get the gallery images path in Android?

By using following code I am getting image path in 4.4.4 but, when I am using it in lollipop 5.0.1, it is not working.

String[] proj = {
                MediaStore.Images.Thumbnails._ID,
                MediaStore.Images.Thumbnails.DATA,
        };

        CursorLoader cursorLoader = new CursorLoader(
        this,  MediaStore.Images.Media.EXTERNAL_CONTENT_URI, proj, null, null, null);        

        Cursor imageCursor = cursorLoader.loadInBackground();

Start the loader manager by invoking getSupportLoaderManager when it is needed.

@Override 
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == REQUEST_CODE) {
        if (resultCode == Activity.RESULT_OK) {
            imageUri = data.getData();
            getSupportLoaderManager().initLoader(0, null, this);
        } else if (resultCode == Activity.RESULT_CANCELED) {
            Toast.makeText(this, "Action canceled.", Toast.LENGTH_LONG).show();
        } else { 
            Toast.makeText(this, "Action failed!", Toast.LENGTH_LONG).show();
        } 
    } 
} 

Then create a cursor loader that is used to retrieve the image path.

@Override 
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
    String[] projection = {
            MediaStore.Images.Media.DATA
    }; 
    CursorLoader cursorLoader = new CursorLoader(this, imageUri, projection, null, null, null);

    return cursorLoader; 
} 

When the cursor loader is finished it uses the retrieved data to update the UI.

@Override 
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
    if (data != null) {
        int columnIndex = data.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);

        data.moveToFirst();
        imagePath = data.getString(columnIndex);
    } else { 
        imagePath = imageUri.getPath(); 
    } 

    setupImageView(); 
} 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM