SharedPreferences Android - java

I have this method :
private void deleteExam(String i) {
SharedPreferences prefsContatore = getSharedPreferences("esameKey"+i, Context.MODE_PRIVATE);
SharedPreferences.Editor editorContatore = prefsContatore.edit();
editorContatore.putString("esameKey"+i, "0");
editorContatore.commit();
}
Go? Can I call recursively "esameKey"+i?

getSharedPreferences access to a file and create if it does not exist. Every time you pass a different i a new file is created. Create it once:
SharedPreferences prefsContatore = getSharedPreferences("mySharedPrefFileName", Context.MODE_PRIVATE);
SharedPreferences.Editor editorContatore = prefsContatore.edit();
first argument of putString is a key the second paramter is the value you want to store
editorContatore.putString("esameKey"+i, "0");
this way you are putting for every i the value of 0. Is really that what you want?

Related

Set<String> losing data when restored from SharedPreferences after app is restarted

Im using SharedPreference on android to store a Set of Strings. It is stored and retrived fine to my knowledge but when the app is restarted some data is lost. Strings are add one by one and before adding them I retrieve the set, add a String and then store it again.
This is how I store it:
Set<String> emptySet = null;
SharedPreferences prefs = getContext().getSharedPreferences(getContext().getString(R.string.pref_disagree_key), Activity.MODE_PRIVATE);
String newIdAgreed = getItem(position).getId();
if (prefs.contains(getContext().getString(R.string.pref_disagree_key))) {
Set<String> updateSet = prefs.getStringSet(getContext().getString(R.string.pref_disagree_key), emptySet);
updateSet.add(newIdAgreed);
SharedPreferences.Editor editor = prefs.edit();
editor.putStringSet(getContext().getString(R.string.pref_disagree_key), updateSet);
editor.commit();
} else {
Set<String> newSet = new HashSet<String>();
newSet.add(newIdAgreed);
SharedPreferences.Editor editor = prefs.edit();
editor.putStringSet(getContext().getString(R.string.pref_disagree_key), newSet);
editor.commit();
}
And this is how I get it back:
if (prefsDisagree.contains(getContext().getString(R.string.pref_disagree_key))){
disagree_set = new HashSet<String>(prefsDisagree.getStringSet(getContext().getString(R.string.pref_disagree_key), emptySet));
for (String item: disagree_set){
//stuff done here
}
}
I saw some similar questions about this topic but none of the answers solved my problem. Any ideas?
The StringSet is not persistent when you are trying to edit it all again after it was saved and therefore newer data that was just added wont get saved when you quit the app and open it again.
It is actually documented: getStringSet
You need to copy first the StringSet and then insert/add data to the copied StringSet:
Set<String> s = new HashSet<String(prefs.getStringSet(
getContext().getString(R.string.pref_disagree_key),
emptySet));

How SharedPreference.Editor actually work in Android?

