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 ?
Related
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.
I've a bunch of strings in an arraylist.
I want to save some of the strings in a shared preferences.
like if user selects a sting whose index is 3, I want to store that particular string in a shared preference.
Is it possible?
Please let me know.
I hope that this code will help you understand it
int id = selectedItemNum;
ArrayList<String> list = new ArrayList<String>();
list.add("Item1");
list.add("Item2");
list.add("Item3");
list.add("Item4");
String selectedString = list.get(id);
String APP_PREFERENCES = "savedStrings";
SharedPreferences mySharedPreferences = getSharedPreferences(APP_PREFERENCES, Context.MODE_PRIVATE);
Editor editor = mySharedPreferences.edit();
editor.putString("savedString"+id, selectedString);
editor.apply();
To save data to SharedPreferences:
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
for(int i=0; i<arraylist.size(); i++){
sharedPreferences.edit().putString("TAG" + Integer.toString(i)
,arraylist.get(i)).apply();
}
To get data from SharedPreferences:
sharedPreferences.getString("TAG" + "x", null); x is a number position in array list
I am creating an app that saves that saves user's previous names. I am using Shared Preferences so when the user kills the app and reopens it the names will still show in the saved Activity. The app currently displays the saved names, but once it's closed and the life cycle is killed, and then restarted the names aren't retrieved.
Code to save the names:
protected void addToSaved(String s){
GlobalList.pref = getApplicationContext().getSharedPreferences("MyPref", Context.MODE_PRIVATE); // 0 - for private mode
SharedPreferences.Editor editor = GlobalList.pref.edit();
if(GlobalList.tagsActive.size() < 6){
GlobalList.tagsActive.addFirst(GlobalList.tagsAvail.removeFirst());
editor.putString(GlobalList.tagsActive.getFirst(), s);
}else{
editor.remove(GlobalList.tagsActive.removeLast());
GlobalList.tagsAvail.add(GlobalList.tagsActive.removeLast());
//adding shared pref
GlobalList.tagsActive.addFirst(GlobalList.tagsAvail.removeFirst());
editor.putString(GlobalList.tagsActive.getFirst(), s); // Storing string value
}
//GlobalList.editor.commit(); // commit changes into sharedpreferences file.
editor.commit();
Code to retrieve and display the names:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_saved_names);
for (int i = 0; i < GlobalList.tagsActive.size(); i++) {
//setting martian name to screen
// getting String
nameTexts[i] = (TextView) findViewById(textId[i]);
//set conditon here so no null pointer
GlobalList.pref = getApplicationContext().getSharedPreferences("MyPref", Context.MODE_PRIVATE); // 0 - for private mode
String s =GlobalList.pref.getString(GlobalList.tagsActive.get(i), "");
nameTexts[i].setText(s);
}
}
}
Code for global list so can be edited across classes:
public class GlobalList {
static LinkedList<String> tagsAvail = new LinkedList<String>();
static LinkedList<String> tagsActive = new LinkedList<String>();
static SharedPreferences pref;
static SharedPreferences.Editor editor;
}
That happens because when the app starts up on onCreate, the length of GlobalList.tagsActive.size() is zero, so the code inside the FOR loop does not execute.
Change your FOR loop for this:
while (true) {
//setting martian name to screen
// getting String
//set conditon here so no null pointer
GlobalList.pref = getApplicationContext().getSharedPreferences("MyPref", Context.MODE_PRIVATE); // 0 - for private mode
String s =GlobalList.pref.getString(GlobalList.tagsActive.get(i), "");
if (s.equals("")){
break; //exits while loop if no more items are found in SharedPref
else{
nameTexts[i] = (TextView) findViewById(textId[i]);
nameTexts[i].setText(s);
}
}
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.
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();