How to save image path using Shared Preferences - android

I have an activity that opens another activity to get a camera gallery pic. The picture comes back to my original activity and rest in an imageView. That's working fine. How do I save the image so when the user comes back later, or kills to app the image is still there. I know I am supposed the use Shared Preferences to get the image path and not save the image itself but I just don't know how do that.
Activity A
private ImageView im1;
private String selectedImagePath;
private static final int SELECT_PICTURE = 1;
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);
im1.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);
};
((Button)dialogView.findViewById(R.id.button3))
.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);
}});
Activity B
Button send = (Button) findViewById(R.id.send);
send.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent intent=new Intent();
setResult(RESULT_OK, intent);
Bundle bundle=new Bundle();
bundle.putInt("image",R.id.showImg);
intent.putExtras(bundle);
finish();
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);
img.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);
}

Override onPause() method in Activity with an image (to understand why onPause, check life cycle of an Activity diagram here: http://developer.android.com/reference/android/app/Activity.html) like this:
#Override
protected void onPause() {
SharedPrefrences sp = getSharedPreferences("AppSharedPref", 0); // Open SharedPreferences with name AppSharedPref
Editor editor = sp.edit();
editor.putString("ImagePath", selectedImagePath); // Store selectedImagePath with key "ImagePath". This key will be then used to retrieve data.
editor.commit();
super.onPause();
}
It means that whenever this Activity goes into background, the image path will be saved in SharedPreferences with name AppSharedPref - this name can be whatever you like, but you need to use the same one when retrieving data.
Then override onResume() method in the same Activity so that you can retrieve image path when Activity comes to foreground:
#Override
protected void onResume() {
SharedPreferences sp = getSharedPreferences("AppSharedPref", 0);
selectedImagePath = settings.getString("ImagePath", "");
super.onResume();
}
You may also want to play with overriding other methods, like for example onStart() according to diagram, but this I leave to you.

You could use the "selectedImagePath" in passing intents from one Activity to another.
in Activity A.
Intent intent = new Intent(this , Activity.class);
intent.putExtra("imagePath", selectedImagePath );
and to get it in Activity B,
String strImagePath = getIntent().getExtras().getString("imagePath");

String imagePath = ... ;
SharedPrefrences prefs = getSharedPreferences("application_settings", 0);
Editor editor = prefs.edit();
editor.putString("image_path", imagePath);
editor.commit();

SharedPreferences prefs = this.getSharedPreferences(
"com.example.app", Context.MODE_PRIVATE);
To read preferences:
String path = prefs.getString("key", default value);
To edit and save preferences
prefs.edit().putString("key", value).commit();

Related

How to persist a android.net.Uri (referencing an image in Gallery) in Android

Through the following snippet, I get an image Uri:
Intent galleryIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent, RESULT_PHOTO_ALBUM);
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case RESULT_PHOTO_ALBUM:
if (data != null && data.getData() != null) {
displayAttachedPhoto(data.getData());
}
break;
Everything works but when I tried to persist android.net.Uri by:
String uriString = uri.toString();
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("my_image", uriString);
editor.apply();
That's how I tried to restore:
String uriString = sharedPref.getString("my_image", "");
Uri uri = Uri.parse(uriString);
imageView.setImageURI(uri);
The imageView doesn't display at all. In fact, the Uri object reconstructed is not the identical object. Is there any way to fix this?
to save value in SharedPreferences ,you must use : commit or apply.
Try this code..
write time..
SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME,MODE_PRIVATE).edit();
editor.putString("my_image", uriString);
editor.apply();
getting time ..
SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
String image = prefs.getString("my_image", null);
define this method..
/**
* this method used to get camera image path.
*
* #param
* #return
*/
public String getPathFromURI(Uri contentUri) {
String res = null;
String[] proj = {MediaStore.Images.Media.DATA};
Cursor cursor = getActivity().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;
}
after that in onActivityResult method passs..
Uri uri = data.getData();
String path = getPathFromURI(uri);
after that path it store into sharedPreferences.

How to store/get image in PreferencesScreen

