I have a series of ImageButtons in my app. Through the app, the user can set the background of the ImageButton to a drawable file.
This is working perfectly fine, when the user selects the image they would like and clicks a refresh button, the ImageButton's image changes.
The issue is, when I go to other activities the changed ImageButton's go and are returned to the default image.
I've been trying to do this through SharedPreferences. I've tried to get this working using all of the other similar questions on here with no luck.
I'm a complete beginner when it comes to SharedPreferences and I know that storing images isn't what it's built for, but it's the only way I can think of to solve my problem.
Any help would be MASSIVELY appreciated! Thanks in advance guys.
What I know about storing images with SharedPreferences:
I know that I have to convert the drawbable to a bitmap and then encode that into Base64 (because SharedPreferences will accept strings). I have done this, and I think the encoding is working.
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
grey11.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
byte[] grey11base64 = byteArrayOutputStream.toByteArray();
final String encodedGrey11 = Base64.encodeToString(grey11base64, Base64.DEFAULT);
In my main activity (where the images are displayed), I currently have OnCreate and onStop methods and an onClick for the refresh button.
EDIT:
In my onCreate(Bundle savedInstantState):
final SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt("drawableAgreen", R.drawable.a);
editor.commit();
Inside my Refresh button:
int drawableId = sharedPref.getInt("drawableId", 0);
ImageButton.setBackgroundResource(drawableId)
Just store the drawable id in SharedPreferences and refer it.
// store drawable id in SharedPreferences
SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt("drawableId", R.drawable.btn_background);
editor.commit();
// Read from sharedPref and set background
int drawableId = sharedPref.getInt("drawableId", 0);
ImageButton imageButton = (ImageButton) findViewById(R.id.imageButton);
imageButton.setBackgroundResource(drawableId);
Your'd better not store drawable id ,for every time compile your app, the id may be different.You could store drawable name in SharedPreferences and get those resources id by ResourcesUtils.
public class ResourcesUtils {
private static final String RES_ID = "id";
private static final String RES_STRING = "string";
private static final String RES_DRABLE = "drable";
public static int getId(Context context,String resName){
return getResId(context,resName,RES_ID);
}
public static int getStringId(Context context,String resName){
return getResId(context,resName,RES_STRING);
}
public static int getDrableId(Context context,String resName){
return getResId(context,resName,RES_DRABLE);
}
public static int getResId(Context context,String resName,String defType){
return context.getResources().getIdentifier(resName, defType, context.getPackageName());
}
}
Related
I have an ImageView ImageView1, whose background can be set by the user. How can I save the state of that background, so that when the user closes the app and reopens it, the background of ImageView1 is still the same?
Is it possible with onSaveInstanceState or do I have to write something different, and if so: How can I do this?
Right now I have:
public void onSaveInstanceState(#NonNull Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("ImageView1", imageView1);
but imageView1 gets red underline, even though declared before to id of ImageView
You can use shared preferences:
Save to shared preferences on change.
Get from shared preferences on app reopen.
Check documentation for more:
https://developer.android.com/training/data-storage/shared-preferences
You can use SharedPreferences as follows:
SharedPreferences sharedPreferences;
sharedPreferences = getSharedPreferences("data", 0);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("image", //put image path here);
editor.apply();
Then override the onResume method as follows
#Override
protected void onResume() {
super.onResume();
SharedPreferences sharedPreferences = getSharedPreferences("data", 0);
String imagePath = sharedPreferences.getString("image", ""); //default value is empty
}
Then load image using picasso or glide like..
Picasso.get().load(imagePath).into(imageview);
I need to fix one problem.
In the Android Studio I am trying to use SharedPreferences and store the font type but there is something wrong with my code. Please help me out.
// Load Text Font start
SharedPreferences myTextFont = this.getSharedPreferences("MyTextFont", MODE_PRIVATE);
textFont = myTextFont.getInt("font", textExample.getTypeface().getStyle());
textExample.setTypeface(textExample.getTypeface());
textView3.setTypeface(textExample.getTypeface(), textExample.getTypeface().getStyle());
// Load Text Font end
//Font Buttons start
final Typeface typeface1 = ResourcesCompat.getFont(this,R.font.mkhatvruli);
type_1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
textExample.setTypeface(typeface1);
SharedPreferences myTextFont = getSharedPreferences("MyTextFont", MODE_PRIVATE);
SharedPreferences.Editor editor = myTextFont.edit();
editor.putInt("font", textExample.getTypeface().getStyle());
editor.commit();
}
});
When I click, the button font type changes in the text view but does not store.
I think that something is wrong here:
editor.putInt("font", textExample.getTypeface().getStyle());
I am creating an android application, I am displaying images from drawable folder based on the numbering, my activity start showing images from number 1 and I am using buttons to show next or previous image.
I am trying to save the value of image user was viewing while pressed back button using shared preferences. my code looks like this
private int currentPage = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_read);
final Button btnNext = findViewById(R.id.btnNext);
final Button btnBack = findViewById(R.id.btnBack);
listOfObjects = getResources().getStringArray(R.array.object_array);
images = getResources().obtainTypedArray(R.array.object_image);
itemImage = (ImageView)findViewById(R.id.imgSpace);
final Spinner spinner = (Spinner)findViewById(R.id.spinner);
ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String>(this,R.layout.my_spinner, listOfObjects);;
spinnerAdapter.setDropDownViewResource(R.layout.my_spinner);
spinner.setAdapter(spinnerAdapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
itemImage.setImageResource(images.getResourceId(spinner.getSelectedItemPosition(), -1));
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
final ImageView img = findViewById(R.id.imgSpace);
PhotoView photoView = (PhotoView) findViewById(R.id.imgSpace);
img.setImageResource(getResources().getIdentifier("page_"+currentPage,"drawable",getPackageName()));
btnNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(spinner.getSelectedItemPosition() < spinner.getAdapter().getCount()){
spinner.setSelection(spinner.getSelectedItemPosition()+1);
}
}
} );
}
currentPage is the variable which I want to save after pressing back button or to go to any other activity and also if user minimises the application, I want to pass it to main activity in order to show the extra button of resume activity and also to show the exact image the user was seeing before pressing the back button when user clicks on resume activity button.
I am using Chris Banes's photoview to show the image. I know how to pass variables and et them in PHP however android is new for me. ANy help would be appreciated.
SharedPreferences prefs = getSharedPreferences("nameOfSharedPreference", MODE_PRIVATE);
SharedPreferences.Editor editor = getSharedPreferences("nameOfSharedPreference", MODE_PRIVATE).edit();
editor.putInt("image", R.imageID).commit();
#Override
onBackPressed(){
image = prefs.getInt("image", defaultValue) //Default value is taken if the pref doesn't exist yet
}
onBackPressed() is called automatically by android when pressing the phone back button. You can call it manually:
onBackPressed();
I don't understand the question completely but you could write:
SharedPreferences prefs = getSharedPreferences("nameOFPref", MODE_PRIVATE);
private int currentPage = prefs.getInt("image", 1);
The way it works is it saves a file in nameOfPref in the "image" section so you get it back when the program launches. Here we put 1 as default value so the value it will take is 1 the first time you launch the program. You should write:
SharedPreferences.Editor editor = getSharedPreferences("nameOfSharedPreference", MODE_PRIVATE).edit();
editor.putInt("image", idOFImageCurrentlyVIewed).commit();
Later in the program each time the user changes image. So it will change the preference and will make sure that when you launch the program back currentImage will take the right value.
In android studio you can look at the file system of emulated phones. For preferences you need to go in Android/data/com.yourPackageName/preferences and you should see your file there if everything goes fine.
So i made a game with a simple score keeping system, It seems that the highscore gets put into the shared prefs correctly, but when trying to load the high score into the activity oncreate the application crashes. this is my code.
SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
int score = sharedPref.getInt("SCORE", 0);
String score2 = Integer.toString(score);
text10.setText(score2);
Not sure what i'm doing wrong so any advice will be great!
Here is my save score code
private void savePref(String key, int value) {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor edit = sp.edit();
edit.putInt(key, value);
edit.apply();
}
From the log you have shared, it is clear that you have not get the TextView properly. Assuming that you have set the layout, do something like this:
text10 = (TextView) findViewById(R.id.your_textview_id);
SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
int score = sharedPref.getInt("SCORE", 0);
String score2 = Integer.toString(score);
text10.setText(score2);
Save SharedPreferences properly, using both name and mode
SharedPreferences sharedPreferences = context.getSharedPreferences("DATA",Context.MODE_PRIVATE);
I think this is happening beacuse, the method that you're using getPreferences(PREFERENCE_MODE_PRIVATE)
returns the preferences saved by Activity's class name as described here :
Retrieve a SharedPreferences object for accessing preferences that are private to this activity. This simply calls the underlying getSharedPreferences(String, int) method by passing in this activity's class name as the preferences name.
So, when you're saving the prefs in SomeActivity it's being saved under the name "SomeActivity"
but when you're getting the prefs in this activity it's returning you the prefs saved under this activity's class name.
So, you should use getSharedPreferences (String name, int mode) method with the same name instead.
source
UPDATE
After looking at the stacktrace looks like your TextView object text10 is null, initialize it and the problem will be solved.
I'm trying to use sharedpreferences to store an integer. Something is wrong though, so the integer won't get saved. Whenever I stop my app the integer won't show up, it isn't there and isn't getting saved. Here's my code that's located in my onCreate() method:
private int point;
//...
SharedPreferences sp = getSharedPreferences("prefs_file",MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.putInt("your_int_key", point);
editor.apply();
SharedPreferences sp1 = getSharedPreferences("prefs_file",MODE_PRIVATE);
int highScoreSaved = sp1.getInt("your_int_key", 0);
Try sp1.commit().
Have a look at the developer guide:
https://developer.android.com/guide/topics/data/data-storage.html#pref