I'm not able to pick pdf file from internal storage, external storage, recent or google sheet.
Intent intent = new Intent("com.sec.android.app.myfiles.PICK_DATA");
intent.putExtra("CONTENT_TYPE", "application/pdf");
intent.addCategory(Intent.CATEGORY_DEFAULT);
startActivityForResult(intent, FILE_SELECT_CODE);
Try this,
private static final int PICK_FILE = 101;
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("application/pdf");
intent.addCategory(Intent.CATEGORY_OPENABLE);
try {
startActivityForResult(Intent.createChooser(intent, "Select a File"), PICK_FILE);
} catch (android.content.ActivityNotFoundException ex) {
// Potentially direct the user to the Market with a Dialog
Toast.makeText(this, "Please install a File Manager.",
Toast.LENGTH_SHORT).show();
}
onActivityResult:
#Override
public void onActivityResult(int reqCode, int resultCode, Intent data) {
super.onActivityResult(reqCode, resultCode, data);
switch (reqCode) {
case PICK_FILE:
if (resultCode == RESULT_OK) {
// Get the Uri of the selected file
Uri uri = data.getData();
// Get the path
String path = getPath(mContext, uri);
Log.d(TAG, "Path: " + path);
if (path != null && path.contains(".pdf")) {
}
}
break;
}
}
getPath:
public String getPath(Context context, Uri uri) {
if ("content".equalsIgnoreCase(uri.getScheme())) {
String[] projection = {"_data"};
Cursor cursor;
try {
cursor = context.getContentResolver().query(uri, projection, null, null, null);
assert cursor != null;
int column_index = cursor.getColumnIndexOrThrow("_data");
if (cursor.moveToFirst()) {
return cursor.getString(column_index);
}
cursor.close();
} catch (Exception e) {
// Eat it
}
} else if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}
return null;
}
You can use Intent.ACTION_OPEN_DOCUMENT,
Each document is represented as a content:// URI backed by a DocumentsProvider, which can be opened as a stream with openFileDescriptor(Uri, String), or queried for DocumentsContract.Document metadata.
All selected documents are returned to the calling application with persistable read and write permission grants. If you want to maintain access to the documents across device reboots, you need to explicitly take the persistable permissions using takePersistableUriPermission(Uri, int).
Callers must indicate the acceptable document MIME types through setType(String). For example, to select photos, use image/*. If multiple disjoint MIME types are acceptable, define them in EXTRA_MIME_TYPES and setType(String) to /.
For the more details, please refer this link
Note that above mentioned is only available on API Level 19+.
Have a look at this also, how to pick few type of file via intent in android?
Related
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
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);
}
}
}
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..
I am trying to get the Path from an image to send it later to a server. The problem is when I try to get it, my code doesn't work (you will see there is an extra }. That is because the code from the OnCreate ends and then I worte the other functions):
enviar.setOnClickListener(new View.OnClickListener() {
String datos="";
//Bundle extras=getIntent().getExtras();
#Override
public void onClick(View view) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(intent, 0);
//Uri imagen=intent.getData();
//datos=imagen.getPath();
//mostrar.setText(datos);
}
});
}
private String getRealPathFromURI(Uri contentURI) {
String result;
Cursor cursor = getContentResolver().query(contentURI, null, null, null, null);
if (cursor == null) {
result = contentURI.getPath();
} else {
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
result = cursor.getString(idx);
cursor.close();
}
return result;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
switch(requestCode) {
case 0:
if(resultCode == this.RESULT_OK){
try {
final Uri imageUri = imageReturnedIntent.getData();
String path = getRealPathFromURI(imageUri);
mostrar.setText(path);
}
catch (Exception e) {
Log.e("Erroreeeee: ", e.getMessage());
}
}
break;
}
}
You have two problems.
The first one is that startActivityForResult() is not immediate. You do not have any results in the next statement.
So, you are welcome to call startActivityForResult(), as I do in this sample app:
private void get() {
Intent i=
new Intent()
.setType("image/png")
.setAction(Intent.ACTION_GET_CONTENT)
.addCategory(Intent.CATEGORY_OPENABLE);
startActivityForResult(i, REQUEST_GET);
}
Your results are delivered to onActivityResult():
#Override
public void onActivityResult(int requestCode, int resultCode,
Intent resultData) {
if (resultCode==Activity.RESULT_OK) {
Uri image=resultData.getData();
// do something
}
}
Your second problem is that you are thinking that you are picking a file. You are not. You are picking a piece of content, using any activity that the user decides to have handle ACTION_GET_CONTENT. getPath() only has meaning if the scheme of the Uri is file, and that is rather unlikely. There is no reliable means of getting a filesystem path for an arbitrary Uri, for the simple reason that the Uri does not have to point to a file.
Ideally, your "upload to a server" logic can work with an InputStream. In that case, call openInputStream() on a ContentResolver to get an InputStream on the content identified by the Uri. If your "upload to a server" logic only works with files, use that InputStream to copy the content to some temporary file that you control (e.g., in getCacheDir()), then use that temporary file for your upload. Delete the temporary file when you are done with it.
I have an application which is running on desktop fine .There is one button on my desktop app in which it open the gallary select image.
But when I run that app on webview what will happen when I clcik that button .? will it open our mobile image gallary .?
I created a small open source Android Library Project that streamlines this process, while also providing a built-in file explorer (in case the user does not have one present). It's extremely simple to use, requiring only a few lines of code.
You can find it at GitHub: aFileChooser.
If you want the user to be able to choose any file in the system, you will need to include your own file manager, or advise the user to download one. I believe the best you can do is look for "openable" content in an Intent.createChooser() like this:
private static final int FILE_SELECT_CODE = 0;
private void showFileChooser() {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");
intent.addCategory(Intent.CATEGORY_OPENABLE);
try {
startActivityForResult(
Intent.createChooser(intent, "Select a File to Upload"),
FILE_SELECT_CODE);
} catch (android.content.ActivityNotFoundException ex) {
// Potentially direct the user to the Market with a Dialog
Toast.makeText(this, "Please install a File Manager.",
Toast.LENGTH_SHORT).show();
}
}
You would then listen for the selected file's Uri in onActivityResult() like so:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case FILE_SELECT_CODE:
if (resultCode == RESULT_OK) {
// Get the Uri of the selected file
Uri uri = data.getData();
Log.d(TAG, "File Uri: " + uri.toString());
// Get the path
String path = FileUtils.getPath(this, uri);
Log.d(TAG, "File Path: " + path);
// Get the file instance
// File file = new File(path);
// Initiate the upload
}
break;
}
super.onActivityResult(requestCode, resultCode, data);
}
The getPath() method in my FileUtils.java is:
public static String getPath(Context context, Uri uri) throws URISyntaxException {
if ("content".equalsIgnoreCase(uri.getScheme())) {
String[] projection = { "_data" };
Cursor cursor = null;
try {
cursor = context.getContentResolver().query(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow("_data");
if (cursor.moveToFirst()) {
return cursor.getString(column_index);
}
} catch (Exception e) {
// Eat it
}
}
else if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}
return null;
}