I have a preferences screen where I want a user to select an image. I do this just right. I even manage to display the image after it's selected. But, my question is this. How do I "get" the image? Like getBoolean(), getString(), etc. there is no "getImageUri" or whatever.
Here's my current code for opening the picker and assigning my own ImageView the chosen image
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.layout.activity_settings);
Preference prefereces = findPreference("test");
prefereces.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference preference) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
int PICK_IMAGE = 1;
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE);
return true;
}
});
}
protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
if (resultCode == RESULT_OK) {
Uri selectedImage = imageReturnedIntent.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 filePath = cursor.getString(columnIndex);
cursor.close();
ImageView ok = (ImageView)findViewById(R.id.incognitoView);
ok.setImageURI(selectedImage);
Log.d("OK", "Data Recieved! " + filePath);
}
}
Here's a screenshot to better explain:
Click "select image" brings up the Gallery Picker - actually picking an image puts the image at the center of the view, like so.
Help is appreciated!
If you use a PreferenceClickListener, you have to implement the logic of saving/retrieving the preference yourself.
You can use a SharedPreferences.Editor to edit SharedPreferences:
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sp.edit();
editor.putString("image_uri", imageUri);
editor.apply();
However, I would not recommend to store the image URI inside a SharedPreference, because the URI might not be accessible later. Instead, I would store the image in the file system and put a reference inside a SharedPreference.
You can read a image from URI with a ParcelFileDescriptor:
ParcelFileDescriptor pfd = this.getContentResolver().openFileDescriptor(imageUri, "r");
FileInputStream is = new FileInputStream(pfd.getFileDescriptor());
...
(I would move all code for saving/retrieving preference to an own class.)
public class MySettings {
public static final String PREF_KEY_IMAGE_REF = "pref_image_ref";
private Context mContext;
private SharedPreferences mPreferences;
public MySettings(Context) {
mContext = context;
mPreferences = PreferenceManager.getDefaultSharedPreferences(context);
}
public String getImageRef() {
return mPreferences.getString(PREF_KEY_IMAGE_REF, null);
}
public void setImageRef(String imageRef) {
SharedPreferences.Editor editor = mPreferences.edit();
editor.putString(PREF_KEY_PREF_KEY_IMAGE_REF, imageRef);
editor.apply();
}
}

pass image uploaded from user gallery to another activity

i have a registration activity in which user can upload image from his gallery, i want to pass this photo to navigation drawer in main activity & also to userprofile activity and i cant find the way how, code for RegistrationActivity:
code for RegistrationActivity:
public class RegisterActivity extends AppCompatActivity implements View.OnClickListener {
de.hdodenhof.circleimageview.CircleImageView uplo;
private static int RESULT_LOAD_IMAGE = 1;
Context ctx = this;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
final Button bRegister = (Button) findViewById(R.id.bRegister);
//upload profile image
uplo = (de.hdodenhof.circleimageview.CircleImageView) findViewById(R.id.uploadimage);
uplo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(
Intent.ACTION_PICK,
MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
}
});
bRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(RegisterActivity.this,MainActivity.class);
i.putExtra("picture", String.valueOf(uplo));
startActivity(i);
finish();
}
});
}
//to take the chosen image from user mobile gallery
#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();
uplo.setImageBitmap(BitmapFactory.decodeFile(picturePath));
}
}
a sample of code would be very helpful
thank you
Send the intent
Intent intent = new Intent(Home.this, Upload.class);
intent.putExtra("picture", thumbnail);
and receive in other other activity
Bitmap bitmap = (Bitmap) intent.getParcelableExtra("picture");
hope it work :)
If you want to send the image, just send the path.
change it to.
bRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(RegisterActivity.this,MainActivity.class);
i.putExtra("picture", picturePath);// send path
startActivity(i);
finish();
}
});
and receive the path in another activity.
and set as..
.setImageBitmap(BitmapFactory.decodeFile(picturePath));
2nd If you want to access picture on other activities
Just put the path in shared preferences as USER_DP string. and get it whenever you want. eg.
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
shared.edit().putString("USER_DP",picturePath).commit();// like this
You can use below code to save your path in to shared preferences and you can fetch it as per your requirement. initialise shared preference
SharedPreferences sharedPref = context.getSharedPreferences(SHARED,Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
save path
public void savePath(String key,String path){
editor.putString(key, path);
editor.commit();
}
retrieve path in your specific class--
` public String getPath(String key ){
if (sharedPref.contains(key)){
String path="";
path=sharedPref.getString(key, " ");
return path;
}
return "";
} `

How to use onSaveInstanceState to remember image uploaded by user

in my app I let the user to upload an image from his/her phone. When the user closes the app and then open it again I want the image to be still there, but it doesn't work. So far my code is:
private static int SELECT_PICTURE = 0;
ImageView imgImage;
Button btnUploadImage;
String filePath;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState != null) {
filePath = savedInstanceState.getString("FILE_PATH");
imgImage.setImageBitmap(BitmapFactory.decodeFile(filePath));
}
btnUploadImage = (Button) findViewById(R.id.btnUploadImage);
imgImage = (ImageView) findViewById(R.id.imgImage);
btnUploadImage.setOnClickListener(MainActivity.this);
}
#Override
public void onClick(View view) {
selectImage();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
Bitmap bitmap = getPath(data.getData());
imgImage.setImageBitmap(bitmap);
}
}
private Bitmap 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();
filePath = cursor.getString(column_index);
Bitmap bitmap = BitmapFactory.decodeFile(filePath);
return bitmap;
}
private void selectImage() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), SELECT_PICTURE);
}
#Override
public void onSaveInstanceState(Bundle outState) {
outState.putString("FILE_PATH", filePath);
super.onSaveInstanceState(outState);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
savedInstanceState.getString("FILE_PATH");
super.onRestoreInstanceState(savedInstanceState);
}
}
Can you help me with the code? I think the problem is in the onCreate method, but I don't know how to change the code. Thank You.
The RestoreInstanceState could be used when user rotate screen, or change languaje (that force Activity to destroy and be recreated once).
If the user close the app, that does not work, for that reason you could use Shared Preferences, or save information in another place.
This is how you can use the Shared Preferences:
For save some key:
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.String("ImagePath", yourImagePathToSave);
editor.commit()
And to get again:
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
String imagePathSaved = sharedPref.getString("ImagePath", null); //null represents the default value.
Android Developer Docs
getString returns a String variable and you need to assign this to your field
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
filePath = savedInstanceState.getString("FILE_PATH");
super.onRestoreInstanceState(savedInstanceState);
}
but this is only for configuration changes (like rotating your screen).
If you want the filepath to be remembered when your app is "closed" i.e. te user quits out and swipes it from the recent lists. Then you need to save the file path to memory with SharedPreferences: https://developer.android.com/training/basics/data-storage/shared-preferences.html
in the situation of closing and reopening app you can't use on onSaveInstanceState. you can save the pictures path in the SharedPreferences and then retrieve it and load image in the ImageView in your onCreate method
SharedPreferences sharedPreferences =
context.getSharedPreferences("user", Context.MODE_PRIVATE);
String imagePath = sharedPreferences.getString("image","");
if(!imagePath.isEmpty()){
Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
imgImage.setImageBitmap(bitmap);
}

