Issue
so I'm trying to save an Imageview to sharedpreference so when the user chose an image from the app it self, the Image will be saved and set to the imageview id if that makes sense! and when the user exit my app and reopen it the image will be the same one he saved?
I tried this code but it's giving me errors such as for input string " "
My SharedPreference
CompassBtn.setOnClickListener{
val prefCompass = getSharedPreferences("Drawable", Context.MODE_PRIVATE)
val editor = prefCompass.edit()
editor.putInt("ic_compass", ic_compass.setImageResource(R.drawable.ic_compass1).toString().toInt())
editor.commit()
}
**this is how am trying to retrieve it **
val prfCompass = getSharedPreferences("Drawable", Context.MODE_PRIVATE)
prfCompass.getInt("ic_compass", 0)
please help and thanks in advance
Solution
First of all, if you are new to Android Development, please check Picasso for uploading images. In short, it makes it easier/faster to upload images using resource id/url.
Your question really depends on the type of images you want user to select in the future.
1) If all of the images that can be selected are already in the application you can just save the resource id of image in SharedPreferences
as an int
val sharedPref: SharedPreferences = context.getSharedPreferences("PREFERENCE_NAME", Context.MODE_PRIVATE)
// Resource id is the int under drawables folder ->R.drawable.myImage
fun save(KEY_NAME: String, value: Int) {
val editor: SharedPreferences.Editor = sharedPref.edit()
editor.putInt(KEY_NAME, value)
editor.apply()
}
fun getInt(KEY_NAME: String): Int {
return sharedPref.getInt(KEY_NAME, 0)
}
2) If you are letting user to select from gallery (this is the tricky part) inside onActivityResult
(which gets called after user selects an image with the argument, Intent data
, that includes the information on image). Accessing the data of intent (data.getData())
will give you the URI. Then you need to find the path of the image (path where the image is stored in user's phone) and save it to SharedPreferences
. I will leave getting the path of image as a challenge to you. And when you want to upload the image you can just;
Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
Drawable drawable = new BitmapDrawable(getResources(), bitmap);
myLayoutItem.setBackground(drawable);
3) If you have a server you can just upload your images there and store the url as a string in SharedPreferences/associate url with an image attribute of user. And use Picasso to display the image.
Answered By - Prethia
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.