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.
Related
I'm new with HashMap, how can I save permanently and add other items when I reopen the application?
For example:
private HashMap<String, Recognition> registered = new HashMap<>();
public void register(String name, Recognition rec) {
registered.put(name, rec);
}
I can see all items inside registered using:
for (Map.Entry<String, Recognition> entry : registered.entrySet()) {
final String name = entry.getKey();
... }
But when I close and reopen app, I can't see all objects saved inside registered.
I see lot of people using SharedPreferences, but I don't know how to add items inside the pre-saved hashmap.
You can do it indirectly this way:
//writing into file
SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString( key, hashmap.getValue() );
editor.commit();
//reading from file
SharedPreferences pref = getPreferences(Context.MODE_PRIVATE);
for( i = 0;i < size;i++) )
pref.getString( i , defaultValue );
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 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
}
I have a hash map table as below,
HashMap<String, String> backUpCurency_values = new HashMap<String, String>();
and i want to store these value for future use.. how can i do that?
Edit:
i will store to Country names and currencyvalue as key and value pair...
You should just use a for-each loop and iterate through the map like this:
SharedPreferences.Editor editor = getSharedPreferences(PREFS_NAME, 0).edit();
for( Entry<String, String> entry : backUpCurency_values.entrySet() )
editor.putString( entry.getKey(), entry.getValue() );
editor.commit();
Then when you need to get your values back for later use you do the following (provided that this SharedPreference-object is reserved for currency):
SharedPreferences prefs = getSharedPreferences(PREFS_NAME, 0);
for( Entry<String, ?> entry : prefs.getAll().entrySet() )
backUpCurency_values.put( entry.getKey(), entry.getValue().toString() );
You can use SharedPreferences.
settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
//The below step you can repeat to put all the key value pair from the hashmap to the shared preference
editor.putString("Key", Value);
// Commit the edits!
editor.commit();
And to retrieve later use
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
boolean silent = settings.getString(<Key>, <defaultvalue>);
There are a few different ways to approach this. With nothing more to go on than the info that you want to store a HashMap to SharedPreferences, I can only make assumptions.
First thing I'd ask is whether you will be storing other things in the SharedPreferences as well- I'll assume you will.
Here is how I would approach it:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("backUpCurency", stringify(backUpCurency_values));
editor.commit();
You may want to see what stringify does:
// turns a HashMap<String, String> into "key=value|key=value|key=value"
private String stringify(HashMap<String, String> map) {
StringBuilder sb = new StringBuilder();
for (String key : map.keySet()) {
sb.append(key).append("=").append(map.get(key)).append("|");
}
return sb.substring(0, sb.length() - 1); // this may be -2, but write a unit test
}
Then you can just parse that string with known structure upon reading the shared preferences later.
private HashMap<String, String> restoreIt() {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
String backup = settings.getString("backUpCurency", "");
HashMap<String, String> map = new HashMap<String, String>();
for (String pairs : backup.split("|")) {
String[] indiv = pairs.split("=");
map.put(indiv[0], indiv[1]);
}
return map;
}
You can use SharedPreference like this:
SharedPreferences s_pref=PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
Editor edit=s_pref.edit();
edit.putString("key","value");
edit.commit();
later you can use it like:
String s=s_pref.getString("key","default value");
But,you must have list of keys you have saved values with,into SharedPreferences so that you can get values easily at the time of retrieving them.
To store the values use this code
SharedPreferences preferences = getSharedPreferences(
PREF_FILE_NAME, MODE_PRIVATE);
if (value.equals("")) {
boolean storedPreference = preferences.contains(key);
if (storedPreference) {
SharedPreferences.Editor editor = preferences.edit();
editor.remove(key); // value to store
Log.d("KEY",key);
editor.commit();
}
}else{
SharedPreferences.Editor editor = preferences.edit();
editor.putString(key, value); // value to store
Log.d("KEY",key);
editor.commit();
}
To retrieve the values use this code
SharedPreferences preferences = getSharedPreferences(
PREF_FILE_NAME, MODE_PRIVATE);
Map<String, String> map = (Map<String, String>) preferences.getAll();
if(!map.isEmpty()){
Iterator<Entry<String, String>> iterator = map.entrySet().iterator();
while(iterator.hasNext()){
Map.Entry pairs = (Map.Entry)iterator.next();
pairs.getKey()+pairs.getValue();
//write code here
}
}
I have created a shared preference for a boolean value and for a string value. The boolean value is gotten in another activity. But for the string I am only getting default value.
Home.class
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor spe = prefs.edit();
spe.putBoolean("flag", true);
spe.putString("user", "hello");
spe.commit();
welcome.class
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
boolean flag= prefs.getBoolean("flag", false);
String user=prefs.getString("user","Nothing");
TextView tv = new TextView(this);
tv.setText("Flag : "+flag+(" User : "+user);
For 'user', only 'Nothing' is displaying. Where should I correct my code?
Try using:
SharedPreferences settings = getSharedPreferences(appName,0);
settings.getBoolean("flag", true);
settings.getString("user", "hello");
And to put:
SharedPreferences settings = getSharedPreferences(appName,0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("flag",true);
editor.putString("user","hello");
editor.commit();
This is what I use in my application, and it shares booleans/ints/strings accrossed many many Classes
Note: appName doesn't have to be the app name, like in the official tutorial.