using this recipe to try and choose an image from the gallery and then upload it to s3 but
my path always returns null.
private string _imgPath;
public void InitializeMediaPicker()
{
Intent = new Intent();
Intent.SetType("image/*");
Intent.SetAction(Intent.ActionGetContent);
StartActivityForResult(Intent.CreateChooser(Intent, "Select Picture"), 1000);
}
public string GetImage()
{
InitializeMediaPicker();
return _imgPath;
}
protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
{
if ((requestCode != 1000) || (resultCode != Result.Ok) || (data == null)) return;
var uri = data.Data;
_imgPath = GetPathToImage(uri);
}
private string GetPathToImage(Android.Net.Uri uri)
{
string path = null;
// The projection contains the columns we want to return in our query.
var projection = new[] { Android.Provider.MediaStore.Images.Media.InterfaceConsts.Data };
using (var cursor = ManagedQuery(uri, projection, null, null, null))
{
if (cursor == null) return path;
var columnIndex = cursor.GetColumnIndexOrThrow(Android.Provider.MediaStore.Images.Media.InterfaceConsts.Data);
cursor.MoveToFirst();
path = cursor.GetString(columnIndex);
}
return path;
}
Here is a working implementation ported from this question and specifically, this answer.
Include the WRITE_EXTERNAL_STORAGE permission in your manifest for this code to work.
public delegate void OnImageResultHandler(bool success, string imagePath);
protected OnImageResultHandler _imagePickerCallback;
public void GetImage(OnImageResultHandler callback)
{
if (callback == null) {
throw new ArgumentException ("OnImageResultHandler callback cannot be null.");
}
_imagePickerCallback = callback;
InitializeMediaPicker();
}
public void InitializeMediaPicker()
{
Intent = new Intent();
Intent.SetType("image/*");
Intent.SetAction(Intent.ActionGetContent);
StartActivityForResult(Intent.CreateChooser(Intent, "Select Picture"), 1000);
}
protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
{
if ((requestCode != 1000) || (resultCode != Result.Ok) || (data == null)) {
return;
}
string imagePath = null;
var uri = data.Data;
try {
imagePath = GetPathToImage(uri);
} catch (Exception ex) {
// Failed for some reason.
}
_imagePickerCallback (imagePath != null, imagePath);
}
private string GetPathToImage(Android.Net.Uri uri)
{
string doc_id = "";
using (var c1 = ContentResolver.Query (uri, null, null, null, null)) {
c1.MoveToFirst ();
String document_id = c1.GetString (0);
doc_id = document_id.Substring (document_id.LastIndexOf (":") + 1);
}
string path = null;
// The projection contains the columns we want to return in our query.
string selection = Android.Provider.MediaStore.Images.Media.InterfaceConsts.Id + " =? ";
using (var cursor = ManagedQuery(Android.Provider.MediaStore.Images.Media.ExternalContentUri, null, selection, new string[] {doc_id}, null))
{
if (cursor == null) return path;
var columnIndex = cursor.GetColumnIndexOrThrow(Android.Provider.MediaStore.Images.Media.InterfaceConsts.Data);
cursor.MoveToFirst();
path = cursor.GetString(columnIndex);
}
return path;
}
Example Usage:
Button button = FindViewById<Button> (Resource.Id.myButton);
button.Click += delegate {
GetImage(((b, p) => {
Toast.MakeText(this, "Found path: " + p, ToastLength.Long).Show();
}));
};
I've used a callback instead of returning the path for GetImage as the calling method would finish executing before OnActivityResult is called so the path returned would never be valid.
I changed the GetPathToImage method from the Xamarin recipe to the code below and now it works!
private string GetPathToImage(Android.Net.Uri uri)
{
ICursor cursor = this.ContentResolver.Query(uri, null, null, null, null);
cursor.MoveToFirst();
string document_id = cursor.GetString(0);
document_id = document_id.Split(':')[1];
cursor.Close();
cursor = ContentResolver.Query(
Android.Provider.MediaStore.Images.Media.ExternalContentUri,
null, MediaStore.Images.Media.InterfaceConsts.Id + " = ? ", new String[] { document_id }, null);
cursor.MoveToFirst();
string path = cursor.GetString(cursor.GetColumnIndex(MediaStore.Images.Media.InterfaceConsts.Data));
cursor.Close();
return path;
}
Related
private String getRealPathFromURI(Uri image) {
String[] proj = { MediaStore.Images.Media.DATA };
//This method was deprecated in API level 11
//Cursor cursor = managedQuery(contentUri, proj, null, null, null);
CursorLoader cursorLoader = new CursorLoader(
this,
image, proj, null, null, null);
Cursor cursor = cursorLoader.loadInBackground();
int column_index =
cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
public static String getFilePathByUri(Context context, Uri uri) {
String fileName = "";
Uri filePathUri = uri;
if (uri.getScheme().toString().compareTo("content") == 0) {
Cursor cursor = context.getContentResolver().query(uri, null, null, null, null);
if (cursor.moveToFirst()) {
int column_index = cursor.getColumnIndexOrThrow("_data");
filePathUri = Uri.parse(cursor.getString(column_index));
fileName = filePathUri.getEncodedPath();
}
cursor.close();
} else if (uri.getScheme().compareTo("file") == 0) {
fileName = filePathUri.getEncodedPath();
} else {
fileName = fileName + "_" + filePathUri.getLastPathSegment();
}
return fileName;
}
Try this
private String getRealPathFromURI(String contentURI) {
Uri contentUri = Uri.parse(contentURI);
Cursor cursor = mContext.getContentResolver().query(contentUri, null, null, null, null);
if (cursor == null) {
return contentUri.getPath();
} else {
cursor.moveToFirst();
int index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
String str = cursor.getString(index);
cursor.close();
return str;
}
}
Check this
#SuppressLint("NewApi")
public static String getRealPathFromURI(Context context, Uri uri) {
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;
}
Get URI from Camera
private Uri capturedUri;
public void openCamera() {
Intent takePicture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createMediaFile(1);
} catch (IOException ex) {
}
// Continue only if the File was successfully created
if (photoFile != null) {
capturedUri = null;
capturedUri = Uri.fromFile(photoFile);
takePicture.putExtra(MediaStore.EXTRA_OUTPUT, capturedUri);
startActivityForResult(takePicture, 1);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == 1) {
if ((null == data) || (data.getData() == null)) {
try {
Bitmap photo = MediaStore.Images.Media.getBitmap(getContentResolver(), capturedUri);
img_profileimage.setImageBitmap(photo);
capturedUri = getImageUri(context, photo);
} catch (IOException e) {
e.printStackTrace();
}
} else {
Toast.makeText(context, context.getResources().getString(R.string.some_thing_went_wrong), Toast.LENGTH_SHORT);
}
} else if (requestCode == 2) {
if (data.getData() != null) {
// Uri selectedImage = data.getData();
capturedUri = null;
capturedUri = data.getData();
} else {
Toast.makeText(context, context.getResources().getString(R.string.some_thing_went_wrong), Toast.LENGTH_SHORT);
}
}
}
}
public Uri getImageUri(Context inContext, Bitmap inImage) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String picturePath = MediaStore.Images.Media.insertImage(inContext.getContentResolver(), inImage, "Image", null);
return Uri.parse(picturePath);
}
public File createMediaFile(int type) throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String fileName = type == 1 ? "JPEG_" + timeStamp + "_" : "VID_" + timeStamp + "_";
File storageDir = Environment.getExternalStoragePublicDirectory(type == 1 ? Environment.DIRECTORY_PICTURES : Environment.DIRECTORY_MOVIES);
File file = File.createTempFile(fileName, /* prefix */type == 1 ? ".jpg" : ".mp4",/* suffix */storageDir/* directory */);
return file;
}
I made an Gallery Pick Intent.
final Intent galleryIntent = new Intent();
galleryIntent.setType("image/*");
galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
activity.startActivityForResult(galleryIntent, requestCode);
I choose a picture from google drive and return to onActivityResult
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == REQUEST_GALLERY_PICK) {
try {
setAvatar(ImageUtils.getPath(EditClientActivity.this, data.getData(), IMAGE));
} catch (IOException e) {
e.printStackTrace();
}
}
} else {
avatarSizeOriginal = null;
}
}
Here I get the path from selected Image:
public static String getPath(Context ctx, Uri uri, String fileType) {
String mPath = null;
Cursor mCursor;
String[] mColumns = {MediaStore.Images.Media.DATA};
if (uri == null) {
return null;
}
// algorithm to be used for devices starting with KK
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
String mId = uri.getPathSegments().get(uri.getPathSegments().size() - 1);
String mSelection = "";
Uri mProvider = null;
if (mId.contains(":")) {
final String[] split = mId.split(":");
mId = split[1];
}
if (fileType.equals(FileTypes.IMAGE)) {
mSelection = MediaStore.Images.Media._ID + "=?";
mProvider = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
}
if (fileType.equals(FileTypes.VIDEO)) {
mSelection = MediaStore.Video.Media._ID + "=?";
mProvider = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
}
if (fileType.equals(FileTypes.AUDIO)) {
mSelection = MediaStore.Audio.Media._ID + "=?";
mProvider = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
}
mCursor = ctx.getContentResolver().query(mProvider, mColumns, mSelection, new String[]{mId}, null, null);
} else {
mCursor = ctx.getContentResolver().query(uri, mColumns, null, null, null);
}
int column_index = mCursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
if (mCursor != null && mCursor.moveToFirst()) {
mPath = mCursor.getString(column_index);
mCursor.close();
}
if (mPath==null) {
mPath = uri.getPath();
}
return mPath;
}
And at last when I try to use the image i get a crash:
private void setAvatar(String path) throws IOException {
avatarSizeOriginal = new File(path);
initialAvatar = new File(path);}
It indicates path /document/acc=1;doc=231
How to deal with such issue ?
get path of video file selected from gallery getting NULL. How to get path of video file ? Get URi in Activity Result also give null. converting Uri to String also getting Null.
Intent intent;
String selectedVideo1Path, selectedVideo2Path;
EditText e1,e2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.videos_activity);
Button button1 = (Button) findViewById(R.id.video1_btn);
Button button2 = (Button) findViewById(R.id.video2_btn);
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
selectVideoFromGallery();
startActivityForResult(intent, 101);
}
});
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
selectVideoFromGallery();
startActivityForResult(intent, 102);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 101) {
if (data.getData() != null) {
selectedVideo1Path = getPath(data.getData());
Toast.makeText(MergeVideosActivity.this, "Path 1 : "+selectedVideo1Path, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "Failed to select video", Toast.LENGTH_LONG).show();
}
}
if (requestCode == 102) {
if (data.getData() != null) {
selectedVideo2Path = getPath(data.getData());
//String str2 = selectedVideo2Path.toString();
// e2.setText(str2);
Toast.makeText(MergeVideosActivity.this, "Path 2 : "+selectedVideo2Path, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "Failed to select video", Toast.LENGTH_LONG).show();
}
}
}
This is my getPath method
public String getPath(Uri uri) {
int column_index = 0;
String[] projection = {MediaStore.Images.Media.DATA};
Cursor cursor = managedQuery(uri, projection, null, null, null);
if (cursor != null) {
column_index = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATA);
cursor.moveToFirst();
}
return cursor.getString(column_index);
}
Selected Video from Gallery I hope its OK ? Check it
public void selectVideoFromGallery() {
if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)) {
intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Video.Media.EXTERNAL_CONTENT_URI);
} else {
intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Video.Media.INTERNAL_CONTENT_URI);
}
intent.setType("video/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
}
}
Update your getPath method
public String generatePath(Uri uri,Context context) {
String filePath = null;
final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
if(isKitKat){
filePath = generateFromKitkat(uri,context);
}
if(filePath != null){
return filePath;
}
Cursor cursor = context.getContentResolver().query(uri, new String[] { MediaStore.MediaColumns.DATA }, null, null, null);
if (cursor != null) {
if (cursor.moveToFirst()) {
int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
filePath = cursor.getString(columnIndex);
}
cursor.close();
}
return filePath == null ? uri.getPath() : filePath;
}
#TargetApi(19)
private String generateFromKitkat(Uri uri,Context context){
String filePath = null;
if(DocumentsContract.isDocumentUri(context, uri)){
String wholeID = DocumentsContract.getDocumentId(uri);
String id = wholeID.split(":")[1];
String[] column = { Media.DATA };
String sel = Media._ID + "=?";
Cursor cursor = context.getContentResolver().
query(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;
}
I have developing app which get the path from SDcard for all types (Images, Audio, Video)...
It works fine for opening the Default Android Browsers(Gallery). But when i open the SDcard in other app's it throws NullPointer. For example i have open the SDcard through my app using Explorer app shows null pointer exception...
I will save the image path to SQlite and get the content from the SQLite on another activity. But this Explorer app shows all types, not only for specified type. (Example i select image button, but it shows all types).
radio_group.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup rd_group, int checked_id) {
checking = null;
switch(checked_id) {
case R.id.radio_image:
checking = "image";
break;
case R.id.radio_audio:
checking = "audio";
break;
case R.id.radio_video:
checking = "video";
break;
}
}
});
// I have a radio button for type of content will shown only
select_content.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
if(checking.equals("")) {
Toast.makeText(getApplicationContext(), "Please select the content type", Toast.LENGTH_SHORT).show();
return;
}
// when i select image, show image content only in SDcard.
// When i select audio, show only audio contents.
// when i select video, show only video contents.
if(checking.equals("image")) {
Intent intent_image = new Intent();
intent_image.setType("image/*");
intent_image.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent_image, "Select Image"), SELECT_IMAGE_DIALOG);
}
if(checking.equals("audio")) {
Intent intent_audio = new Intent();
intent_audio.setType("audio/*");
intent_audio.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent_audio, "Select Audio"), SELECT_AUDIO_DIALOG);
}
if(checking.equals("video")) {
Intent intent_video = new Intent();
intent_video.setType("video/*");
intent_video.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent_video, "Select Video"), SELECT_VIDEO_DIALOG);
}
}
});
public void onActivityResult(int requestCode, int resultCode, Intent result) {
// imagePath = null;
if (requestCode == SELECT_IMAGE_DIALOG) {
if (resultCode == Activity.RESULT_OK) {
Uri data = result.getData();
Log.d("DATA", data.toString());
selected_Path = getPath(data);
final_path.getBytes();
selected_path_text.setText(final_path);
Log.d("Image Path", final_path);
}
}
if (requestCode == SELECT_AUDIO_DIALOG) {
if (resultCode == RESULT_OK) {
Uri data = result.getData();
Log.d("DATA", data.toString());
selected_Path = getPath(data);
final_path.getBytes();
selected_path_text.setText(final_path);
Log.d("Audio Path", final_path);
}
}
if (requestCode == SELECT_VIDEO_DIALOG) {
if (resultCode == RESULT_OK) {
Uri data = result.getData();
Log.d("DATA", data.toString());
selected_Path = getPath(data);
final_path.getBytes();
selected_path_text.setText(final_path);
Log.d("Video Path", final_path);
}
}
}
private String getPath(Uri data) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(data, projection, null, null, null);
column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
final_path = cursor.getString(column_index);
Log.d("Image Path", final_path);
return cursor.getString(column_index);
}
Try this:
Intent i = new Intent(Intent.android.provider.MediaStore.{File type for getting path }.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_CODE);
if (requestCode == RESULT_CODE && resultCode == RESULT_OK && null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.{FILETYPE }.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
path = cursor.getString(columnIndex);
cursor.close();
}
We can do by usin ContentProviders also:
private Cursor mCursor;
if (audio) {
mUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
mCursor = mContentResolver.query(mUri, null, null, null, null);
if (mCursor != null && mCursor.moveToFirst()) {
do {
mFileName = mCursor
.getString(mCursor
.getColumnIndex(MediaStore.Audio.Media.DISPLAY_NAME));
mFilePath = mCursor
.getString(mCursor
.getColumnIndex(MediaStore.Audio.Media.DATA));
} while (mCursor.moveToNext());
}
}
if (video) {
mUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
mCursor = mContentResolver.query(mUri, null, null, null, null);
if (mCursor != null && mCursor.moveToFirst()) {
do {
mFileName = mCursor
.getString(mCursor
.getColumnIndex(MediaStore.Video.Media.DISPLAY_NAME));
mFilePath = mCursor
.getString(mCursor
.getColumnIndex(MediaStore.Video.Media.DATA));
} while (mCursor.moveToNext());
}
}
if (image) {
mUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
mCursor = mContentResolver.query(mUri, null, null, null, null);
if (mCursor != null && mCursor.moveToFirst()) {
do {
mFileName = mCursor
.getString(mCursor
.getColumnIndex(MediaStore.Images.Media.DISPLAY_NAME));
mFilePath = mCursor
.getString(mCursor
.getColumnIndex(MediaStore.Images.Media.DATA));
} while (mCursor.moveToNext());
}
}
mCursor.close();
I have this code that allows me to select file from the SDcard and upload it to server, it was working fine in an activity. Now i switched to fragment and used the same code but it's not working. What is happening is that the onActivityResult() is called and the window to select file pop-up and when I select a file, nothing happens resultCode = -1. I don't know how to fix this.
Here is the code from the onActivityResult():
public void selectFile() {
Intent intent = new Intent();
intent.setType("*/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
startActivityForResult(Intent.createChooser(intent, "Select File"), FILE_SELECT_CODE);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.i("Here ","onActivityResult");
Log.i("Here ","onActivityResult");
Log.i("resultCode ",resultCode+"");
if (resultCode == RESULT_OK) {
Log.i("Here ","onActivityResult");
if (requestCode == FILE_SELECT_CODE) {
Log.i("Here ","onActivityResult");
Uri selectedFileUri = data.getData();
String uriString = selectedFileUri.toString();
Log.i("UriString ", uriString);
File fileToUpload = new File(uriString);
if (uriString.startsWith("content://")) {
Cursor cursor = null;
try {
cursor = getActivity().getContentResolver().query(selectedFileUri, null, null, null, null);
if (cursor != null && cursor.moveToFirst()) {
uploadFileName = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
}
uploadFilePath = getPath(selectedFileUri);
Log.i("Upload File Path ", uploadFilePath);
} finally {
cursor.close();
}
} else if (uriString.startsWith("file://")) {
uploadFileName = fileToUpload.getName();
uploadFilePath = uriString.replace("file://", "");
Log.i("Upload File Path ", uploadFilePath);
}
}
}
}
private String getPath(Uri selectedFileUri) {
if (selectedFileUri == null)
return null;
String[] projection = {MediaStore.Images.Media.DATA};
Cursor cursor = getActivity().getContentResolver().query(selectedFileUri, projection, null, null, null);
if (cursor != null) {
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
return selectedFileUri.getPath();
}