How to Save multiple images to ImageView using Shared Preferences

I have a activity with a couple of ImageViews. The user can LongPress an ImageView and they have the option of getting any image from the camera gallery. I am trying to save the imagepath of those images so that when the user closes and opens the app again the image will still be in the imageView. I dont understand why this isn't working.
Here is my Activity A where the imageView is
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);
im1.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);};
#Override
protected void onPause() {
SharedPreferences sp = getSharedPreferences("AppSharedPref", 1); // Open SharedPreferences with name AppSharedPref
Editor editor = sp.edit();
editor.putString("ImagePath", selectedImagePath); // Store selectedImagePath with key "ImagePath". This key will be then used to retrieve data.
editor.commit();
super.onPause();
}
protected void onResume1() {
SharedPreferences sp = getSharedPreferences("AppSharedPref", 1);
selectedImagePath = sp.getString("ImagePath", "");
super.onResume();
}
And Activity B gets the cam gallery pic and sends back to Activity A
Button send = (Button) findViewById(R.id.send);
send.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent intent=new Intent();
setResult(RESULT_OK, intent);
Bundle bundle=new Bundle();
bundle.putInt("image",R.id.showImg);
intent.putExtras(bundle);
finish(); }
});
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);
img.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);
}
Make:
#Override
protected void onResume() {
SharedPreferences sp = getSharedPreferences("AppSharedPref", 1);
selectedImagePath = sp.getString("ImagePath", "");
Bitmap myBitmap = BitmapFactory.decodeFile(selectedImagePath);
im1.setImageBitmap(myBitmap);
super.onResume();
}
instead of:
protected void onResume1() {
SharedPreferences sp = getSharedPreferences("AppSharedPref", 1);
selectedImagePath = sp.getString("ImagePath", "");
super.onResume();
}
Because your activity extends Activity class, which has this method declared and implemented. This method is called after Activity returns to foreground. What you want is to override this method so that it does what you want it to do.

Categories

Resources