SharedPreferences not saving all the data after restart - android

I am new to Android App Development and I am supposed to make a TodoList App for a course. But the SharedPreference in my code is not working. I dont know if I'm supposed to use it in a specific way in a specific method like onCreate or onStop.
It is saving the first input the user is entering permanently, but in the same position:
(The "task0" is what I used to track the different variable names I used as argument for "putString" in addStuff method, to avoid replacing values)
It is saving the inputs after that in the same session, but if the user ends that session, all those values after "t" are gone. If the user restarts the app and inputs something else (like "g"), it is saving "g" in that same 3rd position.
I have basic Java knowledge and I tried to understand what is going on using it, but failed. Please let me know where is the mistake and how to use SharedPreferences properly.
public class TodoActivity extends AppCompatActivity {
public ArrayList<String> items;
public ArrayAdapter<String> itemsAdapter;
public ListView list;
public String s;
public EditText taskBox;
public static final String filename = "itemsList";
public TextView text;
public static int counter = 0;//counter starting at 0 no matter what, everytime the app starts
public String newtask= "task";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_todo);
list = (ListView) findViewById(R.id.list1);text = (TextView) findViewById(R.id.text1);
taskBox = (EditText) findViewById(R.id.box);
s = taskBox.getText().toString();
items = new ArrayList<String>();
itemsAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, items);
list.setAdapter(itemsAdapter);
//add items to list
items.add("First Item");
items.add("Second Item");
//restore
SharedPreferences sp = this.getSharedPreferences("itemsList", 0);
//checking if it stores the previous values, this gives the last input but not the previous ones after restarting the app
String dummyname = "task";
text.setText(String.valueOf(counter));//since counter is again at
for(int c=0; c<=50; c++){
String num = String.valueOf(c);
dummyname = dummyname + num;
String x = sp.getString(dummyname, "not found");
if (x.equalsIgnoreCase("not found")){
counter=c-1;
break;
} else {
items.add(x);
text.setText(dummyname);
}
}
}
public void addItem(View v){
s = taskBox.getText().toString();
itemsAdapter.add(s);//adding the new task as string
String temp = String.valueOf(counter);
newtask = "task" + temp;
//trying to store the new tasks with different variable names to avoid being replaced
text.setText(newtask);
SharedPreferences sp = this.getSharedPreferences("itemsList", 0);
SharedPreferences.Editor e = sp.edit();
e.putString(newtask,s);
e.apply();
counter++;
}
}

If you have relatively small collection of key-values that you would like to save,
You should use Shared preference API
Read from the shared preference:
Pass the key and value you want to write,create a SharedPreferences.Editor by calling edit() on your SharedPreferences.
Pass key and values you want to save by using this method putInt() ,putString() ,Then call commit() to save the changes. For example:
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt("KeyName", newHighScore);
editor.commit();
Write from the shared preference:
To retrieve values from a shared preferences file, call methods such as getInt() and getString(),
providing the key for the value you want, and optionally a default value to return if the key isn't present. For example:
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
int defaultValue = getResources().getInteger(R.string.saved_high_score_default);
long highScore = sharedPref.getInt("KeyName", defaultValue);

Two things :
1) To initialize SharedPreferences use :
sharedPreferences = getSharedPreferences("itemsList", Context.MODE_PRIVATE);
2) Where are you calling addItem() method??

The problem is about the Tag you use to save items. See this Line :
dummyname = dummyname + num;
You add item by this format :
task0
task1
task2
but you are getting values in this format
task0
task01
task012
Just change these two line of code :
//dummyname = dummyname + num;
//String x = sp.getString(dummyname, "not found");
String newDummy= dummyname + num;
String x = sp.getString(newDummy, "not found");

Related

Sharedpreferences not saving data when app restart

