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
Related
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());
}
}
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.
So I am trying to use SharedPreferences to pass a value from the Activity to a Class. The problem is the following:
On initial loading of the Activity, the value is stored in SharedPreferences but if I exit the Activity and return back, and try to update the value, the SharedPreferences does not seem to update and stays at the value of the initial load of the Activity.
Some class function
private void populatePlayerQueue(){
int category_index;
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this.getContext());
category_index = sharedPreferences.getInt("selected_category", 0);
}
Activity onResume
#Override
public void onResume() {
super.onResume();
int tmp = Integer.parseInt(getIntent().getStringExtra("CategoryIndex"));
//store the category in the shared preferences
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt("selected_category", tmp);
editor.commit();
}
What I am trying to do:
I have to send an integer from the activity to a specific class and if I come back to the activity then I need to store the update value and so the class will be able to access the newly updated value again. I only have access to the context and not the activity. This causes errors if I try to create an interface callback to communicate with the activity. So this option is eliminated, hence I am trying anything I can to do that.
For some better result remove the SharedPreference through its key at the time of exit application.
In your case when you exit your application just clear the SharedPreference like:
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.remove("selected_category"); //Just remove it by its specific key
editor.commit();
Then it will clearly load and save the new value again when you go back to your application on the same key or you can use new one.
I am getting weird problem with my app.
I have set-up one SharedPreference, like this
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(this);
flag = prefs.getBoolean("handle_calls", false);
if (flag) {
SharedPreferences.Editor editor = prefs.edit();
editor.clear();
editor.putBoolean("checkFlag", true);
editor.commit();
}
it was working fine some days before, but now this code is working fine but when I try to read these preferences in my SmsReceiver Class SharedPreferences doesnt read these values and default values are read (false)...Sometimes it work and most of the time it doesnt work at all!
Here is how I am reading the SharedPreferences
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
SmsManager sms = SmsManager.getDefault();
//flag = prefs.getBoolean("handle_calls", false);
checkFlag = prefs.getBoolean("checkFlag", false);
checkDecisionFlag = prefs.getBoolean("checkDecisionFlag", false);
This checkDecisionFlag is working fine but checkFlag is taking default values.
Really pissed! Please Help!
remove the editor.clear(); from if condition. as clear will clear all the data from SharedPreference.
if (flag) {
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("checkFlag", true);
editor.commit();
}
Solved it!
This code was fine, instead the problem was with the life-cycle oriented. I had one another SharedPreference on which this depend. That was getting false again and again.
I think you wanted to use if (!flag) (not flag) on the third line of the first code sample.
I need a little help with Android Shared Preferences. I'm trying to put a boolean type in SP and make it visible from every other activity in my application.And I want to be able to change the state of boolean type to true/false from another activity so I can make some changes in the UI depending on that boolean value.
For now I'm using this piece of code,which I understand but it's not correct.
Here it is :
Activity 1:
boolean isLoggedIn = false;
SharedPreferences isLogged = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = isLogged.edit();
editor.putBoolean("isLoggedIn", isLoggedIn);
editor.commit();
Activity 2 :
boolean isLogged=true;
int mode = Activity.MODE_PRIVATE;
SharedPreferences mySharedPreferences;
mySharedPreferences=getSharedPreferences("isLoggedIn",mode);
mySharedPreferences.edit().putBoolean("isLoggedIn", isLogged);
boolean bool = mySharedPreferences.getBoolean("isLoggedIn",false);
Log.w("Boolean","Boolean state : "+bool);
In Activity 2 try using like this and it will work
mySharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
and remove below line
mySharedPreferences.edit().putBoolean("isLoggedIn", isLogged);
Put edit.commit(); after mySharedPreferences.edit().putBoolean("isLoggedIn", isLogged);
This will help you to get correct value.