File choosing error - android

I have an android application that choosing image. The file uri is obtaining correctly.
RequestBody requestFile=null;
File file=null;
String filePath=getPath(fileUri).trim(); // getting same filepath choosing via gallery or other file manager
if (fileUri!= null )
try{
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT)
file = FileUtils.getFile(getActivity(),fileUri); // neglect this line Iam using api below 19
else {
file=new File(filePath); // TODO: 30-Mar-17 CORRECT THE ERROR FOR API BELOW 19
}
String haaii="sdf";
String g=file.getAbsolutePath(); //excecuting when choosing file manager.
requestFile = RequestBody.create(
MediaType.parse(context.getContentResolver().getType(fileUri)),
file
); // weired not excecuting..null pointer expet choosing via gallery
}catch (Exception e){
Log.e("multipart",e.toString());
}
else Log.e("fileuri","uri is null");
path method
public String getPath(Uri uri) {
String path = null;
String[] projection = { MediaStore.Files.FileColumns.DATA };
Cursor cursor = getActivity().getContentResolver().query(uri, projection, null, null, null);
if(cursor == null){
path = uri.getPath();
}
else{
cursor.moveToFirst();
int column_index = cursor.getColumnIndexOrThrow(projection[0]);
path = cursor.getString(column_index);
cursor.close();
}
return ((path == null || path.isEmpty()) ? (uri.getPath()) : path);
}
choosing file
Intent intent = new Intent();
// Show only images, no videos or anything else
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
// Always show the chooser (if there are multiple options available)
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
result is obtained using
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
uri = data.getData();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), uri);
// Log.d(TAG, String.valueOf(bitmap));
photo.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
When choosing via file manager -getting error
E/multipart: java.lang.NullPointerException
when choosing via gallery -ok
But the error is strange. When choosing via gallery it is okay. But when using the file manager getting null pointer exception. But string value filePath is same when choosing via file manager or gallery. How to solve this?. But when I remove try catch block the null pointer exception is not showing, but the next line is not executing..

Related

Path of selected image is null

I am trying to get the real path of a URI.
First I start the gallery app through an intent:
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select picture"), SELECT_IMAGE );
After that the onActivityResult gets called, where I try to get the absolut path of the URI.
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
if (resultCode == RESULT_OK) {
Uri uri;
if (requestCode == SELECT_IMAGE) {
final Uri uri_data = data.getData();
// Get the path from the Uri
final String path = getPathFromURI(uri_data);
if (path != null) {
File f = new File(path);
uri = Uri.fromFile(f);
}
}
}
} catch (Exception e) {
Log.e("FileSelectorActivity", "File select error", e);
}
}
The uri_data contains "content://com.android.providers.media.documents/document/image%3A67", but the resulting path is null.
The pathFromUri method looks like this:
private String getPathFromURI(Uri contentUri) {
String res = null;
String[] proj = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(contentUri, proj, null, null, null);
if (cursor.moveToFirst()) {
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
res = cursor.getString(column_index);
}
cursor.close();
return res;
}
Here the column_index is 0, but cursor.getString returns null.
Why does this happen?
I have the permission android.permission.READ_EXTERNAL_STORAGE
EDIT:
So I want to take a picture through the camera app, and the user then chooses the image. So the file should be acutally stored on the phone (which is, since I am testing it on my phone)
EDIT:
Okey, the solution was to request the permissions at runtime...sorry guys

How can I get the path from a file

