Shared Preferences not saving data - android

Initializing highScore array :
score = 0;
sharedPreferences = context.getSharedPreferences("Scores", Context.MODE_PRIVATE);
//initialize the array of high scores
highScore[0] = sharedPreferences.getInt("score1",0);
highScore[1] = sharedPreferences.getInt("score2",0);
highScore[2] = sharedPreferences.getInt("score3",0);
highScore[3] = sharedPreferences.getInt("score4",0);
highScore[4] = sharedPreferences.getInt("score5",0);
Checking For the 4 Highest Values :
highScore[5] = score;
Arrays.sort(highScore);
This is my code for saving data in shared preferences
SharedPreferences.Editor e = sharedPreferences.edit();
for(int j=4;j>=0;j--){
e.putInt("score"+(j+1),highScore[j]);
e.apply();
}

I will suggest to use like that.
SharedPreferences pref;
pref= context.getSharedPreferences("Scores", Context.MODE_PRIVATE);
SharedPreferences.Editor e = pref.edit();
for(int j=4;j>=0;j--){
e.putInt("score"+(j+1),highScore[i]);
}
e.apply();

Instead of commiting after completing the if loop , commit in each iteration of your loop like this:
SharedPreferences.Editor e = sharedPreferences.edit();
for(int j=4;j>=0;j--){
e.putInt("score"+(j+1),highScore[i]);
e.apply();
}
it will work.

Related

OnButton Click Share Preferences

