I have created an activity that upon button click user are able to upload a picture from their device gallery, which would get cast to an imageview. The problem is that it is only able to retrieve image from device gallery, not from phone camera gallery, or from phone google drive folder. I would want that its able to upload any picture from their phone, regardless of the source.
Below is the code:
Button buttonLoadImage = (Button) findViewById(R.id.btnPictureSelect);
buttonLoadImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent i = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK
&& null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
ImageView imageView = (ImageView) findViewById(R.id.profilePicturePreview);
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
}
}
private byte[] readInFile(String path) throws IOException {
// TODO Auto-generated method stub
byte[] data = null;
File file = new File(path);
InputStream input_stream = new BufferedInputStream(new FileInputStream(
file));
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
data = new byte[16384]; // 16K
int bytes_read;
while ((bytes_read = input_stream.read(data, 0, data.length)) != -1) {
buffer.write(data, 0, bytes_read);
}
input_stream.close();
return buffer.toByteArray();
}
Any help would be greatly appreciated.
Update:
private static final int READ_REQUEST_CODE = 42;
in the code
Button buttonLoadImage = (Button) findViewById(R.id.btnPictureSelect);
buttonLoadImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent imageIntent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
imageIntent.addCategory(Intent.CATEGORY_OPENABLE);
imageIntent.setType("image/*");
imageIntent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(imageIntent , READ_REQUEST_CODE);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == READ_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
Uri uri = null;
if (data != null) {
uri = data.getData();
Log.i(TAG, "Uri: " + uri.toString());
showImage(uri);
}
}
}
private void showImage(Uri uri) {
// TODO Auto-generated method stub
ImageView imageView = (ImageView) findViewById(R.id.profilePicturePreview);
imageView.setImageUri(Uri.parse(new File("path_to_your_image".toString()));
}
error:
The method parse(String) in the type Uri is not applicable for the arguments (File)
in line
imageView.setImageUri(Uri.parse(new File("path_to_your_image".toString()));
Update 2:
private void showImage(Uri uri) {
// TODO Auto-generated method stub
ImageView imageView = (ImageView) findViewById(R.id.profilePicturePreview);
imageView.setImageUri(Uri.fromFile(new File("/sdcard/myimage.jpg")));
error:
The method setImageUri(Uri) is undefined for the type ImageView
It would be better to use Intent to search the image type files available in your device.
Intent imageIntent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
imageIntent.addCategory(Intent.CATEGORY_OPENABLE);
imageIntent.setType("image/*");
imageIntent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(imageIntent , READ_REQUEST_CODE); // set READ_REQUEST_CODE to 42 in your class
Now, process your results in the onActivityResult() method.
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == READ_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
Uri uri = null;
if (data != null) {
uri = data.getData();
Log.i(TAG, "Uri: " + uri.toString());
showImage(uri);
}
}
Related
I have added Camera permissions as well which is working perfectly but the image view is not holding the image that is captured. The manifest file is also proper still. The app isn't crashing even it is not showing any errors as well. And I even want to add the image to the database.
public class RiderProfile extends AppCompatActivity {
ImageView imgDp,imgDlFront,imgDlback;
TextView txtDp,txtDl;
Button btnSave;
public static final int CAMERA_REQUEST = 1888;
private static final String TAG = "1111";
private static final int MY_CAMERA_PERMISSION_CODE = 100;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_rider_profile);
imgDp = (ImageView)findViewById(R.id.imgDp);
imgDlFront = (ImageView)findViewById(R.id.imgDlFront);
imgDlback = (ImageView)findViewById(R.id.imgDlback);
txtDp = (TextView) findViewById(R.id.txtDp);
txtDl = (TextView)findViewById(R.id.txtDl);
btnSave = (Button) findViewById(R.id.btnSave);
imgDp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(i, CAMERA_REQUEST);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_REQUEST && resultCode == Activity.RESULT_OK) {
Bitmap photo1 = (Bitmap) data.getExtras().get("data");
Log.d(TAG, "onActivityResult: click ");
imgDp.setImageBitmap(photo1);
}
}
});
imgDlFront.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(i, CAMERA_REQUEST);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_REQUEST && resultCode == Activity.RESULT_OK) {
Bitmap photo2 = (Bitmap) data.getExtras().get("data");
Log.d(TAG, "onActivityResult: click ");
imgDlFront.setImageBitmap(photo2);
}
}
});
imgDlback.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(i, CAMERA_REQUEST);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_REQUEST && resultCode == Activity.RESULT_OK) {
Bitmap photo3 = (Bitmap) data.getExtras().get("data");
Log.d(TAG, "onActivityResult: click ");
imgDlback.setImageBitmap(photo3);
}
}
});
}
}
1. #Override
public void onCameraOpen() {
Intent pictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (pictureIntent.resolveActivity(getPackageManager()) != null) {
try {
imageFile = CameraUtils.createImageFile(this);
} catch (IOException e) {
e.printStackTrace();
return;
}
imageUri = FileProvider.getUriForFile(this, getPackageName() + ".provider", imageFile);
pictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(pictureIntent, IntentRequestCode.RESULT_CODE_IMAGE_CAPTURE);
}
}
2. #Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case RESULT_CODE_IMAGE_CAPTURE:
if (resultCode == RESULT_OK) {
onCaptureImage(imageFile, imageUri);
} else {
Toast.makeText(this, "Camera canceled", Toast.LENGTH_SHORT).show();
}
break;
}
}
3. void onCaptureImage(File imageFile, Uri imageUri) {
Uri uri = Uri.fromFile(imageFile);
String selectedImagePath = CameraUtils.getPath(application, uri);
File file1 = new File(selectedImagePath);
if (file1.length() != 0) {
FileAttachments b_data = new FileAttachments();
b_data.setFileName(file1.getName());
CameraUtils.writeScaledDownImage(file1, getApplication());
b_data.setFile(file1);
}
}
i was building my app on API level 23 ,then i have changed API level to 25 the same code is not working now , here's my code :
public class expert extends Activity implements View.OnClickListener {
Button btnsetwall;
ImageButton imgbtntakeph;
ImageView Imview;
static final int REQUEST_IMAGE_CAPTURE = 1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_expert);
Imview = (ImageView) findViewById(R.id.imageView22);
btnsetwall = (Button) findViewById(R.id.button2);
btnsetwall.setOnClickListener(this);
}
#Override
public void onClick(View v) {
dispatchTakePictureIntent();
}
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
Imview.setImageBitmap(imageBitmap);
// CALL THIS METHOD TO GET THE URI FROM THE BITMAP
Uri tempUri = getImageUri(getApplicationContext(), imageBitmap);
// CALL THIS METHOD TO GET THE ACTUAL PATH
Toast.makeText(getBaseContext(),"Here "+ getRealPathFromURI(tempUri), Toast.LENGTH_LONG).show();
}
}
public Uri getImageUri(Context inContext, Bitmap inImage) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = MediaStore.Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);
return Uri.parse(path);
}
public String getRealPathFromURI(Uri uri) {
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
return cursor.getString(idx);
}
when i try to pick image from gallery or to get captured image my app crashes and i get UriString Exception
can any one tell the reason ?? and how to solve !
thanks in advance
i'm trying to do an activity which can show picture from gallery. But my Activity needs to remember bitmap uri for another time so it can always open that picture.
here is my .java
edited
i added something else to convert uri to string then string to uri but it doesn't work. Can someone help?
public class DersProgram extends Activity { private static int RESULT_LOAD_IMAGE = 1;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dersprogrami);
Button buttonLoadImage = (Button) findViewById(R.id.button1);
buttonLoadImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent i = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
Uri uri = data.getData();
String BitmapURI;
BitmapURI = uri.toString();
uri = Uri.parse(BitmapURI);
SharedPreferences sharedPreferences = getSharedPreferences("BitmapURI", Context.MODE_PRIVATE);
sharedPreferences.edit().putString("BitmapURI", "your URI as a String").apply();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(uri,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
ImageView imageView = (ImageView) findViewById(R.id.resim);
Bitmap bmp = null;
try {
bmp = getBitmapFromUri(uri);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
imageView.setImageBitmap(bmp);
}
}
private Bitmap getBitmapFromUri(Uri uri) throws IOException {
ParcelFileDescriptor parcelFileDescriptor =
getContentResolver().openFileDescriptor(uri, "r");
FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();
Bitmap image = BitmapFactory.decodeFileDescriptor(fileDescriptor);
parcelFileDescriptor.close();
return image;
}
}
I want to open picture which is called before. Please help me(also i am a beginner) sorry for my English.
As said, use SharedPreferences.
store your bitmapURI as a String in your Activity:
SharedPreferences sharedPreferences = getSharedPreferences("some string", Context.MODE_PRIVATE);
sharedPreferences.edit().putString("BitmapURI", "your URI as a String").apply();
and retrieve it whenever your want:
String bitmapURI = sharedPreferences.getString("BitmapURI", "default string if BitmapURI is not set");
I'm trying to save the path of an image imported from the gallery using this method:
case R.id.media:
Intent i = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
return true;
Here is the on activity result method:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
final Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = (cursor.getString(columnIndex));
cursor.close();
mImage = picturePath;
ImageView imageView = (ImageView) findViewById(R.id.note_image);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
imageView.setClickable(true);
imageView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent viewImageIntent = new Intent(android.content.Intent.ACTION_VIEW, selectedImage);
startActivity(viewImageIntent);
}
});
}
}
And here is the populate field method:
mImage =(note.getString(
note.getColumnIndexOrThrow(NotesDbAdapter.KEY_IMAGE)));
But this is not working, the path doesnt get saved and when i close the activity and start the activity again, the image is gone. How can i fix this?
How to use default camera to take a picture in android ?
Uri imageUri;
final int TAKE_PICTURE = 115;
public void capturePhoto(View view) {
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
File photoFile = new File(Environment.getExternalStorageDirectory(), "Photo.png");
intent.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(photoFile));
imageUri = Uri.fromFile(photoFile);
startActivityForResult(intent, TAKE_PICTURE);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case TAKE_PICTURE:
if (resultCode == Activity.RESULT_OK) {
Uri selectedImageUri = imageUri;
//Do what ever you want
}
}
}
The intent which is used to open the camera is
buttonCapturePhoto.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, CAPTURE_IMAGE);
}
});
The code which gives you the image after capturing is
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Uri uriImage;
InputStream inputStream = null;
if ( (requestCode == SELECT_IMAGE || requestCode == CAPTURE_IMAGE) && resultCode == Activity.RESULT_OK) {
uriImage = data.getData();
try {
inputStream = getContentResolver().openInputStream(uriImage);
Bitmap bitmap = BitmapFactory.decodeStream(inputStream, null, options);
imageView.setImageBitmap(bitmap);
} catch (NullPointerException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
imageView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
imageView.setAdjustViewBounds(true);
}
}
This is a simple example.Anyway this will return the image as a small bitmap.If you want to retrive the full-sized image ,is a bit more complicated.
ImageView takePhotoView = (ImageView) findViewById(R.id.iwTakePicture);
Bitmap imageBitmap = null;
takePhotoView.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
dispatchTakePictureIntent(0);
}
});
private void dispatchTakePictureIntent(int actionCode) {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(takePictureIntent, actionCode);
}
private void handleSmallCameraPhoto(Intent intent) {
Bundle extras = intent.getExtras();
this.imageBitmap = (Bitmap) extras.get("data");
takePhotoView.setImageBitmap(imageBitmap);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(resultCode == RESULT_OK)
handleSmallCameraPhoto(data);
}