onActivityResult return resultCode = -1 - android

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();
}

Related

how to select image from Device and it's path in android Studio

I need to select image from device and it's full path
But I get null value.. this is my Code
any suggestions
private void openPicture() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,
"Select Picture"), SELECT_PICTURE);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_PICTURE) {
Uri selectedImageUri = data.getData();
String selectedImagePath = getPath(selectedImageUri);
Toast.makeText(this, ""+selectedImagePath, Toast.LENGTH_SHORT).show();
}
}
}
public String getPath(Uri uri) {
if( uri == null ) {
return null;
}
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
if( cursor != null ){
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String path = cursor.getString(column_index);
cursor.close();
return path;
}
return uri.getPath();
}
it's return Null value. I need selected image Path.

Image path null in Android

I have code like this, the problem is when i want to save it to sqlite, the error message shown that i got null in image path.
Here is the main activity
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_PICTURE) {
Uri selectedImageUri = data.getData();
System.out.println("Data Image : "+selectedImageUri);
selectedImagePath = getPath(selectedImageUri);
System.out.println("Image Path : " + selectedImagePath);
image1.setVisibility(View.VISIBLE);
image1.setImageURI(selectedImageUri);
}
}
}
private String getRealPathFromURI(Uri contentURI) {
String result;
Cursor cursor = getContentResolver().query(contentURI, null, null, null, null);
if (cursor == null) { // Source is Dropbox or other similar local file path
result = contentURI.getPath();
} else {
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
result = cursor.getString(idx);
cursor.close();
}
return result;
}
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
I use this method to take photos from camera.
private void capturePhoto() {
// save this Uri in a field variable.
uri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
new ContentValues());
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
startActivityForResult(intent, CAMERA_REQUEST);
}
then onActivityResult will look like this:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK){
// use the field Uri, it now points to the path to the image taken from the camera.
}
}
In manifest file set permission
Check permission granted in onActivityResult method and after its granted READ_EXTERNAL_STORAGE
If it has Permission then call doCreatePath() and set the same in onRequestPermissionsResult on permission granted.
void doCreatePath()
{
try {
Uri originalUri = filePath;
String pathsegment[] = originalUri.getLastPathSegment().split(":");
String id = pathsegment[0];
final String[] imageColumns = {MediaStore.Images.Media.DATA};
final String imageOrderBy = null;
Uri uri = getUri();
Cursor imageCursor = getActivity().getContentResolver().query(uri, imageColumns,
null, null, null);
if (imageCursor.moveToFirst()) {
int column_index_data = imageCursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
realPath = imageCursor.getString(column_index_data);
System.out.print("value" + realPath);
}
} catch (Exception e) {
e.printStackTrace();
}
}
It works!.

How to get path from SDcard in android for audio, video, image, files?

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();

How to get any File Path ,Name ,Extension from onActivityResult?

My Codes are:
1.
File file = new File(Environment.getExternalStorageDirectory(),"myFolder");
Log.d("path", file.toString());
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setDataAndType(Uri.fromFile(file), "*/*");
startActivityForResult(intent,0);
2.
#Override
protected void onActivityResult(int requestCode,
int resultCode, Intent FileReturnedIntent) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, FileReturnedIntent);
How to get the file path,name,extension? (suppose files are in doc,pdf,csv format)
It return the file extention like pdf, doc .. etc
public static String getMimeType(Context context, Uri uri) {
String extension;
if (uri.getScheme().equals(ContentResolver.SCHEME_CONTENT)) {
final MimeTypeMap mime = MimeTypeMap.getSingleton();
extension = mime.getExtensionFromMimeType(context.getContentResolver().getType(uri));
} else {
extension = MimeTypeMap.getFileExtensionFromUrl(Uri.fromFile(new File(uri.getPath())).toString());
}
return extension;
}
It returns you the real path where you get the file name. One friend use this way and it is really useful.
Get filename and path from URI from mediastore
public String getRealPathFromURI(Context context, Uri contentUri) {
Cursor cursor = null;
try {
String[] proj = { MediaStore.Images.Media.DATA };
cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} finally {
if (cursor != null) {
cursor.close();
}
}
}
You get file name from this
public String getFileName(Uri uri) {
String result = null;
if (uri.getScheme().equals("content")) {
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
try {
if (cursor != null && cursor.moveToFirst()) {
result = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
}
} finally {
cursor.close();
}
}
if (result == null) {
result = uri.getPath();
int cut = result.lastIndexOf('/');
if (cut != -1) {
result = result.substring(cut + 1);
}
}
return result;
}
I am late but it can help others here is the solution.
Uri uri = data.getData();
ContentResolver cr = this.getContentResolver();
String mime = cr.getType(uri);
you can use like this
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data)
{
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
}
}
Once try as follows if the FileReturnedIntent contains File as extras
Bundle data1=FileReturnedIntent.getExtras();
File f=(File)data1.get(key);
String path=f.getAbsolutePath();
System.out.println("The file path along with extension is : "+path);
Hope this will helps you.
Nova day in Kotlin:
val myFile = File(data?.data!!.path)
you can put String Extra to intent using
intent.putExtra("path", your_path);
and get it in onActivityResult by
FileReturnedIntent.getStringExtra("path");

Xamarin Choose Image From Gallery Path is Null

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;
}

Categories

Resources