Below is my Code :
public void OnAttendLogin(View view) {
sp = getSharedPreferences("attendlogin", MODE_PRIVATE);
String emp_id = sp.getString("emp_id", null);
InTImeWorker inTImeWorker = new InTImeWorker(this);
inTImeWorker.delegate = (AsyncResponse) this;
inTImeWorker.execute(emp_id);
//shared pref for saving In_time in textview
sp = getSharedPreferences("InTime", MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
String in_time_sharedpref = In_time.getText().toString();
editor.putString("in_time_sp", in_time_sharedpref);
editor.apply();
editor.commit();
out_time_button.setEnabled(true);
in_time_button.setEnabled(false);
}
I want to know what wrong I am Doing in Code ?
How i can use two shared Preferences in android studio ??
You are doing wrong that you are using same reference for both shared preference.
Yes, you can use two shared Preference at one button click.
Create two shared Preference object.
SharedPreferences sp;
SharedPreferences sp2;
SharedPreferences.Editor editorSp ;
SharedPreferences.Editor editorSp2 ;
sp = getSharedPreferences("attendlogin", MODE_PRIVATE);
sp2 = getSharedPreferences("InTime", MODE_PRIVATE);
Final code will be like this:
public void OnAttendLogin(View view) {
sp = getSharedPreferences("attendlogin", MODE_PRIVATE);
String emp_id = sp.getString("emp_id", null);
InTImeWorker inTImeWorker = new InTImeWorker(this);
inTImeWorker.delegate = (AsyncResponse) this;
inTImeWorker.execute(emp_id);
//shared pref for saving In_time in textview
sp2 = getSharedPreferences("InTime", MODE_PRIVATE);
SharedPreferences.Editor editor = sp2.edit();
String in_time_sharedpref = In_time.getText().toString();
editorsp2.putString("in_time_sp", in_time_sharedpref);
editorsp2.apply();
editorsp2.commit();
out_time_button.setEnabled(true);
in_time_button.setEnabled(false);
}
Use one sharedpreference name
"sp = getSharedPreference("attendlogin",MODE_PRIVATE);"
and use different different variable to save data
example:
SharedPreferences.Editor editor = sp.edit();
String in_time_sharedpref = In_time.getText().toString();
editor.putString("in_time_sp", in_time_sharedpref);
editor.apply();
String emp_id = sp.getString("emp_id", null);
i.e. sp should be same with name ""

Retrieving and Updating values using Sharedpreferences

I need to know how can shared preference can be used to keep my data persistent and also update the values.I have written some code.
MainActivity.java
SharedPreferences sPrefs= this.getSharedPreferences(mypreference, Context.MODE_PRIVATE);
if(sPrefs.contains("userData"))
{
retreivepreviousdata=gson.fromJson(sPrefs.getString("userData",""),DataStore.class);
userDataStore.getDataStore().addAll(retreivepreviousdata.getDataRetrieve());
}
userDataStore.getDataStore().add(usrData);
SharedPreferences.Editor prefEditor = getSharedPreferences(mypreference, Context.MODE_PRIVATE).edit();
String saveData = gson.toJson(userDataStore);
prefEditor.putString("userData", saveData);
prefEditor.apply();
Toast.makeText(getApplicationContext(), "Success", Toast.LENGTH_SHORT).show();`
SecondActivity.java
String mypreference="user_data";
SharedPreferences sPrefs= this.getSharedPreferences(mypreference, Context.MODE_PRIVATE);
DataStore dataPull=new DataStore();
Gson gson=new Gson();
String pull=sPrefs.getString("userData","");
dataPull=gson.fromJson(pull,DataStore.class);
System.out.println(dataPull.getDataStore().get(0).toString());
RecyclerView recyclerView=(RecyclerView)findViewById(R.id.recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
MyRecyclerAdapter mAdapter=new MyRecyclerAdapter(dataPull);
recyclerView.setAdapter(mAdapter);
The problem with this code is the values entered are saved and persistent.But when i close,reopen the app and enter values the previous data gets override.
For Storing the value into SharedPreferences
SharedPreferences shared = getSharedPreferences("user_Info", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = shared.edit();
editor.putString("key", value);
editor.commit();
For retrieving values from SharedPreferences just use this
SharedPreferences sharedPref = getSharedPreferences("user_Info", Context.MODE_PRIVATE);
String value = sharedPref.getString("key", "defaultValue");
If you want to store an ArrayList inside SharedPreferences, just convert it to a string. Then, you can "deconvert" it. E.G.
String toSave;
// Object is for your object type. Just get your objects converted to string, that's the point.
for(Object obj : arrayList){
toSave += obj.toString() + "\n";
}
SharedPreferences prefs = getSharedPreferences("PREFS_NAME", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("key", toSave);
editor.apply();
and...
SharedPreferences prefs = getSharedPreferences("PREFS_NAME",Context.MODE_PRIVATE);
String toGet = prefs.getString("key", "");
String[] parts = toGet.split("\n");
for(String s : parts){
arrayList.add(s); // or do whatever conversion you want to get your Object type
}

Multiple SharedPreferences in an android app

SharedPreferences pref = getSharedPreferences("user1", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putString("firstName", firstnameString);
editor.commit();
SharedPreferences pref = getSharedPreferences("user2", Context.MODE_PRIVATE);
...
I am trying to create multiple sharedpreferences using the above code and trying to access all the sharedpreference names i.e user1,user2 etc using the code below.
But i am getting a NULLPointerException while accessing even though the sharedpreference is created.
Map<String,?> allsharedpref = pref.getAll();
if(allsharedpref!=null){
for(Map.Entry<String, ?> entry : allsharedpref.entrySet()){
Toast.makeText(this, entry.getKey()+"\n", Toast.LENGTH_LONG).show();
}
To get values from all SharedPreferences which you have created. you will need to read file names from shared_prefs :
File prefsdir = new File(getApplicationInfo().dataDir,"shared_prefs");
String[] list = prefsdir.list();
String[] preflist = new String[list.length()];
for(int i=0;i<list.length(),i++){
String preffile = list[i].substring(0, list[i].length()-4);
preflist[i]=preffile;
}
Now use preflist to get values from all SharedPreferences:
for(int index=0;index<preflist.length(),index++){
SharedPreferences spPref = getSharedPreferences(preflist[index], MODE_PRIVATE);
Map<String,?> allsharedpref = spPref.getAll();
if(allsharedpref!=null){
for(Map.Entry<String, ?> entry : allsharedpref.entrySet()){
Toast.makeText(this, entry.getKey()+"\n", Toast.LENGTH_LONG).show();
}
}
getSharedPreferences() can only be called after onCreate() has been called on an Activity.

SharedPreferences string Array not working

I got two Activitys where I want to save and to load a two String[] Array (Sizes are same).
Code in Activity 1 looks like this (load)
SharedPreferences data = getSharedPreferences("data",Context.MODE_PRIVATE);
SharedPreferences.Editor editor = data.edit();
for (int i = 0;i<array_question.length;++i)
{
array_question[i] = data.getString("FAE"+i, array_question[i]);
array_answer[i] = data.getString("ATW"+i, array_answer[i]);
}
Activity two (save)
SharedPreferences data = getSharedPreferences("data",Context.MODE_PRIVATE);
SharedPreferences.Editor editor = data.edit();
for (int i = 0;i<Main.array_question.length;++i)
{
editor.putString("FAE"+i,Main.array_question[i]);
editor.putString("ATW"+i,Main.array_answer[i]);
}
editor.commit();
I got no error or crash but also no result.When I want to load them there is nothing... What is my fault ?

SharedPreferences keep getting default value

I keep Getting the Default value either my UI will display null or if I use integers it displays that default value as well here it is in the string form plz help
//putting the information in shared preferences
TextView pScore1=(TextView)findViewById(R.id.pScore1f);
SharedPreferences peepsScores2= PreferenceManager.getDefaultSharedPreferences(GamePlayFirst.this);
SharedPreferences.Editor editor2 =peepsScores2.edit();
String userScore11 = pScore1.getText().toString();
editor2.putString("userScore11",userScore11);
editor2.commit();
//getting it and editing it
SharedPreferences peepsScores2 = PreferenceManager.getDefaultSharedPreferences(this);
int u;
int one =1;
int newUsrScore1=1;
String userScore11 = peepsScores2.getString("userScore11",null);
u=Integer.parseInt(userScore11);
newUsrScore1 = u+one;
String newUserScore1 = Integer.toString(newUsrScore1);
SharedPreferences.Editor editor = peepsScores2.edit();
editor.putString(newUserScore1, NewUserScore1);
editor.commit();
//getting it and displaying it on the UI
SharedPreferences peepsScores2 = PreferenceManager.getDefaultSharedPreferences(this);
String userScore11 = peepsScores2.getString("NewuserScore1",null);
pScore1.setText(" "+userScore11);
I have added some comment to you code please check:
//putting the information in shared preferences
TextView pScore1=(TextView)findViewById(R.id.pScore1f);
SharedPreferences peepsScores2=
PreferenceManager.getDefaultSharedPreferences(GamePlayFirst.this);
SharedPreferences.Editor editor2 =peepsScores2.edit();
String userScore11 = pScore1.getText().toString();
editor2.putString("userScore11",userScore11);
editor2.commit();
//getting it and editing it
SharedPreferences peepsScores2 = PreferenceManager.getDefaultSharedPreferences(this);
int u;
int one =1;
int newUsrScore1=1;
String userScore11 = peepsScores2.getString("userScore11",null);
u=Integer.parseInt(userScore11);
newUsrScore1 = u+one;
String newUserScore1 = Integer.toString(newUsrScore1);
SharedPreferences.Editor editor = peepsScores2.edit();
//#Praful: here newUserScore1 seems to be integer value and you are storing
//null here. I think it it should be
//`editor.putString("NewuserScore1", newUsrScore1);`
editor.putString(newUserScore1, null);
//#Praful: call commit here
editor.commit;
//getting it and displaying it on the UI
SharedPreferences peepsScores2 = PreferenceManager.getDefaultSharedPreferences(this);
String userScore11 = peepsScores2.getString("NewuserScore1",null);
pScore1.setText(" "+userScore11);
This line
editor.putString(newUserScore1, null);
should be
editor.putString("NewuserScore1",newUserScore1);
and also don't forget to commit your changes using editor.commit();
Whenever you working with SharedPreference never forget to call commit() to save your changes.
SharedPreferences.Editor editor = peepsScores2.edit();
editor.putString("NewuserScore1", newUserScore1);
editor.commit();

Categories

Resources