Create a class specifically for retrieving an image? - android

I have a method of retrieving an image from the gallery that works perfectly fine for me. My issue is, I use it in three separate activities and feel that I should make a class that can be called to get the image.
This is my code:
private void getImage () {
Intent galleryIntent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
// Start the Intent
startActivityForResult(galleryIntent, RESULT_LOAD_IMG);
}
and
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
mRLMenuParams.setVisibility(View.GONE);
mRLImageParams.setVisibility(View.VISIBLE);
bmSelectedImage = null;
try {
// When an Image is picked
if (requestCode == RESULT_LOAD_IMG && resultCode == RESULT_OK
&& null != data) {
// Get the Image from data
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
// Get the cursor
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
// Move to first row
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
imgDecodableString = cursor.getString(columnIndex);
cursor.close();
ImageView imSelectedImage = (ImageView) findViewById(R.id.imageView_image);
imSelectedImage.setImageBitmap(BitmapFactory.decodeFile(imgDecodableString));
Bitmap bmImage = Bitmap.createBitmap(BitmapFactory.decodeFile(imgDecodableString));
bmSelectedImage = bmImage.copy(Bitmap.Config.ARGB_8888, true);
} else {
Toast.makeText(this, "You haven't picked Image", Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Toast.makeText(this, "Something went wrong", Toast.LENGTH_LONG).show();
}
}
When I try to put this in its own class, i can't get it to work, even when passing the Context. It seems that I would need to make it an activity, and if so, I don't see the point in separating it. Am I missing something that will allow me to put this in its own class and return the image?
Thanks!

You're using the method onActivityResult which comes from Activity. Maybe have a class method to do the code you have inside onActivityResult. Change your class to contain two separate methods, since if your separate class contains onActivity it won't work unless it's an activity.
http://developer.android.com/reference/android/app/Activity.html

Related

import images from gallery into fragment

im trying to implement a fragment inside a navigation slider. I need to create a button in 1 of my fragments to import images from my default gallery. I have tried many codes online, but they don't seem to be working.
It depend on android version you are using if you test your app in android 6.0 than you should ask permission at runtime else image is not returned by android.
For Pre-Marshmallow you can use code:
Intent pickIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
pickIntent.setType("image/*");
startActivityForResult(pickIntent, 0);
and then override method
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, requestCode, data);
try {
// When an Image is picked
if (requestCode == 0 && resultCode == Activity.RESULT_OK && null != data) {
Uri selectedImage = data.getData();
image.setImageBitmap(BitmapFactory.decodeFile(getRealPathFromURI(selectedImage)));
} else
new ShowErrorToast(getActivity(), "Hey! your Android phone is busy");
} catch (Exception e) {
}
}
than use method to get path of image
public String getRealPathFromURI(Uri data) {
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(data
, filePathColumn, null, null, null);
String picturePath = "";
if (cursor != null) {
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
picturePath = cursor.getString(columnIndex);
cursor.close();
}
return picturePath;
}
For Marshmallow you should ask for permission runtime and follow above code

Save a ImageView state after exit App (onSaveInstanceState)

I have a app where i allow the user to pick a picture from galery and it use as PROFILE PICTURE, pick a picture and set in a "ImageView" in my app.
The problem is that when the app is closed, ou the activity is changed the picture desapear, or back de default picture again, i want save this picture state for when back to activity or when close and re-open the app the picture continue there and dont need set all over again.
I am new in developing, please if you can help me looking my code below and give make the needed changes and give me the ready code i will be really deeply thankful cause i spent several days for do it and still i cant. I need a ready code cause i am new in developing and if you try explain something i will not understand.
Here is my code where i pick the picture:
public class MainActivity extends Activity {
private static int RESULT_LOAD_IMG = 1;
String imgDecodableString;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void loadImagefromGallery(View view) {
// Create intent to Open Image applications like Gallery, Google Photos
Intent galleryIntent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
// Start the Intent
startActivityForResult(galleryIntent, RESULT_LOAD_IMG);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
// When an Image is picked
if (requestCode == RESULT_LOAD_IMG && resultCode == RESULT_OK
&& null != data) {
// Get the Image from data
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
// Get the cursor
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
// Move to first row
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
imgDecodableString = cursor.getString(columnIndex);
cursor.close();
ImageView imgView = (ImageView) findViewById(R.id.imgView);
// Set the Image in ImageView after decoding the String
imgView.setImageBitmap(BitmapFactory
.decodeFile(imgDecodableString));
} else {
Toast.makeText(this, "You haven't picked Image",
Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Toast.makeText(this, "Something went wrong", Toast.LENGTH_LONG)
.show();
}
}
}
Try overriding the onSaveInstanceState Activity lifecycle methods. Here's a blog post regarding its best practices.
http://inthecheesefactory.com/blog/fragment-state-saving-best-practices/en

handling result from activity to a fragment

I have a fragment which contains four images each image when clicked it opens a gallery for the user to select image from there in the activity result when retrieving the image name and path I'm passing this result to an activity through intent that handles the cropping of the image in the cropping activity after the cropping is done i don't know how to send back the result of the cropped image to the fragment and place it in the image view same process is done for the 4 images how can i achieve that. Here is my starting code.
enter code here
attach_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
pickFromGallery();
}
});
private void pickFromGallery()
{
Intent galleryIntent = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, RESULT_LOAD_IMG);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
// When an Image is picked
if (requestCode == RESULT_LOAD_IMG && resultCode == getActivity().RESULT_OK
&& null != data) {
// Get the Image from data
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
// Get the cursor
Cursor cursor = getContext().getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
// Move to first row
assert cursor != null;
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
imgDecodableString = cursor.getString(columnIndex);
cursor.close();
startCrop(imgDecodableString);
} else {
Toast.makeText(getActivity(), "You haven't picked Image",
Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
Toast.makeText(getActivity(), "Something went wrong", Toast.LENGTH_LONG)
.show();
}
}
private void startCrop(String imageUri)
{
Intent intent = new Intent(getActivity(),CropActivity.class);
intent.putExtra("Image",imageUri);
startActivity(intent);
}
}
in my cropping activity here is my code
enter code here
Intent i = getIntent();
image = i.getStringExtra("Image");
Log.d("Image",""+image);
DisplayMetrics metrics = getResources().getDisplayMetrics();
int imageWidth = (int) ( (float) metrics.widthPixels / 1.5 );
int imageHeight = (int) ( (float) metrics.heightPixels / 1.5 );
bitmap = BitmapLoadUtils.decode(image, imageWidth, imageHeight);
imageCropView.setImageBitmap(bitmap);
imageCropView.setAspectRatio(3, 2);
findViewById(R.id.crop_btn).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
if(!imageCropView.isChangingScale())
{
Bitmap b = imageCropView.getCroppedImage();
}
}
});
after cropping here the image i need to set this cropped image in the image view in the fragment same for the rest of the image with the same process how can this be achieved .
Any help would be appreciated.
You can start the activity using startActivityForResult(...) method, so you can send data back.
As for how to pass the bitmap using intent, check this stackoverflow question.
Then you can get the Bitmap on the onActivityResult(...) method of your fragment.
Passing bitmaps via intents is not a good practice and will not work if the bitmap is large and therefore should be avoided.
I would suggest u to save the bitmap on disk and pass the path of the saved image to the fragment. Check the edit of the accepted answer in this post
Also shouldn't call startActivity() from a fragment. It should be done from the another activity. Check this Communicating With Fragments Guide