I'm making an App where I call the file explorer, the when I choose a file i get the name with file.getName() and put it in a TextView and get the path with file..getPath() and save it in a String, this String I use it to attach the file into a mail... my problem is that when a choose a file like .PDF, .DOC, .DOCX, .MP3 I can attach it but when a select an image I get this kind of path: "/media/external/images/media/1220" and does not attach anithing, I've been serarching everywhere and use almost every option I have found with no result.
Here is my code:
private void PickFile(View v) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");
startActivityForResult(intent, PICKER);
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if ((resultCode == RESULT_OK) && (requestCode == PICKER)) {
String FilePath = data.getData().getPath();
File file = new File(FilePath);
}
if (txtAdjunto1.getText() == "_") {
adjunto1 = file.getPath();// I get the path to add it to the MimeBodyPart
txtAdjunto1.setText(file.getName());// I put the name in the TextView
I've been trying this:
public String getRealPathFromURI(Uri contentUri) {
Cursor cursor = null;
int column_index;
String ruta = null;
try {
String[] proj = { MediaStore.Images.Media.DATA };
cursor = getContentResolver().query(contentUri, proj, null, null, null);
if (cursor != null){
column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
ruta = cursor.getString(column_index);
}
return ruta;
} finally {
if (cursor != null) {
cursor.close();
}
}
But the app crashes when I pick the file.
Also tried this:
file = new File(file.getAbsolutePath());
But still geting this "/media/external/images/media/1220"...
Hop someone can help me with this, and thanks in advance
ACTION_GET_CONTENT and ACTION_OPEN_DOCUMENT allow the user to choose a piece of content. That content might be a local file. That content might also be:
Something on a file server on the network
Something in a cloud storage service, such as Google Drive
Something in an encrypted volume
Something that is a file, but is not a file that you can access directly
And so on
You have two main options. If you only want files, then use a third-party file chooser library to replace all of the code in your question.
Or, you can take the Uri that you get from data.getData() in onActivityResult() and do two things with it:
First, use DocumentFile.fromSingleUri() to get a DocumentFile object pointing to that Uri. You can call getName() on the DocumentFile to get a "display name" for the content, which should be something that the user will recognize.
Then, use a ContentResolver and openInputStream() to get at the content itself, similar to how you might use a FileInputStream to get at the bytes in a file.
Try this...
The following code is to select any type of file from file manager and camera then convert to byte array and attach file make edit as per your requirement
private void selectFile() {
final CharSequence[] items = {"Camera", "Choose from File Manager",
"Cancel"};
AlertDialog.Builder builder = new AlertDialog.Builder(ComposeActivity.this);
builder.setTitle("Add Attachment!");
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
boolean result = Constant.checkPermission(ComposeActivity.this);
if (items[item].equals("Camera")) {
userChoosenTask = "Camera";//String
if (result)
cameraIntent();
} else if (items[item].equals("Choose from File Manager")) {
userChoosenTask = "Choose from File Manager";//String
if (result) {
FileManagerIntent();
}
} else if (items[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
to call camera
private void cameraIntent() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_CAMERA);
}
file from file manager
private void FileManagerIntent() {
try {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");
startActivityForResult(Intent.createChooser(intent, "Select File"), 111);
} catch (Exception e) {
// Handle exceptions here
e.printStackTrace();
}
}
results
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == SELECT_FILE)
onSelectFromGalleryResult(data);
else if (requestCode == REQUEST_CAMERA)
onCaptureImageResult(data);
}
}
getting camera result and converting it to bytearray
private void onCaptureImageResult(Intent data) {
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");
Uri uri = Uri.fromFile(destination);
String uriString = uri.toString();
String path = destination.getAbsolutePath();
if (uriString.startsWith("content://")) {
Cursor cursor = null;
try {
cursor = ComposeActivity.this.getContentResolver().query(uri, null, null, null, null);
if (cursor != null && cursor.moveToFirst()) {
strFileName = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
}
} finally {
cursor.close();
}
} else if (uriString.startsWith("file://")) {
strFileName = destination.getName();
}
attachLayout.setVisibility(View.VISIBLE);
txtFileName.setText(strFileName);
try {
fileByteArray = bytes.toByteArray();
strFile = Base64.encodeToString(fileByteArray, Base64.DEFAULT);
Log.v("Soma", strFile);
Log.v("Byte Array * ", strFile);
} catch (Exception e) {
e.printStackTrace();
}
}
result from file manager
private void onSelectFromGalleryResult(Intent data) {
Uri uri = data.getData();
if (uri.toString().contains("video") || uri.toString().contains("audio")) {
Toast.makeText(ComposeActivity.this, "Oops! can't send video/audio file", Toast.LENGTH_SHORT).show();
} else {
String uriString = uri.toString();
File myFile = new File(uriString);
String path = myFile.getAbsolutePath();
if (uriString.startsWith("content://")) {
Cursor cursor = null;
try {
cursor = ComposeActivity.this.getContentResolver().query(uri, null, null, null, null);
if (cursor != null && cursor.moveToFirst()) {
strFileName = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
}
} finally {
cursor.close();
}
} else if (uriString.startsWith("file://")) {
strFileName = myFile.getName();
}
Log.v("Super DisplayName", strFileName);
attachLayout.setVisibility(View.VISIBLE);
txtFileName.setText(strFileName);
try {
InputStream iStream = getContentResolver().openInputStream(uri);
fileByteArray = getBytes(iStream);
strFile = Base64.encodeToString(fileByteArray, Base64.DEFAULT);
Log.v("Byte Array * ", strFile);
} catch (Exception e) {
e.printStackTrace();
}
}
}
file to bytearray
public byte[] getBytes(InputStream inputStream) throws IOException {
ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int len = 0;
while ((len = inputStream.read(buffer)) != -1) {
byteBuffer.write(buffer, 0, len);
}
return byteBuffer.toByteArray();
}

how to get a real path of PDF file in android

we want to choose a pdf file using intent from a gallery so how can get a real path of a pdf file. We want to choose a PDF file from a gallery and upload this file on a server.
public String getPathFromURI(Context context, Uri contentUri) {
if ( contentUri.toString().indexOf("file:///") > -1 ){
return contentUri.getPath();
}
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();
}
}
}
Hi here is sample code for selecting pdf file from external storage and get file's path using which you can access file's data and upload data on your server.
Here PICK_IMAGE is any number you want as your request code.
Intent intent = new Intent();
intent.setType("application/pdf");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select File"),PICK_IMAGE);
public void onActivityResult(int requestCode, int resultCode, final Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE) {
try {
Uri uri1 = data.getData();
String path = String.valueOf(uri1);
String path_lastPart = path.substring(path.indexOf("/storage"));
if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
// Do the file write
path_lastPart = path_lastPart.replace("%20", " ");
File yourFile = new File(path_lastPart);
} else {
// Request permission from the user
ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 0);
}
} catch (Exception e2) {
Log.e("macro", "" + e2);
}
}
}

