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
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.
As you have mentioned in the comment that you have the images in the res/drawable folder, and you want to save the selected image by the user and load the same when the user reopens the app.
So, the thing you have to do is save the resourceId in the preference and use that value.
It will be something this.
//Suppose this is your selected drawable, you need to save its resourceId to shared preferences which is INT value
val resourceId: Int = R.drawable.your_drawable_image
//save resouceId to sharedPreference
//You can do this to set the Image in the ImageView
your_imageview.setImageDrawable(getDrawable(resourceId))
I hope this will be of any help to you.
Related
Im making and android app which let the user select an image from the phone and load it to an ImageView. The further process is to send the image as a POST request to a PHP script
It all works fine if I load the image to a File object from the file location, but this require that the user open a setting on the phone which allow the app to access and manage local files..
So, is there a way to read the image from the imagview into a File object?
This is my current working code
val fil = File(getRealPathFromURI(imageUri!!).toString())
if (Build.VERSION.SDK_INT >= 30){
if (!Environment.isExternalStorageManager()){
var getpermission = Intent()
getpermission.setAction(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION);
startActivity(getpermission);
}
}
var reqB = RequestBody.create("image/*".toMediaTypeOrNull(),fil)
var part = MultipartBody.Part.createFormData("file",fil.name,reqB)
Kotlin throws an access error if I try to load it to a File object if the users dont allow it through the settings on the phone. I believe its a security issue on android.
Really what I want to do is
Let the user select an existing image on the phone
Display it in an imageview
Create a function which get the selected image into an MultipartBody.part without the user having to grant the app access to special rights
I get an image from an user which is converted into a bitmap. I then convert the bitmap to a an byte array and send it over JSON to be stored in a database. Then when the user starts the particular activity I want the image to be retrieved form the database and displayed to the user.
In the application a user is able to make a post with a title, description and an image. I want these three variables stored in the database so that when someone else views the post, they are able to see all the content. Also the image would be stored in the database as a blob, i simply use JSON to send the data to an backend application which handles all the communication with the DB.
My problem is that the bitmap that I get seems to be a reference to some memory on the device android.graphics.Bitmap#324a72b which changes every time I run the application although I select the same image. I want to be able to retrieve the actual bitmap so it can be stored in a DB. I'm also not using as web server for storing the images since its a smaller project.
b.buttonNewItemUpImg.setOnClickListener {
val openGalleryIntent = Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
startActivityForResult(openGalleryIntent, ResultLoadImage)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == ResultLoadImage){
if (resultCode == Activity.RESULT_OK){
var temp = MediaStore.Images.Media.getBitmap(this.contentResolver, data!!.getData())
bitmap = getResizedBitmap(temp!!, maxImageSize)
b.imageView.setImageURI(data!!.getData())
}
}
}
The getResizedBitmap() function simply makes the image smaller.
As described in https://stackoverflow.com/a/57576381/6359367
Use this
var temp = ImageDecoder.createSource(this.getContentResolver(), data!!.getData())
bitmap = ImageDecoder.decodeBitmap(temp);
beware this code was java I tried to adapt it to kotlin you may need to tweak it a bit
Instead of storing the whole image in the database, you should copy images to the app's local storage and then store, path of these copied images to the database, which you can use later to retrieve the images.
Copying image to the app's local storage after getting the selected image uri
//creating an image file in the app's local storage
val dir = requireActivity().getDir(FOLDER_TO_SAVE, Context.MODE_PRIVATE).path
val copiedImageFile = File(dir, UUID.randomUUID().toString() + ".jpg")
val copiedImageUri = Uri.fromFile(copiedImageFile)
//copying selected image to the local storage
data!!.getData().path?.let {
File(it).copyTo(copiedImageFile)
}
Get path of the above copied image, using its uri
copiedImageUri.path.?.let{
val copiedImagePath = "file://$it"
//now save this path to your database
}
Use this saved image path to retrieve the image in any fragment or activity.
I have a form, where I have a imageview and other two text fields. This imageview will be updated with the pic a user chooses(either from gallery or by taking a pic). I will be saving this image in internal storage and other two text fields and saved image path in SQLite DB.
User has option of not choosing any image. In that case I should not save any image, coz I simply be wasting storage. For that how do I distinguish when a user chooses or not to upload any image?
int NEW_PIC=1;
int NO_CHANGE=0;
initialise
img_camera.setTag(AppConfig.NO_CHANGE);
when Changed set
img_camera.setTag(AppConfig.NEW_PIC_ADDED);
if ((int) iv_userImage.getTag() == NEW_PIC_ADDED) {
//New Image Added
}
else{
//Not New
}
Here is my code to display profile picture using gravatar.
ParseUser user = mUsers.get(position);
String email = user.getEmail().toLowerCase();
if (email.equals("")) {
holder.userImageView.setImageResource(R.drawable.avatar_empty);
} else {
String hash = MD5Util.md5Hex(email);
String gravatarUrl = "http://www.gravatar.com/avatar/" + hash + "?s=204&d=404";
Picasso.with(mContext).load(gravatarUrl)
.placeholder(R.drawable.avatar_empty)
.into(holder.userImageView);
}
But it is not showing even my profile picture and loads empty drawable.
You used a bunch of fake emails to populate your friend list, if so, gravatar won't be able to find images for those fake emails. So gravatar will return a 404, and your code will use the default "avatar_empty" image in the drawable folder.
A quick way to test to see if gravatar is working is to change the &d=404 to &d=monsterid and create a friend with a fake email "SDFSDSF#DSFSsdfsFSFSssf.com"
That friend will have an gravatar cartoon image.
Also you can try put http://www.gravatar.com/avatar/edb1260aa6f7f77688deee83e0a088f7?s=204&d=monsterid in your gravatarUrl. It will show picture.
Hope this helps someone , this is the code i used.
get library from:- https://github.com/tkeunebr/gravatar-android (you will get the .jar,, add it to lib)
Code for loading gravatar:
String gravatarUrl = Gravatar.init().with(user.email).size(100).build();
Picasso.with(mContext)
.load(gravatarUrl)
.into((ImageView) convertView.findViewById(R.id.user_avatar));
And if you want to set a default image in case of there is no gravatar set for the email(to override the default gravatar) then use:
String gravatarUrl = Gravatar.init().with(user.email).defaultImage(defaultImageUrl).size(100).build();
Hope this helps someone.
I have listview having customized some textview and one imageview. When I long click on item I have store that item information to the database but the question is how to store image in sdcard and store the relevant path to the database. The image alread download as cache now I don't want to re-download that image.
Is there way to store that Image to the sdcard.
I am using this example to download the images for listview https://github.com/thest1/LazyList
Edit
I got solution
no need to extra process when using this example. Just store the web path of image into the database and pass that imageview into the ImageLoader object with path it'll use the cache images if the image was exist for same URL
No Need to extra process, Using this example it'll will care for future usage also for same URL of image. This will get from the cache directory if the image found that use that image otherwise download it and then use it.
If you use Prime the caching will be transparent, when you request the image again it will grab it from a memory cache if available or a disk cache automatically. It also is really easy to get images with.
You can save your bitmap which you get via Bitmap bitmap=memoryCache.get(url); using save-file-to-sd-card.
You can also get the bitmap from the ImageView(if you want) like:
//say your ImageView object is i;
i = (ImageView) findViewById(R.id.img);
Drawable d = i.getBackground();
Bitmap bitmap = ((BitmapDrawable)d).getBitmap();