I'm trying to make "add favorites" button in my app. I can send and get value with sharedpreferences properly, but when I restart the app, favorites are empty again. I guess I need override OnPause method, but I couldn't apply properly. I need help, thanks in advance.
PLAYING RADIO FRAGMENT
public static int incrementedValue = 0;
add_favorites_button= (Button) view.findViewById(R.id.add_favorites_button);
add_favorites_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
SharedPreferences settings = getActivity().getSharedPreferences("PREFS", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("radio_link"+ incrementedValue, radio_play_link);
editor.putString("radio_name" + incrementedValue, radio_name);
editor.putString("listener_number" + incrementedValue, listener_number);
//editor.clear();
editor.commit();
incrementedValue++;
}
});
FAVORITES FRAGMENT
final List<String> radio_name_list = new ArrayList<>();
final List<String> radio_link_list = new ArrayList<>();
final List<String> listener_numbers = new ArrayList<>();
for (int i=0; i<PlayRadioFragment.incrementedValue; i++) {
SharedPreferences settings = getActivity().getSharedPreferences("PREFS",0);
radio_name_list.add(settings.getString("radio_name" +i, ""));
radio_link_list.add(settings.getString("radio_link" +i, ""));
listener_numbers.add(settings.getString("listener_number" +i, ""));
}
...
then I show them in listview
...
for (int i=0; i<PlayRadioFragment.incrementedValue; i++)
After restarting the app (or Fragment), this incrementedValue will be back to what it was initialized with, probably 0, so you won't load anything from SharedPreferences (not entering the for-loop at all).
Try something like
for (int i=0; i<Integer.MAX_VALUE; i++) {
String s = settings.getString("radio_name" +i, "")
if (TextUtils.isEmpty(s))
break;
} else {
radio_name_list.add(s);
}
You probably also want to avoid overwriting the old favorites after the app restart, so you have to set the incrementedValue after loading the favorites like
incrementedValue = radio_name_list.size();
This is happening because on restarting app the variable named incrementedValue gets value once again as 0 and in for loop conditional statement is not full filling and that's why loop is not executing as expected. To resolve this issue you can do one more thing you need to save the value of incrementedValue in shared preference as well and in for loop testing statement get the updated value from shared preference. Hope that helps you

Shared Prefereces saved names not showing after restarting the App

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

Save just an integer into .txt Android

In my application i have to save just an int variable like "score" or "level" so that the progress of the users doesn't go lost.
I tried to parse from a String but it doesn't work for me.
I also tried:
private int readFromFile() {
Scanner getScore= new Scanner(STORETEXT);
punteggio=getScore.nextInt();
return score;
}
where SCORETEXT has been defined:
private final static String STORETEXT = "score.txt";
If i put into the OnCreate:
int points= readfromFIle();
The app crashes.
1) Can you tell me what's the source code to read a Int?
2)I would like to know how to write it to .txt too, just to be sure the code i am using for writing is correct.
You are right in use SharedPreferences. Your app crashes because of empty string resource.
<string name="scoreNow">HERE MUST BE YOUR STRING VALUE</string>
Name attribute in tag is only an identifier, not a value.
But in fact, you shouldn't use strings in resources as key for some value. String resources are needed for localization. Keys for SharedPreferences and same classes better to be constant fields in class. For example, for your code:
public class Storage {
//...
private static final String SCORE_KEY = "score";
public void saveScore(int score) {
SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt(SCORE_KEY, scoreValue);
editor.apply(); //apply is better than commit in fact
}
public int readScore() {
SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
int scoreValue = sharedPref.getInt(SCORE_KEY, 0);
return scoreValue;
}
}

displays shared preferences in textview

