get Path From Uri via CursorLoader - Android android.net

Android examples for android.net:Uri

Description

get Path From Uri via CursorLoader

Demo Code

import android.content.Context;
import android.content.CursorLoader;
import android.database.Cursor;
import android.net.Uri;
import android.provider.MediaStore;

public class Main {

  public static String getPathFromUri(Context context, Uri contentUri) {
    if (contentUri != null) {
      if (contentUri.getScheme().toString().compareTo("content") == 0) {
        String[] proj = { MediaStore.Images.Media.DATA };
        CursorLoader loader = new CursorLoader(context, contentUri, proj, null, null, null);
        Cursor cursor = loader.loadInBackground();
        int index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();//from  w ww  .ja v a2s.c o  m
        return cursor.getString(index);
      } else if (contentUri.getScheme().toString().compareTo("file") == 0) {
        String fileName = contentUri.toString().replace("file://", "");
        return fileName;
      }
    }
    return null;
  }

}

Related Tutorials