Multiple file upload from android webview (Kitkat and lower android versions) - java

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

Related

How to create file chooser with camera option in android Studio?

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

how to get absolute path from pick file in android device?

i try many way but intent not return path that i want , how can i get absolute path ?
this is which i retrieved
/document/image:29163
code for intent
binding.buttonSetVoiceGallery.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("*/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent, 0);
}
});
when activityresult
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 0 && resultCode == RESULT_OK) {
Log.d(TAG,data.getData().getPath());
}
}
Try this code for getting absolute path:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 0 && resultCode == RESULT_OK) {
Log.d(TAG,data.getData().getPath());
Object objImg = data.getExtras().get("path");
Log.e("Selected", "" + objImg.toString());
/*--getting image uri from object--*/
Uri selectedImage = Uri.parse(String.valueOf(objImg));
Log.e("Selected Image", "" + selectedImage);
/*--create file object using uri--*/
File myFile = new File(selectedImage.getPath());
String path = myFile.getAbsolutePath();
Log.e("AbsolutePath---", ""+path);
}
}
binding.buttonSetVoiceGallery.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
launcher.launch(intent);
}
});
ActivityResultLauncher<Intent> launcher = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
#Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == Activity.RESULT_OK ) {
Intent data = result.getData();
Uri uri= data.getData();
File file = new File(FileMyutils.getPath(getContext(),uri));
}
}
});
public class FileMyutils {
private static final String TAG = "FileUtils";
#WorkerThread
#Nullable
public static String getReadablePathFromUri(Context context, Uri uri) {
String path = null;
if ("file".equalsIgnoreCase(uri.getScheme())) {
path = uri.getPath();
}
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT) {
path = getPath(context, uri);
}
if (TextUtils.isEmpty(path)) {
return path;
}
Log.d(TAG, "get path from uri: " + path);
if (!isReadablePath(path)) {
int index = path.lastIndexOf("/");
String name = path.substring(index + 1);
String dstPath = context.getCacheDir().getAbsolutePath() + File.separator + name;
if (copyFile(context, uri, dstPath)) {
path = dstPath;
Log.d(TAG, "copy file success: " + path);
} else {
Log.d(TAG, "copy file fail!");
}
}
return path;
}
public static String getPath(final Context context, final Uri uri) {
final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
if (isExternalStorageDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
Log.d("External Storage", docId);
final String[] split = docId.split(":");
final String type = split[0];
if ("primary".equalsIgnoreCase(type)) {
return Environment.getExternalStorageDirectory() + "/" + split[1];
}
} else if (isDownloadsDocument(uri)) {
String dstPath = context.getCacheDir().getAbsolutePath() + File.separator + getFileName(context,uri);
if (copyFile(context, uri, dstPath)) {
Log.d(TAG, "copy file success: " + dstPath);
return dstPath;
} else {
Log.d(TAG, "copy file fail!");
}
} else if (isMediaDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[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[]{split[1]};
return getDataColumn(context, contentUri, selection, selectionArgs);
}
} else if ("content".equalsIgnoreCase(uri.getScheme())) {
return getDataColumn(context, uri, null, null);
} else if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}
return null;
}
public static String getFileName(Context context, Uri uri) {
Cursor cursor = context.getContentResolver().query(uri,null,null,null,null);
int nameindex = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
cursor.moveToFirst();
return cursor.getString(nameindex);
}
private static String getDataColumn(Context context, Uri uri, String selection,
String[] selectionArgs) {
Cursor cursor = null;
final String column = "_data";
final String[] projection = {column};
try {
cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
null);
if (cursor != null && cursor.moveToFirst()) {
final int column_index = cursor.getColumnIndexOrThrow(column);
return cursor.getString(column_index);
}
} finally {
if (cursor != null)
cursor.close();
}
return null;
}
private static boolean isExternalStorageDocument(Uri uri) {
return "com.android.externalstorage.documents".equals(uri.getAuthority());
}
private static boolean isDownloadsDocument(Uri uri) {
return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}
private static boolean isMediaDocument(Uri uri) {
return "com.android.providers.media.documents".equals(uri.getAuthority());
}
private static boolean isReadablePath(#Nullable String path) {
if (TextUtils.isEmpty(path)) {
return false;
}
boolean isLocalPath;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
if (!TextUtils.isEmpty(path)) {
File localFile = new File(path);
isLocalPath = localFile.exists() && localFile.canRead();
} else {
isLocalPath = false;
}
} else {
isLocalPath = path.startsWith(File.separator);
}
return isLocalPath;
}
private static boolean copyFile(Context context, Uri uri, String dstPath) {
InputStream inputStream = null;
OutputStream outputStream = null;
try {
inputStream = context.getContentResolver().openInputStream(uri);
outputStream = new FileOutputStream(dstPath);
byte[] buff = new byte[100 * 1024];
int len;
while ((len = inputStream.read(buff)) != -1) {
outputStream.write(buff, 0, len);
}
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
if (outputStream != null) {
try {
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
return true;
}
}

FileNotFoundException: No files supported by provider at content

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 !

Unreliable result for checking incoming number in contact

I am using code listed here Check Incoming number is stored in Contacts list or not android for checking whether incoming number exist or not in contacts. This code does not give correct result always.
Is there some correction required in this or some other better way to check?
Code:
String res = null;
try {
ContentResolver resolver = context.getContentResolver();
Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phoneNumber));
String a = uri.getLastPathSegment();
Cursor c = resolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, new String[]{ContactsContract.CommonDataKinds.Phone.NUMBER}, ContactsContract.CommonDataKinds.Phone._ID + "=?", new String[]{a}, null);
if (c != null) { // cursor not null means number is found contactsTable
if (c.getCount() > 0) {
if (c.moveToFirst()) { // so now find the contact Name
res = c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
//res = c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
}
c.close();
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
return res;
Try the below code its simple & working for me.
public class TestActivity extends Activity {
private static final int REQUEST_CONTACT_NUMBER = 8512885487;
/** Pops the "select phone number" window */
public void onBrowseForNumbersButtonClicked(View view) {
Intent contactPickerIntent = new Intent(Intent.ACTION_PICK, Phone.CONTENT_URI);
startActivityForResult(contactPickerIntent, REQUEST_CONTACT_NUMBER);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if(data != null && requestCode == REQUEST_CONTACT_NUMBER) {
Uri uriOfPhoneNumberRecord = data.getData();
String idOfPhoneRecord = uriOfPhoneNumberRecord.getLastPathSegment();
Cursor cursor = getContentResolver().query(Phone.CONTENT_URI, new String[]{Phone.NUMBER}, Phone._ID + "=?", new String[]{idOfPhoneRecord}, null);
if(cursor != null) {
if(cursor.getCount() > 0) {
cursor.moveToFirst();
String formattedPhoneNumber = cursor.getString( cursor.getColumnIndex(Phone.NUMBER) );
Log.d("TestActivity", String.format("The selected phone number is: %s", formattedPhoneNumber));
}
cursor.close();
}
}
else {
Log.w("TestActivity", "WARNING: Corrupted request response");
}
}
else if (resultCode == RESULT_CANCELED) {
Log.i("TestActivity", "Popup canceled by user.");
}
else {
Log.w("TestActivity", "WARNING: Unknown resultCode");
}
}
}

Select multiple images from Photo Gallery on Android using Intents NullPointerException

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

Categories

Resources