I am trying to save some String data using SharedPreference.
Here is my code
// SAVE
SharedPreference mySharedPref = new SharedPreference("Data", 0);
mySharedPref.edit().putString("hello", "world");
mySharedPref.edit().putString("my", "code");
mySharedPref.edit().commit();
// LOAD
String str = mySharedPref.getString("hello", ""); // I expect "world"
But it only has an empty string!
Meanwhile,
SharedPreference.Editor editor = mySharedPref.edit();
editor.putString(...);
editor.commit();
This worked....
I thought mySharedPref.edit() returns a reference and makes the code above and below the same.
I am confused now. X(
See this solution
Setting values in Preference:
SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
editor.putString("name", "Elena");
editor.putInt("idName", 12);
editor.commit();
Retrieve data from preference:
SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
String restoredText = prefs.getString("text", null);
if (restoredText != null) {
String name = prefs.getString("name", "No name defined");//"No name defined" is the default value.
int idName = prefs.getInt("idName", 0); //0 is the default value.
}
in your code:
// SAVE
SharedPreference mySharedPref = new SharedPreference("Data", 0);
mySharedPref.edit().putString("hello", "world");
mySharedPref.edit().putString("my", "code");
mySharedPref.edit().commit();
You called edit() each time you put a String but you didn't call commit() after it so your changes is not saved. You should change to this:
// SAVE
SharedPreference mySharedPref = new SharedPreference("Data", 0);
mySharedPref.edit().putString("hello", "world")
.putString("my", "code");
.commit();
edit() method in SharedPreference returns NEW INSTANCE of the Editor interface. I found the comment explaining it in SharedPreferences.java file came with sdk.
Any actions performed on the new instance will be independent from other instances.
In the first part of my code, by calling edit() multiple times, I was performing actions on each independent instance.
It was interesting to notice that edit() returns a new instance instead of a reference.
/**
* Create a new Editor for these preferences, through which you can make
* modifications to the data in the preferences and atomically commit those
* changes back to the SharedPreferences object.
*
* Note that you must call {#link Editor#commit} to have any
* changes you perform in the Editor actually show up in the
* SharedPreferences.
*
* #return Returns a new instance of the {#link Editor} interface, allowing
* you to modify the values in this SharedPreferences object.
*/
Editor edit();

Android Studio: Java- making a global variable

How do you make a variable that can be used across the application. For example, in Swift, you can name it by:
var formattedPrice: String = rowData["date"] as String
defaults.setObject(rowData, forKey: "rowData")
and you can fetch it with:
var variable = defaults.dictionaryForKey("rowData") as? NSDictionary
How can this behavior be mimicked in android studio?
The example you provided looks very similar to SharedPreferences in Android. SharedPreferences allow you to store data and access said data globally within your application. Here is a simple code snippet that shows you how to save and recall an int. You can save the variable as follows:
SharedPreferences sharedPreferences = getSharedPreferences("your_preferences", Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt("your_integer_key", yourIntegerValue);
editor.commit();
And then retrieve it anywhere in your application like so:
SharedPreferences sharedPreferences = getSharedPreferences("your_preferences", Activity.MODE_PRIVATE);
int myIntegerValue = sharedPreferences.getInt("your_integer_key", -1);

Passing data through two activities?

For an app I am developing, I am having the user input some information on one activity, and then on the next, the user will read something, in such that he/she won't be putting any information on it, but on the third activity, I want to display what the user put in the first. Is there a way I can carry that information from the 1st to the 3rd activity without going through the second?
Use sharedPreferences to store that piece of data on the phone. On the 3rd activity, read it and use it.
See it here-
http://developer.android.com/guide/topics/data/data-storage.html#pref
This can be done in many ways !
Why not use Intents to pass the data ?
STEP-1: <Eg:: From Activity1>
Pass the telefone into a new activity with the help of intents
Intent i = new Intent(getApplicationContext(), Activity2.class);
i.putExtra("title",telefone);
i.putExtra("descrip",telefone);
startActivity(i);
STEP-2: <Eg:: From Activity2>
Receive the string passed in another activity
Bundle extras = getIntent().getExtras();
if (extras != null) {
String title= extras.getString("title");
String descrip= extras.getString("descrip");
}
STEP-3: <Eg:: From Activity2> pass data again to Activity3
Receive the string passed in another activity
Bundle extras = getIntent().getExtras();
if (extras != null) {
String title= extras.getString("title");
String descrip= extras.getString("descrip");
}
Pass the data to Activity3
Intent i = new Intent(getApplicationContext(), Activity3.class);
i.putExtra("title",telefone);
i.putExtra("descrip",telefone);
startActivity(i);
Hope it helps ! ..........Let me know if you need more info
Use SharedPreference. Save in A1 and retrieve in A3.
Initialization
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0); // 0 - for private mode
Editor editor = pref.edit();
Storing Data
editor.putBoolean("key_name", true); // Storing boolean - true/false
editor.putString("key_name", "string value"); // Storing string
editor.putInt("key_name", "int value"); // Storing integer
editor.putFloat("key_name", "float value"); // Storing float
editor.putLong("key_name", "long value"); // Storing long
editor.commit(); // commit changes
Retrieving Data
// returns stored preference value
// If value is not present return second param value - In this case null
pref.getString("key_name", null); // getting String
pref.getInt("key_name", null); // getting Integer
pref.getFloat("key_name", null); // getting Float
pref.getLong("key_name", null); // getting Long
pref.getBoolean("key_name", null); // getting boolean
Deleting Data
editor.remove("name"); // will delete key name
editor.remove("email"); // will delete key email
editor.commit(); // commit changes
Clearing Storage
editor.clear();
editor.commit(); // commit changes

sharedpref add strings into table

i trying to insert my string into my database tables ,but it doesnt appear, so any advice on this how do i string my text so it able to appear on android database table
btnplayer = (Button) findViewById(R.id.button1);
tw1 = (TextView)findViewById(R.id.PX2);
btnplayer.setOnClickListener(new View.OnClickListener() {
SharedPreferences myPrefs = getSharedPreferences("PREF_COUNT", 0);
SharedPreferences.Editor myEditor = myPrefs.edit();
public void onClick(View v) {
String Player = myPrefs.getString("tw1",name);
DataStorage.this.btnplayer.setText("add name [" + Player + "]");
myEditor.putString("Player", Player);
myEditor.commit();
Please make your question more clear.
If you want store your data in database in android, you can go for SQLite database available in android http://developer.android.com/training/basics/data-storage/databases.html
but I suggest use sharedpreferences if only strings need to store.
I didn't get the meaning behind this statement String Player = myPrefs.getString("tw1",name); if you already have stored the same value (first time there will be no value so you will getting back the default "name" and then you will again store that name with the new key called "Player"). Where are you storing "tw1"? Exactly what issue you are facing?

Categories