Load SharePrefs Value into textview - java

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.

Related

How to save resource of ImageButton in SharedPreferences?

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());
}
}

SharedPreferences not saving properly - android

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

Android getPrefernces(int) is undefined

**after doing research and trying too look at stackoverflow solutions and try to applay them and failed in all, this error is still appers.
Iam trying to save data by using SharedPreferences and getPrefernces.
**how can i use it as an array for 10 cells only?(so it will save last ten values ive enterd and i could do sorting by max value)
Code:
public void onClick(View v) {
// TODO Auto-generated method stub
SharedPreferences sharedPref = this.getPrefernces(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
EditText name = (EditText)findViewById(R.id.namep);
editor.putString(name.getText().toString(), score);
editor.commit();
}
In the first line (the defind of sharedPref) ive got this error:
The method getPrefernces(int) is undefined for the type new View.OnClickListener(){}
Ive tried to switch it in few ways no ones works, i cant even call getActivity()function after this. i dont know why my code extends Activity.
Ive tried this soultions:
How to resolve an error: getSharedPreferences(String, int) is undefined for the type new View.OnClickListener(){}
The method setOnClickListener(new View.OnClickListener(){}) is undefined for the type imageButton1
Try this:
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
or
SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
this inside the OnClickListner will be pointing to that anonymous class, not the Activity. So you have to use your Activity reference over there instead.
Change
SharedPreferences sharedPref = this.getPrefernces(Context.MODE_PRIVATE);
to
SharedPreferences sharedPref = Your_Activity_Name.this.getPrefernces(Context.MODE_PRIVATE);
You do it in anonymous class OnClickListener and your "this" points to it. You need to call the method like this
OuterActivity.this.getPreferences(Context.MODE_PRIVATE);
or
OuterFragment.this.getActivity().getPreferences(Context.MODE_PRIVATE);
You have to call the method with the Context object. What is "this" in the above code? Then try #Piotr code.
You can't use
this.getPrefernces(Context.MODE_PRIVATE);
in View.onClickListener because that is not the same instance.
Instead of this you have to use something like that:
public void click(View v) {
SharedPreferences pref = PreferenceManager
.getDefaultSharedPreferences(MainActivity.this);
//Your other code
}
Point is that you have to get sharedPreferrences from activity, not from onClickListener.

SharedPreferences not updating value when returning to Activity, but only keeps initial Activity load value

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.

Android SharedPreferences issue

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.

Categories