I want to implement file chooser with camera option.When we select Camera images should be captured and the path of captured image should displayed on textview.and file chooser should be with pdf,word,png and jpeg validation. I tired fileChhoser only but I dont Understand how to implement camera option in that.
The code i have used
ActivityResultLauncher<Intent> sActivityResultLauncher = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
#SuppressLint("Range")
#Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode()== Activity.RESULT_OK){
Intent data = result.getData();
Intent data1 = result.getData();
Uri uri = data.getData();
Uri uri1 = data1.getData();
String uriString = uri.toString();
String uriString1 = uri1.toString();
File myFile = new File(uriString1);
String path = myFile.getAbsolutePath();
String displayName = null;
String displayName1= null;
if (uriString.startsWith("content://")) {
Cursor cursor = null;
try {
cursor = getApplicationContext().getContentResolver().query(uri, null, null, null, null);
if (cursor != null && cursor.moveToFirst()) {
displayName = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
// displayName1 = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
Log.i("displayname",""+displayName);
fileidname.setText(displayName);
}
} finally {
cursor.close();
}
} else if (uriString.startsWith("file://")) {
displayName = myFile.getName();
// displayName1= myFile.getName();
Log.i("displayname1",""+displayName);
fileidname.setText(displayName);
}
}
}
}
);
ActivityResultLauncher<Intent> sActivityResultLauncher1 = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
#SuppressLint("Range")
#Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode()== Activity.RESULT_OK){
//Intent data = result.getData();
Intent data1 = result.getData();
// Uri uri = data.getData();
Uri uri1 = data1.getData();
// String uriString = uri.toString();
String uriString1 = uri1.toString();
File myFile = new File(uriString1);
String path = myFile.getAbsolutePath();
String displayName = null;
String displayName1= null;
if (uriString1.startsWith("content://")) {
Cursor cursor = null;
try {
cursor = getApplicationContext().getContentResolver().query(uri1, null, null, null, null);
if (cursor != null && cursor.moveToFirst()) {
// displayName = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
displayName1 = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
Log.i("displayname",""+displayName);
fileidname1.setText(displayName1);
}
} finally {
cursor.close();
}
} else if (uriString1.startsWith("file://")) {
//displayName = myFile.getName();
displayName1= myFile.getName();
Log.i("displayname1",""+displayName);
fileidname1.setText(displayName1);
}
}
}
}
);
public void OpenfileDialog(View view) {
Intent data = new Intent(Intent.ACTION_OPEN_DOCUMENT);
data.setType("*/*");
String[] mimeTypes = {"image/*","application/pdf"};
data.putExtra(Intent.EXTRA_MIME_TYPES,mimeTypes);
data = Intent.createChooser(data,"Choose a file");
sActivityResultLauncher.launch(data);
}
public void OpenfileDialog1(View view) {
Intent data = new Intent(Intent.ACTION_OPEN_DOCUMENT);
data.setType("*/*");
String[] mimeTypes = {"image/*","application/pdf"};
data.putExtra(Intent.EXTRA_MIME_TYPES,mimeTypes);
data = Intent.createChooser(data,"Choose a file");
sActivityResultLauncher1.launch(data);
}
Related
public static String getRealPath(Uri uri, Context context) {
File file = new File(uri.getPath());
String[] filePath = file.getPath().split(":");
String fileId = filePath[filePath.length - 1];
Cursor cursor = context.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
null,
MediaStore.Images.Media._ID + " = ? ",
new String[]{fileId},
null);
if (cursor != null) {
cursor.moveToNext();
int columnIndex = cursor.getColumnIndex(MediaStore.MediaColumns.DATA);
String realPath = cursor.getString(columnIndex);
cursor.close();
return realPath;
}
return null;
}
this is My code ( uri to path )
When bringing up an image, it brings the absolute path well. But when I call the file, I can't call it.
When i called file Like this..
Intent fileChoose = new Intent(Intent.ACTION_OPEN_DOCUMENT);
fileChoose.setType("*/*");
fileChoose.setAction(Intent.ACTION_GET_CONTENT);
fileLauncher.launch(fileChoose);
and Receive Like this..
private final ActivityResultLauncher<Intent> fileLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback<ActivityResult>() {
#Override
public void onActivityResult(ActivityResult result) {
if (result != null) {
if (result.getData() != null) {
File file = new File(Objects.requireNonNull(CommFunc.getRealPath(result.getData().getData(), FileChooserActivity.this)));
}
}
}
});
and i called Image Like this..
Intent galleryIntent = new Intent();
galleryIntent.setType("image/*");
galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
setResult(RESULT_OK, galleryIntent);
galleryLauncher.launch(Intent.createChooser(galleryIntent, "Select Picture"));
When i press in "addnew" button, the app crash.
The problem is in this part of code:
Boton cbt = new Boton(bt, "","");
listBts.add(cbt);
SharedPreferences sharedPreferences = getSharedPreferences("Array", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
Gson gson = new Gson();
Type type = new TypeToken<BotonClass>() {
}.getType();
String json = gson.toJson(listBts);
editor.remove("Botones").commit();
editor.putString("Botones", json);
editor.commit();
ALL THE CODE:
public class MainActivity extends AppCompatActivity {
MediaPlayer mediaPlayer;
String Tag;
FlexboxLayout fl;
int w;
int h;
ImageView im;
Button curBt;
Boolean delete;
class Boton{
Button bt;
String path;
String fname;
Boton(Button bt, String path, String fname){
this.bt = bt;
this.path = path;
this.fname = fname;
}
}
ArrayList<Boton> listBts;
ArrayList<BotonClass> listClass;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Chequear_Permisos();
listBts = new ArrayList<>();
listClass = new ArrayList<>();
fl = findViewById(R.id.fl);
DisplayMetrics dm = this.getResources().getDisplayMetrics();
w = Math.round(dm.widthPixels);
h = Math.round(dm.heightPixels);
cargar_bts_agregados();
im = findViewById(R.id.im);
im.getLayoutParams().width = w;
im.getLayoutParams().height = w/3;
}
void cargar_bts_agregados() {
SharedPreferences sharedPreferences = getSharedPreferences("Array", MODE_PRIVATE);
class Boton{
Button bt;
String path;
String fname;
}
Type type = new TypeToken<List<Boton>>() {
}.getType();
String json = sharedPreferences.getString("Botones", "");
Gson gson = new Gson();
if(gson.fromJson(json,type)!= null)
listBts = gson.fromJson(json, type);
if (listBts != null)
for (int i = 0; i < listBts.size(); i++) {
}
}
void Chequear_Permisos(){
if(ContextCompat.checkSelfPermission(MainActivity.this,
Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED)
ActivityCompat.requestPermissions(MainActivity.this, new String[] {Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
if(ContextCompat.checkSelfPermission(MainActivity.this,
Manifest.permission.MANAGE_DOCUMENTS) != PackageManager.PERMISSION_GRANTED)
ActivityCompat.requestPermissions(MainActivity.this, new String[] {Manifest.permission.MANAGE_DOCUMENTS}, 1);
}
void config_bt(Button bt, String path, String fname){
bt.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
cargar_cancion(v);
return true;
}
});
bt.getLayoutParams().width = w/2;
bt.getLayoutParams().height = (w/2)/2;
if(fname != "")
bt.setText(fname);
}
public void cargar_cancion(View v){
Tag = v.getTag().toString();
curBt = (Button)v;
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");
intent.addCategory(Intent.CATEGORY_OPENABLE);
startActivityForResult(Intent.createChooser(intent,"Select file or dir"), 1);
setResult(Activity.RESULT_OK);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1 && resultCode == Activity.RESULT_OK) {
class Boton{
Button bt;
String path;
String fname;
}
String path = data.getDataString();
String fname = getFileName(Uri.parse(path));
curBt.setText(fname);
Boton b = new Boton();
/*
b.bt = curBt;
b.path = path;
b.fname = fname;*/
//////lb.get(curBt.getId()).path = path;
//////lb.get(curBt.getId()).fname = fname;
SharedPreferences sharedPreferences = getSharedPreferences("Array", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
Gson gson = new Gson();
String json = gson.toJson(listBts);
editor.putString("Botones", json);
editor.commit();
}
}
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
public void play(View v){
/*if(Integer.parseInt(v.getTag().toString()) > 8 && delete == true){
String pos = v.getTag().toString();
SharedPreferences shPaths = getSharedPreferences("Paths", MODE_PRIVATE);
SharedPreferences.Editor editPath = shPaths.edit();
SharedPreferences shBts = getSharedPreferences("BtNames", MODE_PRIVATE);
SharedPreferences.Editor editorBts = shBts.edit();
editPath.putString(pos, "deleted");
editorBts.putString(pos, "deleted");
editorBts.commit();
editPath.commit();
Log.d("MESAJE", v.getTag().toString());
Log.d("MESAJE", shPaths.getString(String.valueOf(v.getTag().toString()), "_"));
FlexboxLayout fl = findViewById(R.id.fl);
fl.removeView(v);
delete = false;
}*/
SharedPreferences sharedPreferences = getSharedPreferences("Paths", MODE_PRIVATE);
String filePath = sharedPreferences.getString(v.getTag().toString(), "");
Uri uri = Uri.parse(filePath);
mediaPlayer = new MediaPlayer();
try {
mediaPlayer.setDataSource(getRealPathFromURI_API19(this, Uri.parse(filePath)));
mediaPlayer.prepare();
mediaPlayer.start();
Button bt = (Button) v;
bt.setText(getFileName(uri));
} catch (IOException e) {
e.printStackTrace();
//Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
}
catch (Exception e){
//Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
}
}
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;
}
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
public static String getRealPathFromURI_API19(Context context, Uri uri) {
String filePath = "";
// ExternalStorageProvider
if (isExternalStorageDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
if ("primary".equalsIgnoreCase(type)) {
return Environment.getExternalStorageDirectory() + "/" + split[1];
} else {
if (Build.VERSION.SDK_INT > 20) {
//getExternalMediaDirs() added in API 21
File extenal[] = context.getExternalMediaDirs();
if (extenal.length > 1) {
filePath = extenal[1].getAbsolutePath();
filePath = filePath.substring(0, filePath.indexOf("Android")) + split[1];
}
}else{
filePath = "/storage/" + type + "/" + split[1];
}
return filePath;
}
} else if (isDownloadsDocument(uri)) {
// DownloadsProvider
final String id = DocumentsContract.getDocumentId(uri);
//final Uri contentUri = ContentUris.withAppendedId(
// Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
Cursor cursor = null;
final String column = "_data";
final String[] projection = {column};
try {
cursor = context.getContentResolver().query(uri, projection, null, null, null);
if (cursor != null && cursor.moveToFirst()) {
final int index = cursor.getColumnIndexOrThrow(column);
String result = cursor.getString(index);
cursor.close();
return result;
}
} finally {
if (cursor != null)
cursor.close();
}
} else if (DocumentsContract.isDocumentUri(context, uri)) {
// MediaProvider
String wholeID = DocumentsContract.getDocumentId(uri);
// Split at colon, use second item in the array
String[] ids = wholeID.split(":");
String id;
String type;
if (ids.length > 1) {
id = ids[1];
type = ids[0];
} else {
id = ids[0];
type = ids[0];
}
Uri contentUri = null;
if ("image".equals(type)) {
contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
} else if ("video".equals(type)) {
contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
} else if ("audio".equals(type)) {
contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
}
final String selection = "_id=?";
final String[] selectionArgs = new String[]{id};
final String column = "_data";
final String[] projection = {column};
Cursor cursor = context.getContentResolver().query(contentUri,
projection, selection, selectionArgs, null);
if (cursor != null) {
int columnIndex = cursor.getColumnIndex(column);
if (cursor.moveToFirst()) {
filePath = cursor.getString(columnIndex);
}
cursor.close();
}
return filePath;
} else {
String[] proj = {MediaStore.Audio.Media.DATA};
Cursor cursor = context.getContentResolver().query(uri, proj, null, null, null);
if (cursor != null) {
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA);
if (cursor.moveToFirst())
filePath = cursor.getString(column_index);
cursor.close();
}
return filePath;
}
return null;
}
public static boolean isExternalStorageDocument(Uri uri) {
return "com.android.externalstorage.documents".equals(uri.getAuthority());
}
public static boolean isDownloadsDocument(Uri uri) {
return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}
public void addnew(Button bt, String fname, String path) {
fl.addView(bt);
config_bt(bt, fname, path);
}
public void addnew(View v){
if(listBts == null)
Log.d("MESAJE", "MMMMMMM");
final Button bt = new Button(this);
bt.setText("Cargar");
bt.setOnClickListener(new View.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
public void onClick(View v) {
play(bt);
}
});
bt.setTag(contar_bts());
fl.addView(bt);
/*
BotonClass bbc = new BotonClass(bt, "","");
listClass.add(bbc);
listClass.get(0);
cbt.bt = bt;
cbt.path = "";
cbt.fname = "";*/
Boton cbt = new Boton(bt, "","");
listBts.add(cbt);
SharedPreferences sharedPreferences = getSharedPreferences("Array", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
Gson gson = new Gson();
Type type = new TypeToken<BotonClass>() {
}.getType();
String json = gson.toJson(listBts);
editor.remove("Botones").commit();
editor.putString("Botones", json);
editor.commit();
config_bt(bt,"","");
}
public int contar_bts(){
if(listBts == null || listBts.size() == 0)
return 0;
int c =Integer.parseInt(listBts.get(listBts.size()-1).bt.getTag().toString());
return c;
}
public void Elimnar_bt(View v){
delete = true;
}
}
I have an error whenever I try to take a picture by using camera intent.
This is the error
FileNotFoundException: No files supported by provider at content://com.example.fahad.inventory/my_images/dcim/Inventory/JPEG20170922_170324_1975076666.jpg
at com.example.fahad.inventory.AddProductActivity.getBitmap(AddProductActivity.java:270) 09-22 17:03:30.117 12950-12950/? W/System.err: at com.example.fahad.inventory.AddProductActivity.onActivityResult(AddProductActivity.java:197)
This is my code
public class AddProductActivity extends AppCompatActivity {
private static final int REQUEST_IMAGE_CAPTURE = 1;
private static final int REQUEST_SELECT_IMAGE = 2;
private static final String IMAGE_PATH = "imagePath";
private static final String IMAGE_URI = "imageUri";
private static final String BITMAP = "bitmap";
private static final String CAMERA_DIR = "/dcim/";
private String imagePath = "";
private String imageUri = "";
private ImageView imageView;
private Bitmap bitmap;
private Uri mUri;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_product);
Button addProduct = (Button) findViewById(R.id.id_btn_add_product);
Button addImage = (Button) findViewById(R.id.id_btn_add_image);
Button addGalleryImage = (Button) findViewById(R.id.id_btn_add_gallery_image);
imageView = (ImageView) findViewById(R.id.id_image_view);
if (savedInstanceState != null) {
imagePath = savedInstanceState.getString(IMAGE_PATH);
imageUri = savedInstanceState.getString(IMAGE_URI);
bitmap = (Bitmap) savedInstanceState.get(BITMAP);
imageView.setImageBitmap(bitmap);
}
addProduct.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
insert();
}
});
addImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
try {
File f = createImageFile();
mUri = FileProvider.getUriForFile(
AddProductActivity.this, ProductContract.CONTENT_AUTHORITY, f);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, mUri);
// Solution taken from http://stackoverflow.com/a/18332000/3346625
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) {
List<ResolveInfo> resInfoList = getPackageManager().queryIntentActivities(takePictureIntent, PackageManager.MATCH_DEFAULT_ONLY);
for (ResolveInfo resolveInfo : resInfoList) {
String packageName = resolveInfo.activityInfo.packageName;
grantUriPermission(packageName, mUri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
}
}
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
} catch (IOException e) {
e.printStackTrace();
}
}
});
addGalleryImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
intent.addFlags(Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION);
} else {
intent = new Intent(Intent.ACTION_GET_CONTENT);
}
intent.putExtra(Intent.EXTRA_LOCAL_ONLY, true);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.setType("image/*");
startActivityForResult(Intent.createChooser(intent, "Select image"), REQUEST_SELECT_IMAGE);
}
});
}
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG" + timeStamp + "_";
File albumF = getAlbumDir();
File imageF = File.createTempFile(imageFileName, ".jpg", albumF);
return imageF;
}
private File getAlbumDir() {
File storageDir = null;
if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
storageDir = new File(Environment.getExternalStorageDirectory()
+ CAMERA_DIR
+ getString(R.string.app_name));
if (storageDir != null) {
if (!storageDir.mkdirs()) {
if (!storageDir.exists()) {
return null;
}
}
}
} else {
Log.v(getString(R.string.app_name), "External storage is not mounted READ/WRITE.");
}
return storageDir;
}
public void insert() {
EditText editProductName = (EditText) findViewById(R.id.id_edit_product_name);
EditText editProductPrice = (EditText) findViewById(R.id.id_edit_product_price);
EditText editProductQuantity = (EditText) findViewById(R.id.id_edit_product_quantity);
String name = editProductName.getText().toString();
String quantity = editProductQuantity.getText().toString();
String price = editProductPrice.getText().toString();
ContentValues values = new ContentValues();
values.put(ProductContract.ProductColumns.PRODUCT_NAME, name);
values.put(ProductContract.ProductColumns.PRODUCT_QUANTITY, quantity);
values.put(ProductContract.ProductColumns.PRODUCT_PRICE, price);
values.put(ProductContract.ProductColumns.PRODUCT_IMAGE_PATH, imagePath);
values.put(ProductContract.ProductColumns.PRODUCT_IMAGE_URI, imagePath);
Uri uri = getContentResolver().insert(ProductContract.ProductColumns.CONTENT_URI, values);
if (uri != null) {
finish();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
imageUri = mUri.getPath();
bitmap = getBitmap(mUri);
imageView.setImageBitmap(bitmap);
} else if (requestCode == REQUEST_SELECT_IMAGE && resultCode == RESULT_OK) {
if (data != null) {
Uri uri = data.getData();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
final int flags = data.getFlags() & Intent.FLAG_GRANT_READ_URI_PERMISSION;
ContentResolver contentResolver = getContentResolver();
contentResolver.takePersistableUriPermission(uri, flags);
}
imageView.setImageBitmap(getBitmapFromUri(uri));
imageUri = uri.toString();
imagePath = uri.toString();
}
}
}
public Bitmap getBitmapFromUri(Uri uri) {
if (uri == null || uri.toString().isEmpty())
return null;
// Get the dimensions of the View
int targetW = imageView.getWidth();
int targetH = imageView.getHeight();
InputStream input = null;
try {
input = this.getContentResolver().openInputStream(uri);
// Get the dimensions of the bitmap
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inJustDecodeBounds = true;
BitmapFactory.decodeStream(input, null, bmOptions);
input.close();
int photoW = bmOptions.outWidth;
int photoH = bmOptions.outHeight;
// Determine how much to scale down the image
int scaleFactor = Math.min(photoW / targetW, photoH / targetH);
// Decode the image file into a Bitmap sized to fill the View
bmOptions.inJustDecodeBounds = false;
bmOptions.inSampleSize = scaleFactor;
bmOptions.inPurgeable = true;
input = this.getContentResolver().openInputStream(uri);
Bitmap bitmap = BitmapFactory.decodeStream(input, null, bmOptions);
input.close();
return bitmap;
} catch (FileNotFoundException fne) {
fne.printStackTrace();
return null;
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
try {
input.close();
} catch (IOException ioe) {
}
}
}
private Bitmap getBitmap(Uri uri) {
ParcelFileDescriptor parcelFileDescriptor = null;
try {
parcelFileDescriptor =
getContentResolver().openFileDescriptor(uri, "r");
FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();
Bitmap image = BitmapFactory.decodeFileDescriptor(fileDescriptor);
parcelFileDescriptor.close();
return image;
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
try {
if (parcelFileDescriptor != null) {
parcelFileDescriptor.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString(IMAGE_PATH, imagePath);
outState.putString(IMAGE_URI, imageUri);
outState.putParcelable(BITMAP, bitmap);
}
The contentAuthority is my package name.
com.example.fahad.inventory
And this is my paths :
<?xml version="1.0" encoding="utf-8"?>
<paths>
<external-path name="my_images" />
</paths>
And this is my provider in manifest :
<provider
android:name=".data.ProductProvider"
android:authorities="com.example.fahad.inventory"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/file_provider_paths" />
</provider>
I have seen some posts like this by I don't understands it. or it didn't help me with my problem.
The error in the logs are pointing to :
getContentResolver().openFileDescriptor(uri, "r");
Also the data returned in onActivityResult from the camera is always null.
I think the problem is I have to implement OpenFile method in my custom contentProvider but the problem I don't know what to write in that method.
Or the getUriForFile return wrong uri.
Please help me I'm in this problem for two weeks now and it seems I'm not going anywhere.
And I'm new to contentProvider.
Thanks in Advance And happy coding !
In my app, I am using webview to render a webpage from which I need to upload multiple files to the server. OnShowFileChooser() (for lollipop and upper versions) is working fine but onOpenFileChooser() (for other lower android versions). OnshowFileChooser() method not working if I pass an Uri array(Uri[]) to its onValueCallback(). It throws the classCastException. Below is my code which i have used for performing the required opertation. I need a solution to upload multiple file using webview which will work for all android versions.
public class ChromeClient extends WebChromeClient {
// For Android 5.0
public boolean onShowFileChooser(WebView view, ValueCallback<Uri[]> filePath, WebChromeClient.FileChooserParams fileChooserParams) {
// Double check that we don't have any existing callbacks
if (mFilePathCallback != null) {
mFilePathCallback.onReceiveValue(null);
}
mFilePathCallback = filePath;
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
// Create the File where the photo should go
File photoFile = null;
try {
photoFile = createImageFile();
takePictureIntent.putExtra("PhotoPath", mCameraPhotoPath);
} catch (IOException ex) {
// Error occurred while creating the File
Log.e(TAG, "Unable to create Image File", ex);
}
// Continue only if the File was successfully created
if (photoFile != null) {
mCameraPhotoPath = "file:" + photoFile.getAbsolutePath();
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(photoFile));
} else {
takePictureIntent = null;
}
}
Intent contentSelectionIntent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
contentSelectionIntent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
contentSelectionIntent.addFlags(Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION);
contentSelectionIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
contentSelectionIntent.setType("image/*");
Intent[] intentArray;
if (takePictureIntent != null) {
intentArray = new Intent[]{takePictureIntent};
} else {
intentArray = new Intent[0];
}
Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);
chooserIntent.putExtra(Intent.EXTRA_TITLE, "Image Chooser");
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray);
startActivityForResult(chooserIntent, INPUT_FILE_REQUEST_CODE);
return true;
}
//openFileChooser for other Android versions
public void openFileChooser(ValueCallback<Uri[]> uploadMsg, String acceptType, String capture) {
openFileChooser(uploadMsg, acceptType);
}
// openFileChooser for Android 3.0+
public void openFileChooser(ValueCallback<Uri[]> uploadMsg, String acceptType) {
mUploadMessage = uploadMsg;
// Create AndroidExampleFolder at sdcard
// Create AndroidExampleFolder at sdcard
File imageStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
, "AndroidExampleFolder");
if (!imageStorageDir.exists()) {
// Create AndroidExampleFolder at sdcard
imageStorageDir.mkdirs();
}
// Create camera captured image file path and name
File file = new File(
imageStorageDir + File.separator + "IMG_"
+ String.valueOf(System.currentTimeMillis())
+ ".jpg");
mCapturedImageURI = Uri.fromFile(file);
// Camera capture image intent
final Intent captureIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, mCapturedImageURI);
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("image/*");
// Create file chooser intent
Intent chooserIntent = Intent.createChooser(i, "Image Chooser");
// Set camera intent to file chooser
chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Parcelable[]{captureIntent});
// On select image call onActivityResult method of activity
startActivityForResult(chooserIntent, FILECHOOSER_RESULTCODE);
}
// openFileChooser for Android < 3.0
public void openFileChooser(ValueCallback<Uri[]> uploadMsg) {
openFileChooser(uploadMsg, "");
}
}
This is the onActivityResult code
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
if (requestCode != INPUT_FILE_REQUEST_CODE || mFilePathCallback == null) {
super.onActivityResult(requestCode, resultCode, data);
return;
}
Uri[] results = null;
// Check that the response is a good one
if (resultCode == Activity.RESULT_OK) {
if (data == null) {
// If there is not data, then we may have taken a photo
if (mCameraPhotoPath != null) {
results = new Uri[]{Uri.parse(mCameraPhotoPath)};
}
} else {
if (data.getData() != null) {
String dataString = data.getDataString();
if (dataString != null) {
// results = new Uri[]{Uri.parse(dataString)};
// Will return "image:x*"
String wholeID = DocumentsContract.getDocumentId(Uri.parse(dataString.replace("%3A", ":")));
// Split at colon, use second item in the array
String id = wholeID.split(":")[1];
String type = wholeID.split(":")[0];
String[] column = {MediaStore.Images.Media.DATA};
// where id is equal to
String sel = MediaStore.Images.Media._ID + "=?";
Cursor cursor = getContentResolver().
query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
column, sel, new String[]{id}, null);
String filePath = "";
int columnIndex = cursor.getColumnIndex(column[0]);
if (cursor.moveToFirst()) {
filePath = cursor.getString(columnIndex);
results = new Uri[]{Uri.parse("file:" + filePath)};
}
cursor.close();
}
} else {
if (data.getClipData() != null) {
ClipData clipData = data.getClipData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
results = new Uri[clipData.getItemCount()];
for (int i = 0; i < clipData.getItemCount(); i++) {
ClipData.Item image = clipData.getItemAt(i);
Uri uri = image.getUri();
// Will return "image:x*"
String wholeID = DocumentsContract.getDocumentId(uri);
// Split at colon, use second item in the array
String id = wholeID.split(":")[1];
String type = wholeID.split(":")[0];
String contentUri;
if ("image".equals(type)) {
contentUri = MediaStore.Images.Media.DATA;
} else if ("video".equals(type)) {
contentUri = MediaStore.Video.Media.DATA;
} else if ("audio".equals(type)) {
contentUri = MediaStore.Audio.Media.DATA;
}
String[] column = {MediaStore.Images.Media.DATA};
// where id is equal to
String sel = MediaStore.Images.Media._ID + "=?";
Cursor cursor = getContentResolver().
query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
column, sel, new String[]{id}, null);
String filePath = "";
int columnIndex = cursor.getColumnIndex(column[0]);
if (cursor.moveToFirst()) {
filePath = cursor.getString(columnIndex);
}
cursor.close();
results[i] = Uri.parse("file:" + filePath);
}
}
}
}
}
mFilePathCallback.onReceiveValue(results);
mFilePathCallback = null;
} else if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) {
if (requestCode != FILECHOOSER_RESULTCODE || mUploadMessage == null) {
super.onActivityResult(requestCode, resultCode, data);
return;
}
if (requestCode == FILECHOOSER_RESULTCODE) {
if (null == this.mUploadMessage) {
return;
}
Uri result[] = null;
try {
if (resultCode != RESULT_OK) {
result = null;
} else {
if (data.getData() != null)
result[0] = data.getData();
else {
if (data.getClipData() != null) {
result = new Uri[data.getClipData().getItemCount()];
for (int i = 0; i < data.getClipData().getItemCount(); i++) {
result[i] = data.getClipData().getItemAt(i).getUri();
}
} else {
result = null;
}
}
// retrieve from the private variable if the intent is null
//result = data == null ? mCapturedImageURI : data.getData();
}
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "activity :" + e,
Toast.LENGTH_LONG).show();
}
mUploadMessage.onReceiveValue(result);
mUploadMessage = null;
}
}
return;
}
this is the Error report
I try to select multiple images from photo gallery and save it in my custom folder on sdCard.
I wrote some code but i have nullPintException
this is a my source
Intent intent = new Intent();
intent.setType("image/*");
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select Picture"), PICK_FROM_GALLERY);
and this is OnActivityResultCode
if(data!=null)
{
ClipData clipData = data.getClipData();
for (int i = 0; i < clipData.getItemCount(); i++)
{
Uri selectedImage = clipData.getItemAt(i).getUri();
if (selectedImage != null) {
mCurrentPhotoPath = getRealPathFromURI(selectedImage);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
Bitmap bitmap = BitmapFactory.decodeFile(mCurrentPhotoPath, options);
// bitmap=getResizedBitmap(bitmap,1280,720);
String partFilename = currentDateFormat();
if (bitmap != null) {
SaveImage(bitmap, partFilename);
}
}
}
public String getRealPathFromURI(Uri uri) {
Cursor cursor = CarRecieveActivity.this.getContentResolver().query(uri, null, null, null, null);
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
return cursor.getString(idx);
}
private void SaveImage(Bitmap finalBitmap,String fileName) {
File myDir = new File(rootDirectory + "/"+vinNumber.getText().toString());
myDir.mkdirs();
String fname = fileName+".jpg";
File file = new File (myDir, fname);
try {
FileOutputStream out = new FileOutputStream(file);
finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
this is my source .i have two errors.
first when i click only one image in my gallery clipData is null and second,when i choose multiple images from gallery and click ok button i have this error
java.lang.IllegalStateException: Couldn't read row 0, col -1 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it
error is in this function getRealPathFromURI()
how i can solve both problems?
thanks
Select images from device
//Uri to store the image uri
private List<Uri> filePath;
public String path[];
public static List<ImageBeen> listOfImage;
//Image request code
private int PICK_IMAGE_REQUEST = 1;
private int PICK_IMAGE_REQUEST_MULTI = 2;
// select multiple image
private void pickImages() {
filePath = new ArrayList<>();
listOfImage = new ArrayList<>();
Intent intent;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
intent = new Intent();
intent.setType("image/*");
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.setAction(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST_MULTI);
}else {
intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.setAction(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
}
}
Activity result
//handling the image chooser activity result
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST_MULTI && resultCode == RESULT_OK && data != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
ClipData imagesPath = data.getClipData();
if (imagesPath != null) {
path = new String[imagesPath.getItemCount()];
for (int i = 0; i < imagesPath.getItemCount(); i++) {
filePath.add(imagesPath.getItemAt(i).getUri());
path[i] = getPath(imagesPath.getItemAt(i).getUri());
ImageBeen imageBeen = new ImageBeen(imagesPath.getItemAt(i).getUri());
imageBeen.setPath(path[i]);
listOfImage.add(imageBeen);
initViewPager();
}
}else {
path = new String[1];
path[0] = getPath(data.getData());
ImageBeen imageBeen = new ImageBeen(data.getData());
imageBeen.setPath(path[0]);
listOfImage.add(imageBeen);
initViewPager();
}
} else if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null) {
path = new String[1];
path[0] = getPath(data.getData());
ImageBeen imageBeen = new ImageBeen(data.getData());
imageBeen.setPath(path[0]);
listOfImage.add(imageBeen);
initViewPager();
}
}
genarate images path using Image URI
//method to get the file path from uri
public String getPath(Uri uri) {
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
String path = null;
if(cursor!=null) {
if (cursor.moveToFirst()) {
String document_id = cursor.getString(0);
document_id = document_id.substring(document_id.lastIndexOf(":") + 1);
cursor.close();
cursor = getContentResolver().query(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
null, MediaStore.Images.Media._ID + " = ? ", new String[]{document_id}, null);
cursor.moveToFirst();
path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
cursor.close();
return path;
}
}
return path;
}
This is image bean where stored image URI and Image path
public class ImageBeen {
private Uri fileUri;
private String path;
public ImageBeen(Uri fileUri)
{
this.fileUri=fileUri;
}
public String getPath() {
return path;
}
public void setPath(String path)
{
this.path=path;
}
public Uri getFileUri() {
return fileUri;
}
}
For display image use Picasso
compile 'com.squareup.picasso:picasso:2.5.2'
Picasso.with(context)
.load(imageBeen.getFileUri())
.placeholder(R.drawable.not_vailable)
.error(R.drawable.not_vailable)
.into(holder.image);