Does child activity of TabActivity supports onActivityResult() method?

I know there are lots of question related to my question, but i dint get any answer who will solve my problem, Basically my requirement is choose the image from gallary and set that image back to ImageView of child activity of Tab Activity, but in TabActivity i unable to get call to the onActivityResult() method, Since yesterday i was trying to search another way to solve the issue, as i found onActivityResult() will not be going to work i tried to pass image using bundle but i was getting !!! FAILED BINDER TRANSACTION !!! error, how do i handle above situations, please suggest me way to call onActivityResult() method into child activity of TabActivity, Thanks in advance.
My Code is
public void openGallary(int req_code) {
Intent i = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, req_code);
}
Here is my onActivityResult() method in which i passed requestcode from openGallary() method:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK
&& data != null) {
Uri pickedImage = data.getData();
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]));
imgShowLocationImage.setImageBitmap(BitmapFactory
.decodeFile(imagePath));
cursor.close();
}}
Make this on button pick this will take you to gallery where you will be able to pick image.
Intent i = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, LOAD_IMAGE_RESULTS);
And then you call onActivityResult like this .
if (requestCode == LOAD_IMAGE_RESULTS && resultCode == RESULT_OK && data != null)
{
Uri pickedImage = data.getData();
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]));
// image.setImageBitmap(BitmapFactory.decodeFile(imagePath));
image.setImageBitmap(BitmapFactory.decodeFile(imagePath));
cursor.close();
}
This way picked image will apper in your ImageView.

Unable to select particular images using ACTION_PICK intent

I'm using an intent like this:
Intent intent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI);
And in onActivityResult() I have this:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode != Activity.RESULT_OK) {
return; // user cancelled
}
Uri imageUri = data.getData();
if (imageUri == null) {
// (code to show error message goes here)
return;
}
// Get image path from media store
String[] filePathColumn = { android.provider.MediaStore.MediaColumns.DATA };
Cursor cursor = this.getContentResolver().query(imageUri, filePathColumn,
null, null, null);
if (cursor == null || !cursor.moveToFirst()) {
// (code to show error message goes here)
return;
}
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String imagePath = cursor.getString(columnIndex);
cursor.close();
if (imagePath == null) {
// error happens here
}
}
When I select images from particular albums like "Posts", "Profile Photos" (see screenshot) I'm unable to get the image path in onActivityResult(). Images from other albums can be selected with no problems.
I've tried adding intent.putExtra("return-data", true) but data.getExtras() returns null in onActivityResult().
There is similar question here, but no one answered it.
Please help!
hops this will helps you ....
ACTIVITYRESULT_CHOOSEPICTURE is the int you use when calling startActivity(intent, requestCode);
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == ACTIVITYRESULT_CHOOSEPICTURE) {
BitmapFactory.Options options = new BitmapFactory.Options();
final InputStream ist = ontext.getContentResolver().openInputStream(intent.getData());
final Bitmap bitmap = BitmapFactory.decodeStream(ist, null, options);
ist.close();
}
}
if above code doesn't work than just refer this link... it will surly shows the way
http://dimitar.me/how-to-get-picasa-images-using-the-image-picker-on-android-devices-running-any-os-version/
try this:
String selectedImagePath = imageUri.getEncodedPath();
it works for me using gallery image picker
maybe this:
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), data.getData());

Categories

Resources