Save a ImageView state after exit App (onSaveInstanceState) - android

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

Related

On button click choose image from gallery and set in another activity's imageView

I have two activities in one i have a button and in second i have a ImageView, Now i want if i click on first activity's button then i go to gallery and pick an image when i select an image then it will automatically set in second activity's ImageView, My code is working when i set image in same acticity's imageView but i want set the image in second activity's ImageView. Please tell me what code i need to write in SecondActivity, My first Activity is(Select_Image):-
public class Select_Image extends Activity {
Button button;
public static final int PICK_FROM_GALLERY = 100;
Bitmap bitmap;
String imagePath = " ";
Uri uri;
ImageView image;
String path = " ";
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.select_image);
button = (Button)findViewById(R.id.select_btn);
image = (ImageView)findViewById(R.id.edit_image_id); //This is second Activity's ImageView id.
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
galleryIntent();
}
});
}
public void galleryIntent(){
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_FROM_GALLERY);
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == MainActivity.RESULT_OK) {
if (requestCode == PICK_FROM_GALLERY){
}
onSelectFromGalleryResult(data);
}
}
public void onSelectFromGalleryResult(Intent data){
if (data != null) {
try {
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), data.getData());
}
catch (Exception e) {
e.printStackTrace();
}
}
uri = getImageUri(this, bitmap);
imagePath = getRealPathFromUri(uri);
image.setImageBitmap(bitmap);
}
private String getRealPathFromUri(Uri uri) {
Cursor cursor = null;
try {
String[] proj = {MediaStore.Images.Media.DATA};
cursor = this.getContentResolver().query(uri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String ss = cursor.getString(column_index);
return cursor.getString(column_index);
} finally {
if (cursor != null) {
cursor.close();
}
}
}
private Uri getImageUri(Select_Image select_image, Bitmap bitmap) {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
Toast.makeText(select_image, "Image uploaded Successfully", Toast.LENGTH_LONG).show();
path = MediaStore.Images.Media.insertImage(select_image.getContentResolver(), bitmap, "Title", null);
return Uri.parse(path);
}
}
Second Activity(MainActivity)
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
In your onActivityResult, you got the result which is used by your current activity. If an image is selected you got your result on onActivityResult.Here, you can pass this imageUrl in your second activity and open image in your second activity. If you have still any doubt you can ask me.
To sum up, you want to interact with Activity A, start a task then receive the result in Activity B, it's impossible. But you can get the same behavior by 2 options:
Start Activity B on Activity A's button clicked. In Activity B's onCreate, start the image selector and get the result from there.
Start the image selector in A's button clicked, get the result and then pass the result to B using startActivity Intent.
Prefer the first option because it makes the code cleaner, Activity B does its own job and Activity A doesn't need to know about it. Moreover, you save some performance when serialize/deserialize the param from A to B, make the activity transition smoother

When I change screen orientation using sensor ImageView becomes blank in android?

Here i am using following code
Here the problem is to using following code i am picked image from gallery and set in ImageView but when i rotate screen the ImageView become blank. So give me the solution for how to save state and displaying the image.
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(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);
//Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
//.setAction("Action", null).show();
//Intent i = new Intent(MainActivity.this,firstActivity.class);
//startActivity(i);
}
});
}
#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();
}
}
Time rotation restart the activity. This restart must be prevented.
Add the following code in the manifest file in the desired activity
android:configChanges="keyboard|keyboardHidden|orientation|screenSize"
use this in manifest activity tag.
android:screenOrientation="nosensor"
When you change orientation, if you doesn't add
android:configChanges="keyboardHidden|orientation|screenSize"
in manifest -> activity will re-create. Please re-check it.

Create a class specifically for retrieving an image?

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

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

Attach imageView to email

I want to attach imageView to send through Android mail services. This is how i get image from Gallery in Activity A:
public class Activity A extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_gallery);
private static int RESULT_LOAD_IMAGE = 1;
Button viewcards=(Button)findViewById(R.id.viewcards);
viewcards.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
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();
Intent newdata = new Intent(SavedCards.this, Cardd.class);
newdata.putExtra("picture_path", picturePath);
startActivity(newdata);
}
}}
Transfer image to another class and and put imageView in Activity B:
public class Activity B extends Activity {
private ImageView cardimage;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.carddd);
String temp = getIntent().getStringExtra("picture_path");
cardimage = (ImageView) findViewById(R.id.cardimage);
cardimage.setImageBitmap(BitmapFactory.decodeFile(temp));
and in Activity B, i want to attach this image into e-mail by onClick.
txtsend=(TextView) findViewById(R.id.txtsend);
txtsend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
As a reference, how image can attach e-mail is here, but this is to pick from gallery.
How to do this by taken image which is already set on imageView. Thank you.
In your code you setup image to ImageView from file in Activity B. And you know path to this picture file. When you send email just attach this file.
Uri uri = Uri.parse("file://" + attachmentFile);
emailIntent.putExtra(Intent.EXTRA_STREAM, uri);
You can use ImageView's getDrawable method see this http://developer.android.com/reference/android/widget/ImageView.html#getDrawable()
So something like,
Bitmap imgViewBmp = ((BitmapDrawable)cardImage.getDrawable()).getBitmap();
Should work.
PS: I would suggest you to first check the api reference docs for any class you want to use. Chances of finding what you are looking for is quite high. Next best thing would be to actually google what you want to solve, if that doesn't work then "rephrase" you words and try again. The chances that you will find your solution are doubled (if not more) with the latter!

Categories

Resources