In the app I am building, the user selects a picture from gallery and the path is saved in Shared Preferences. I then want to retrieve this picture from the stored path but it doesn't work. The image is an ImageButton, which the user clicks in order to select picture from Gallery.
The code I have to retrieve the picture and "put" on the ImageButton is:
This code does actually work now, put it here in case it helps others.
File imgFile = new File(sharedpreferences.getString(Path, LOCATION_SERVICE));
if(imgFile.exists())
{
Bitmap b = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
ImageButton img=(ImageButton)findViewById(R.id.AddPic);
img.setImageBitmap(b);
}
I know the path is correct, but I am not able to retrieve the picture and put it on the ImageButton.
Below is the code where the user clicks on the ImageButton, and selects a picture from the gallery and the path of that picture is stored within the sharedPreferences:
imgButton = (ImageButton) findViewById(R.id.AddPic);
imgButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent GaleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(GaleryIntent, 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 SelectedCursor = getContentResolver().query(SelectedImage, FilePathColumn, null, null, null);
SelectedCursor.moveToFirst();
int columnIndex = SelectedCursor.getColumnIndex(FilePathColumn[0]);
String picturePath = SelectedCursor.getString(columnIndex);
SelectedCursor.close();
imgButton.setImageBitmap(BitmapFactory.decodeFile(picturePath));
Editor editor = sharedpreferences.edit();
editor.putString(Path, picturePath);
editor.commit();
}
}
What am I doing wrong?
Thanks very much!
Related
So I used this to open my image choose upon button click
//Open image chooser
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, SELECT_PHOTO);
and used onActivityResult
private final static int SELECT_PHOTO = 12345;
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.e("CALLED", "OnActivity Result");
if (requestCode == SELECT_PHOTO && resultCode == RESULT_OK) {
// Let's read picked image data - its URI
Uri pickedImage = data.getData();
// Let's read picked image path using content resolver
String[] filePath = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(pickedImage, filePath, null, null, null);
cursor.moveToFirst();
String imagePath = cursor.getString(cursor.getColumnIndex(filePath[0]));
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
Bitmap bitmap = BitmapFactory.decodeFile(imagePath, options);
Log.e("img", "It worked");
// Do something with the bitmap
// At the end remember to close the cursor or you will end with the RuntimeException!
cursor.close();
}
}
In logcat, OnactivityResult is not being called, and I cant figure out why. So when I click the button, the image chooser pops up, I choose an image, and then it exits back to the main screen.
Am I missing something, as I've followed others' code but I still get the same thing
Give this a try:
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(photoPickerIntent,"Select:"), SELECT_PHOTO);
I would like to allow the user to pock only one image that can be referenced via a uri, I've successfully done this through the following code:
private static final int PICK_IMAGE_REQUEST = 1;
private Uri imageUri;
// Choose file extended from BottomTabView, opens all images on device
public static void openFileChooser(Context context) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
((Activity) context).startActivityForResult(intent, PICK_IMAGE_REQUEST);
// Slide Animation
((Activity) context).overridePendingTransition(R.anim.slide_in_up, R.anim.nothing);
}
// TODO: Is it better to use bitmap or URI
// Check if user has selected file and describe next step
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
// Retrieve image as a URI
imageUri = data.getData();
// Pass image URI to an intent and start activity
Intent intent = new Intent(this, UploadImageActivity.class);
intent.putExtra("imageUri", imageUri.toString());
startActivity(intent);
// Slide Animation
overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
this.finish();
}
}
The above code opens the following:
However, I would like to have something like the following:
Question: How can I achieve something more like the "Custom Gallery"?
if you want to custom layout pick image, you need:
create a screen and using recyclerView to make the layout as you want
get all picture gallery (https://stackoverflow.com/a/25957752/10153377)
I'm making an Android application in Android studio where the user can take a photo and save it into a new folder in their gallery. Currently the application takes the pictures fine but doesn't save the image into the new "SOC" folder in my gallery. I'm not getting any errors and I have no idea why it's not saving the image. Any help would be appreciated.
My code is as fallows
static final int REQUEST_IMAGE_CAPTURE = 1;
private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 0;
public void onClickbtnCamera(View v)
{
Intent imageIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
Uri uriSavedImage=Uri.fromFile(new File("/storage/emulated/0/DCIM/SOC","QR_"+timeStamp+ ".png"));
imageIntent.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedImage);
startActivityForResult(imageIntent, 1);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1) {
//Check for succesful result code
if (resultCode == -1) {
//Show your Toast when the result is a success.
Toast toast = Toast.makeText(getApplicationContext(),
"Picture is saved in your SOC gallery", Toast.LENGTH_SHORT);
toast.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL, 100, 0);
toast.show();
}
}
}
I think you must manually add your new photo Uri to Media Content Provider.
take a look here
Call this method in your Activity for result
protected void addPhotoToGallery() {
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File f = new File(getCurrentPhotoPath());
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
this.getActivity().sendBroadcast(mediaScanIntent);
}
you should save the photo path before launching the intent and then getCurrentPhotoPath() must get that path
I am Trying To upload image to server from gallery and camera.When i Choose image from gallery to upload to server its Work Perfactly.But when i Select camera captured Image for upload to server Its Crash And Showing the error.
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.net.Uri.getScheme()' on a null object reference
At OnActivityResult.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_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();
decodeFile(picturePath);
new ImageUploadTask().execute();
}else {
Toast.makeText(getApplicationContext(), "User Canceled",
Toast.LENGTH_LONG).show();
}
}
i got the error on this line in onActivityResult
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
The method i used for open camera on button click.
loadimage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
AlertDialog.Builder builder = new AlertDialog.Builder(Add_Info.this);
builder.setMessage("Select Image From")
.setCancelable(true)
.setPositiveButton("Camera", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, CAMERA_REQUEST);
mImageCaptureUri = Uri.fromFile(new File(Environment
.getExternalStorageDirectory(), "tmp_avatar_"
+ String.valueOf(System.currentTimeMillis())
+ ".jpg"));
}
})
.setNegativeButton("Gallery", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent i = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
}
});
AlertDialog alert = builder.create();
alert.show();
}
});
Help Me solve this problem.I don't know How t get this error even after i used is already in my Previous PROJECT.
THANKS in Advance
I had same issue when working with Camera api and Intent of onActivityResult, finally I found out it depends on your android device version, in Android M (Marshmallow - 6.0–6.0.1 ) onActivityResult intent is like below :
requestCode : 230 resultCode : -1 intent :Intent{dat=file:///storage/emulated/0/Pictures/Rahnama/IMG_20160508_121332_1519065 564.jpg typ=image/jpeg } RESULT_OK : -1
and for android versions lower than Marshmallow:
requestCode : 230 resultCode : -1 intent : Intent { dat=content://media/external/images/media/309 (has extras) } RESULT_OK : -1
I think you must check android version onActivityResult and the for android versions Marshmallow to get direct file from path in the Uri and Intent:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (Build.VERSION.SDK_INT == Build.VERSION_CODES.M){
final Uri data = intent.getData();
final File file = new File(data.getPath());
// now you can upload your image file
}else{
// in android version lower than M your method must work
}
I hope it can be useful for you.
if (null != account.getPhotoUrl()) {
// Write code here
}
I meet this problem either, after many test, I found its because I set the attribute named android:windowIsTranslucent=true, if I delete this attribute from style, it always work.
I have ImageView & one button on my ImageActivity. when the button is clicked the available images are listed, when one of them is clicked, it is loaded into the ImageView.
imageView xml:
<ImageView
android:id="#+id/imageView"
android:layout_width="300dip"
android:layout_height="300dip"
android:src="#android:drawable/alert_light_frame"
/>
Please see the code:
public class ImageActivity extends Activity {
private static final int SELECT_PICTURE = 1;
private String selectedImagePath;
private ImageView imageView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.comments_detail);
imageView = (ImageView) findViewById(R.id.imageView);
((Button) findViewById(R.id.BtnBrowse))
.setOnClickListener(new OnClickListener()
{
public void onClick(View arg0)
{
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select Picture"), SELECT_PICTURE);
}
});
}
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (resultCode == RESULT_OK)
{
if (requestCode == SELECT_PICTURE)
{
Uri selectedImageUri = data.getData();
selectedImagePath = getPath(selectedImageUri);
//System.out.println("Image Path : " + selectedImagePath);
imageView.setImageURI(selectedImageUri);
}
}
}
public String getPath(Uri uri)
{
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
}
Issue: The issue is that when i click the button the available images are displayed, i selects one of them & it is loaded in the ImageView, when i repeat these steps few time the application throws throws the exception:
java.lang.OutOfMemoryError: bitmap size exceeds VM budget
I goggled it & found that this issue is because of memory leaks but i am unable to find whats wrong with my code. Can anyone spend some of his valuable time to help me?
Thanks.
If you do a series of setImageURIs, you are loading a series of bitmaps into the view. If you are getting the java.lang.OutOfMemoryError: bitmap size exceeds VM budget exception, that implies that the imageView does not recycle the previous bitmap when you load a new one. So you
either need to encourage the imageView to recycle the previous bitmap - possibly with setImageView("")
or get the bitmap from the URI and use setImageBitmap(android.graphics.Bitmap) instead; then you can do setImageBitmap(null) and bitmap.recycle().
Well calling the system.gc() worked!!
Before the image is assigned to the imageView, i called the System.gc(), to take care of memory & it works.
Look at the modified code:
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (resultCode == RESULT_OK)
{
if (requestCode == SELECT_PICTURE)
{
// calling GC to take care of memory, if you remove this one line of code
// application will throw the error "VM out of memory error"
System.gc();
Uri selectedImageUri = data.getData();
selectedImagePath = getPath(selectedImageUri);
imageView.setImageURI(selectedImageUri);
}
}
}
Thanks #Torid.
Can someone comment on it? is this correct way to call the GC in this situation?