how to delete an image from android when its URI is known?

Im developing an android app which selects an image from the gallery in one activity and displays it in another.But when I try to delete the selected image it doesnt delete.I'm passing its uri between the two activies. Many thanks in Advance!!!!
Here's my Code :
ACTIVITY HOMESCREEN
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
Uri uri = data.getData();
Intent i = new Intent(this, Imageviewer.class);
i.putExtra("imgpath", uri.toString());
startActivity(i);
}
}
IMAGEVIEWER ACTIVITY :
Uri imageUri;
imageUri = Uri.parse(intent.getStringExtra("imgpath"));
File fdelete = new File(imageUri.toString());
if (fdelete.exists()) {
if (fdelete.delete()) {
System.out.println("file Deleted :" );
} else {
System.out.println("file not Deleted :");
}
}
First you must take real path of image:
//getting real path from uri
private String getFilePath(Uri uri) {
String[] projection = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(projection[0]);
String picturePath = cursor.getString(columnIndex); // returns null
cursor.close();
return picturePath;
}
return null;
}
Then you can delete this file like below:
Uri imageUri;
imageUri = Uri.parse(intent.getStringExtra("imgpath"));
File fdelete = new File(getFilePath(imageUri));
if (fdelete.exists()) {
if (fdelete.delete()) {
System.out.println("file Deleted :" );
} else {
System.out.println("file not Deleted :");
}
}
Try this : (In the second Activity) ImageViewerActivity in your case.
Intent intent = getIntent();
String receivedPath = intent.getExtras().getString("imgpath");
File fdelete = new File(receivedPath);
if (fdelete.exists()) {
if (fdelete.delete()) {
System.out.println("file Deleted :" );
} else {
System.out.println("file not Deleted :");
}
}
Also you can debug your codes line by line to see and check if the ImgPath is getting correctly or not!
With kotlin you could do: uri.toFile().delete() and its deleted

Android FilePicker dialog only working for some devices

I'm using the regular boiler-plate code for showing the File Picker dialog on android. After I get a file path, I'm uploading that file to my server using aQuery.
However, the code is only working on my old samsung phone that runs on Android 4.1.2 but not on any other devices. I tested it using many devices but it works only on Samsung devices with JellyBean.
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType(minmeType);
intent.addCategory(Intent.CATEGORY_OPENABLE);
// special intent for Samsung file manager
Intent sIntent = new Intent("com.sec.android.app.myfiles.PICK_DATA");
// if you want any file type, you can skip next line
sIntent.putExtra("CONTENT_TYPE", minmeType);
sIntent.addCategory(Intent.CATEGORY_DEFAULT);
Intent chooserIntent;
if (getPackageManager().resolveActivity(sIntent, 0) != null) {
// it is device with samsung file manager
chooserIntent = Intent.createChooser(sIntent, "Open file");
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[]{intent});
} else {
chooserIntent = Intent.createChooser(intent, "Open file");
}
try {
startActivityForResult(chooserIntent, PICKFILE_REQUEST_CODE);
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(getApplicationContext(), "No suitable File Manager was found.\nPlease download a File Manager and try again.", Toast.LENGTH_LONG).show();
}
The onActivityResult code is:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (data != null) {
fPath = data.getDataString();
File file = new File(fPath.substring(7));
params.put("file" + noFilesAttached, file);
noFilesAttached = noFilesAttached + 1;
path.setText(noFilesAttached + " files attached ");
upload.setText("Upload (" + noFilesAttached + ")");
upload.setVisibility(View.VISIBLE);
isUploaded = false;
}
super.onActivityResult(requestCode, resultCode, data);
}
I tried editing the fPath.substring(7) to fpath with no success, and I don't want to use any third-party libraries.
Thanks in advance.
Data.getData() return a uri;
U need a filepath;
Try to find way to transform uri to filepath:
Possibly:
public static String getRealFilePath( final Context context, final Uri uri ) {
if ( null == uri ) return null;
final String scheme = uri.getScheme();
String data = null;
if ( scheme == null )
data = uri.getPath();
else if ( ContentResolver.SCHEME_FILE.equals( scheme ) ) {
data = uri.getPath();
} else if ( ContentResolver.SCHEME_CONTENT.equals( scheme ) ) {
Cursor cursor = context.getContentResolver().query( uri, new String[] { ImageColumns.DATA }, null, null, null );
if ( null != cursor ) {
if ( cursor.moveToFirst() ) {
int index = cursor.getColumnIndex( ImageColumns.DATA );
if ( index > -1 ) {
data = cursor.getString( index );
}
}
cursor.close();
}
}
return data;
}
Try using this library
This library might fix your requirement.

Categories

Resources