I insert the values ​​in sharedpreferences, now I do not know how to display these values ​​in a TextView.
SharedPreferences prefs = getSharedPreferences(SharedPrefName, 0);
SharedPreferences.Editor prefsEditor = prefs.edit();
float importo = prefs.getFloat( "Importo", 0 );
float valore = Float.parseFloat( mImporto.getText().toString() );
prefsEditor.putFloat( "Importo", importo + valore );
prefsEditor.commit();
First thing lets try to save something in SharedPreferences, I'm using a method because is easy to understand this way, and it looks cool :P
TO ADD in class:
private SharedPreferences settings;
private static final String PREFS_NAME = "app_name";
private TextView usernameTextView;
private TextView passwordTextView;
init textviews...
usernameTextView = (TextView)...
passwordTextView= (TextView)...
in constructor add this:
settings = context.getSharedPreferences(
PREFS_NAME, 0);
--Save username and password
public static final String USERNAME = "username";
public static final String PASSWORD= "password";
private void savePreferences(String sharedUsername, String sharedPassword) {
SharedPreferences.Editor SharedEditor = settings.edit();
SharedEditor.putString(USERNAME,
sharedUsername);
SharedEditor.putString(PASSWORD,
sharedPassword);
SharedEditor.commit();
}
--Load and display username and password in a textview
private void loadSharedPreferences() {
if (settings != null) {
String loadUsername= settings.getString(
USERNAME , null);
if (loadUsername != null && !loadUsername.isEmpty()) {
usernameTextView.setText(loadUsername);
}
String loadPassword= settings.getString(
PASSWORD, null);
if (loadPassword!= null && !loadPassword.isEmpty()) {
passwordTextView.setText(loadPassword);
}
}
}
Hope you use it. Cheers
just find your textview in your layout:
TextView tv = (TextView)view.findViewById(R.id.yourtextview);
tv.setText("your value");
It depends where you want to set the value. If you just want to set the value after saving it in SharedPreference, then you can simple do:
TextView YourTextView = (TextView) findViewById(R.id.tv);
YourTextView.setText(String.valueOf(importo + valore) );
If you want to set it in some other class, then you can get the value from SharedPreferencce and set in in TextView. See How to use SharedPreferences in Android to store, fetch and edit values for how to get the values. Then after you extract the value, you can set it as I showed in the example above.
Assuming you mean you need to retrieve these values in a different Activity, you retrieve the values with something like
SharedPreferences values = getSharedPreferences(SharedPrefName, 0);
float valore = values .getFloat("Importo", 0);
Then get the String value and set your TextView or just do
textView.setText("" + valore);
The docs have a good example
SharedPreferences full docs
First getValue from Sharedprefrences :
float value = prefs.getFloat( "Importo", 0 );
set float value in your textview:
textview.setText(String.valueOf( value ));

Saving an arbritrary length array in SharedPreferences - Android

My objective is to save a field entered in an EditText when the user clicks on a button; in this case it's an IP address. The idea would be to show a list of all valid entered IPs when the user focuses on the EditText, similar to saved searches.
I found this useful piece of code. I need a bit of help explaining it. The code runs putString of all the elements in the String[] array which I think is a collection of all the submitted fields in EditText. How do I create this array if only one field is getting added at a time? I need an explanation of what is happening below.
public boolean saveArray(String[] array, String arrayName, Context mContext) {
SharedPreferences prefs = mContext.getSharedPreferences("preferencename", 0);
SharedPreferences.Editor editor = prefs.edit();
editor.putInt(arrayName +"_size", array.length);
for(int i = 0;i < array.length; i++){
editor.putString(arrayName + "_" + i, array[i]);
}
return editor.commit();
}
public String[] loadArray(String arrayName, Context mContext) {
SharedPreferences prefs = mContext.getSharedPreferences("preferencename", 0);
int size = prefs.getInt(arrayName + "_size", 0);
array = new String[size];
for(int i=0;i<size;i++)
array[i] = prefs.getString(arrayName + "_" + i, null);
return array;
}
As per your requirement and the code you referenced, I get the following idea:
Untested for erratas:
public boolean saveoneData(String oneTimeData, String key, Context mContext) {
SharedPreferences prefs = mContext.getSharedPreferences("preferencename", 0);
int size = prefs.getInt(key+"_size", 0); // For the first time it gives the default value(0)
SharedPreferences.Editor editor = prefs.edit();
editor.putString(key+ "_" + size, oneTimeData);
editor.putInt(key+"_size", ++size); // Here everytime you add the data, the size increments.
return editor.commit();
}
public String[] loadArray(String key, Context mContext) {
SharedPreferences prefs = mContext.getSharedPreferences("preferencename", 0);
int size = prefs.getInt(key+ "_size", 0);
array = new String[size];
for(int i=0;i<size;i++)
array[i] = prefs.getString(key+ "_" + i, null);
return array;
}
But I usually don't use the sharedpreferences for large storage of data because it could make data creation, retrieval and data modifications difficult as the data increases. Hope this is what you want.
Once you collect all EditText values in one String[] array or List<String> or Set<String>;
You don't need to save each array value as separate key-value pair in the SharedPreferences. There is much simpler way to save, which is create Set<String> and save them all values under one key:
editor.putStringSet(arrayName, new HashSet<String>(Arrays.asList(array));
For retrieving you can retrieve them as Set<String> in same manner:
Set<String> ipsSet = sharedPrefs.getStringSet(arrayName, null);
What is happening in the code you posted:
Each value of String array is saved individually under unique key and the size of the array, likewise.
Similarly later each item is retrieved moving in the range 0 to the saved size of the array, which is retrieved at first place from the SharedPreferences

Categories

Resources