Select multiple images from Photo Gallery on Android using Intents NullPointerException - java

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

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

Android CursorIndexOutOfBoundsException

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

Android Large Image on Imageview Crashes App on OOM Error

The below code allows a user to pick 4 images from their gallery and upload to a server. At the moment It is uploading all 4 small images but when i try large images it crashes on OOM error.
Even when i try to load 2 large images the app crashes when i load a big images on OOM error. What is the most efficient way to handle such issues?. I have read this Android Bitmaps but i don't seem to get how to implement in my four images code. I have tried Picasso but the app still behaves the same (ditto) above.
SelectImageGallery1 = (Button)findViewById(R.id.buttonSelect1);
SelectImageGallery2 = (Button)findViewById(R.id.buttonSelect2);
SelectImageGallery3 = (Button)findViewById(R.id.buttonSelect3);
SelectImageGallery4 = (Button)findViewById(R.id.buttonSelect4);
UploadImageServer = (Button)findViewById(R.id.buttonUpload);
SelectImageGallery1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Image1 From Gallery"), 1);
}
});
SelectImageGallery2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Image4 From Gallery"), 2);
}
});
SelectImageGallery3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Image3 From Gallery"), 3);
}
});
SelectImageGallery4.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Image4 From Gallery"), 4);
}
});
UploadImageServer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
GetImageNameEditText1 = imageName1.getText().toString();
GetImageNameEditText2 = imageName2.getText().toString();
GetImageNameEditText3 = imageName3.getText().toString();
GetImageNameEditText4 = imageName4.getText().toString();
ImageUploadToServerFunction();
}
});
}
#Override
protected void onActivityResult(int RC, int RQC, Intent I) {
super.onActivityResult(RC, RQC, I);
if (RC == 1&&RQC == RESULT_OK&&I != null&&I.getData() != null) {
Uri uri = I.getData();
try {
bitmap1 = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
imageView1.setImageBitmap(bitmap1);
} catch (IOException e) {
e.printStackTrace();
}
}
if (RC == 2 && RQC == RESULT_OK && I != null && I.getData() != null) {
Uri uri = I.getData();
try {
bitmap2 = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
//bitmap1 = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
imageView2.setImageBitmap(bitmap2);
} catch (IOException e) {
e.printStackTrace();
}
}
if (RC == 3 && RQC == RESULT_OK && I != null && I.getData() != null) {
Uri uri = I.getData();
byte[] imageAsBytes=null;
try {
bitmap3 = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
//bitmap1 = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
imageView3.setImageBitmap(bitmap3);
} catch (IOException e) {
e.printStackTrace();
}
}
if (RC == 4 && RQC == RESULT_OK && I != null && I.getData() != null) {
Uri uri = I.getData();
try {
bitmap4 = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
//bitmap1 = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
imageView4.setImageBitmap(bitmap4);
} catch (IOException e) {
e.printStackTrace();
}
}
}
public String getStringImage1(Bitmap bitmap1){
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap1.compress(Bitmap.CompressFormat.JPEG, 60, baos);
byte[] imageBytes = baos.toByteArray();
String encodedImage1 = Base64.encodeToString(imageBytes, Base64.DEFAULT);
return encodedImage1;
}
public String getStringImage2(Bitmap bitmap2){
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap2.compress(Bitmap.CompressFormat.JPEG, 60, baos);
byte[] imageBytes = baos.toByteArray();
String encodedImage2 = Base64.encodeToString(imageBytes, Base64.DEFAULT);
return encodedImage2;
}
public String getStringImage3(Bitmap bitmap3){
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap3.compress(Bitmap.CompressFormat.JPEG, 60, baos);
byte[] imageBytes = baos.toByteArray();
String encodedImage3 = Base64.encodeToString(imageBytes, Base64.DEFAULT);
return encodedImage3;
}
public String getStringImage4(Bitmap bitmap4){
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap4.compress(Bitmap.CompressFormat.JPEG, 60, baos);
byte[] imageBytes = baos.toByteArray();
String encodedImage4 = Base64.encodeToString(imageBytes, Base64.DEFAULT);
return encodedImage4;
}
This was achieved by using Glide as follows. Using glide ensures the OOM errors are handled and they are not repeated on loading even a 30mb image.
#Override
protected void onActivityResult(int RC, int RQC, Intent I) {
super.onActivityResult(RC, RQC, I);
if (RC == 1 && RQC == RESULT_OK && I != null && I.getData() != null) {
Uri uri = I.getData();
RequestOptions options = new RequestOptions()
.format(DecodeFormat.PREFER_ARGB_8888)
.placeholder(R.drawable.ic_launcher_background)
.error(R.drawable.ic_launcher_background);
Glide.with(this)
.setDefaultRequestOptions(options)
.asBitmap()
.load(uri)
.centerInside()
.into(new CustomTarget<Bitmap>(512, 512) {
#Override
public void onResourceReady(#NonNull Bitmap bitmap1, #Nullable Transition<? super Bitmap> transition) {
imageView1.setImageBitmap(bitmap1);
UploadActivity.this.bitmap1 = bitmap1;
}
#Override
public void onLoadCleared(#Nullable Drawable placeholder) {
}
});
}
ByteArrayOutputStream holds all data in memory. So you cannot store data larger than the heap. Modify the "manifest" in the first way.
AndroidManifest.xml
<application
android:largeHeap="true">
</application>
Use FileInputStream instead of ByteArrayOutputStream.
You should decode bitmap to decrease the size of bitmap before upload to sever:
You can change size(reqWidth\reqHeight) at your disposal
You can refer to my Github to get full code: https://github.com/vancuong0429/ResizeImageUtil/blob/master/ResizeImageUtil
To get a file from onActivityResult(), You can refer link
Android Studio get File from Gallery Intent
In onActivityResult():
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (RC == 1 && RQC == RESULT_OK && I != null && I.getData() != null) {
Uri uri = I.getData();
// Creating file
// Get the path from the Uri
final String path = getPathFromURI(uri);
if (path != null) {
File yourFile = new File(path);
bitmap1 = decodeBitmapFromFile(yourFile, 512, 512)
}
}
}
public 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;
}
fun decodeBitmapFromFile(imageFile: File, reqWidth: Int, reqHeight: Int): Bitmap {
val options = BitmapFactory.Options()
options.inJustDecodeBounds = true
BitmapFactory.decodeFile(imageFile.absolutePath, options)
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight)
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false
var scaledBitmap = BitmapFactory.decodeFile(imageFile.absolutePath, options)
scaledBitmap = modifyOrientation(scaledBitmap, imageFile.absolutePath)
return scaledBitmap
}

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

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

Android - onActivityResult - Invalid column _data

I'm trying to do an application which is sending SMS, and MMS, so I need to retrieve the phone number and eventually an image.
My problem is, if I only the PICK_CONTACT case in onActivityResult, it's working fine, I got my contact phone number.
But if I'm adding the second part, PICK_IMAGE, when I'm clicking on my contact, I got a :
java.lang.IllegalArgumentException: Invalid column _data
But I can still taking images without any problems..
Both intent call
private static final int PICK_CONTACT = 3;
private static final int PICK_IMAGE = 4;
protected void onCreate(Bundle savedInstanceState) {
...
}
public void addImage() {
Intent choosePictureIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(choosePictureIntent,PICK_IMAGE );
}
public void addContact(){
Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
startActivityForResult(intent, PICK_CONTACT);
}
onActivityResult Code
public void onActivityResult(int reqCode, int resultCode, Intent data){
super.onActivityResult(reqCode, resultCode, data);
Uri contactData = data.getData();
switch(reqCode) {
case (PICK_CONTACT):
if (resultCode == Activity.RESULT_OK) {
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
if (cur.moveToFirst()) {
String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
Cursor pCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[]{id}, null);
while (pCur.moveToNext()) {
phone = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
etPhoneNo.setText(phone);
}
pCur.close();
}
}
case (PICK_IMAGE) :
if (resultCode == Activity.RESULT_OK) {
try {
BitmapFactory.Options bmpFactoryOptions = new BitmapFactory.Options();
bmpFactoryOptions.inJustDecodeBounds = true;
bmpFactoryOptions.inSampleSize = 2;
bmpFactoryOptions.inJustDecodeBounds = false;
Bitmap bmp = BitmapFactory.decodeStream(getContentResolver().openInputStream(contactData), null, bmpFactoryOptions);
imageView.setImageBitmap(bmp);
} catch (FileNotFoundException e) {
Log.v("ERROR", e.toString());
}
ContentResolver cr = getContentResolver();
String [] proj = {MediaStore.Images.Media.DATA};
Cursor cursor = cr.query(contactData, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
image_path = cursor.getString(column_index);
}
}
}
How can I resolve that?
I actually solved it ..
I just forgot break; :)

Categories

Resources