save and call Stringbuilder from Sharedpreference [duplicate] - android

This question already has answers here:
Shared preferences for creating one time activity
(14 answers)
Closed 6 years ago.
I 'm testing with some iteration with the coding below, with help of Stringbuilder and want to directly save the outcome to Sharedpreference.
save2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick (View v){
int i;
int n = 10;
StringBuilder outoutcome = new StringBuilder();
for (i = 0; i <= n; i++) {
outoutcome.append(i + "\n");
}
SharedPreferences sharedPreferences = getSharedPreferences("data1", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("outcome1", outoutcome.toString());
}
}
*I also tried editor.putString("outcome1", String.valueOf(outoutcome)); but unfortunately cannot.
for the retrieve of data in another activity, I had tried using coding below :
public static final String DEFAULT = "";
final SharedPreferences sharedPreferences = getSharedPreferences("data1", Context.MODE_PRIVATE);
final String out1 =sharedPreferences.getString("outcome1", DEFAULT);
resultout.setText("Saved data is " + out1 );
but the coding above not working. Then, I searched and found this , tried the code as below but still not working.
final String[] getout1= out1.split(",");
resultout.setText("Saved data is " + getout1 );
Can anyone help here? Thank you in advanced !

You have to use apply() or commit() to save the changes.
editor.apply();
or
editor.commit();

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

SharedPreferences not saving all the data after restart

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

Saving String data to SharedPreference then append to Uri

I want to make a Uri String like "http://almond.com/iOS/html/best.php?best_id=30241,15890"
The parameters of best_id (30241 and 15890) is retrieved like this from a custom url
String[] path = uri.getPath().split("/");
String sid = path[path.length - 1];
The problem is I want to keep appending a parameter with a comma after a click.
But I'm not sure how I can append a parameter to a url string and save it to the same sharedPreference.
sample
pref = getSharedPreferences("pref", MODE_APPEND);
SharedPreferences.Editor savestamp = pref.edit();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < sid.length; i++) {
sb.append(sid[i]).append(",");
}
savestamp.putString("params2", sb.toString());
I'm trying to do it but since I'm a total noob,just googling wont help. I would be grateful if the pros here can help me out.
Commit after putting the values.
pref = getSharedPreferences("pref", MODE_APPEND);
SharedPreferences.Editor savestamp = pref.edit();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < sid.length; i++) {
sb.append(sid[i]).append(",");
}
savestamp.putString("params2", sb.toString());
savestamp.commit();
please add savestamp.commit(); after savestamp.putString method then only it saved to SharedPreference

Passing strings to list and deleting them using shared preferences

i wish to, in one activity, put strings in the sharedpreferences, so then, in another activity, i get those strings, put them in a array and display them sequentially. I managed to do this, but i don`t have any idea how can i delete one specified string when asked. These strings will just be scattered on the shared preferences,and i dont know how to keep track of them. I can pass this unique int id to each element. I tried to use LinkedList, but i cannot pass this kind of structure as a shared preferences. I did not managed to make Gson work also. Please help.
Method that gets the string and put on shared preferences:
public void makefavorites(String[] a, String[] b, int id)
{
int idfinal = id%10;
idfinal = idfinal+1;
a[idfinal] = b[idfinal] +"\n" + "\n"+ a[idfinal];
SharedPreferences prefs = getSharedPreferences("Favorites", Activity.MODE_PRIVATE);
Editor edit = prefs.edit();
int temp = prefs.getInt("favorites_size", 0);
edit.putInt("favorites_size", temp+1);
edit.putString("array_" + prefs.getInt("favorites_size", 0), a[idfinal]);
edit.commit();
refreshfavorites();
}
Method that gets those strings, put on array and display it:
public void refreshfavorites()
{
SharedPreferences prefs = getSharedPreferences("Favorites", Activity.MODE_PRIVATE);
//GETS THE ARRAY SIZE
int size = prefs.getInt("favorites_size", 0);
String[] array = new String[size];
for(int i=0; i<size; i++){
array[i] = prefs.getString("array_" + i, null);
}
}
you have to use editor.remove method to delete specific value from arraylist..
public void removeArray(String[] list)()
{
SharedPreferences.Editor editor = mSharedPrefs.edit();
int size = list.length();
for (int i = 0; i < size; i++) {
editor.remove("favorites_size"+i);
}
editor.commit();
}
i hope its useful to you..

error in my SharedPreferences project

i am new android developer.& i am learning by developer.android.com
when i run a project about SharedPreferences.my app close with this error "the application has stopped unexpectedly.please try again"
in my project there is a edittext control.user write something on it & press save button & close the app.when user open it again there is that text in edittext.
this is my code:
SharedPreferences infor = getSharedPreferences( "information", 0 );
txtNumber.setText( infor.getInt( "number", 032 ) );
btnSave.setOnClickListener( new OnClickListener() {
#Override
public void onClick(View arg0) {
SharedPreferences infor = getSharedPreferences( "information", 0 );
SharedPreferences.Editor editor = infor.edit();
editor.putInt( "number", Integer.parseInt( txtNumber.getText().toString() ) );
editor.commit();
}
} );
Change here from
txtNumber.setText(infor.getInt("number", 032));
to
txtNumber.setText(infor.getInt("number", 032)+"");
OR
int my = infor.getInt("number", 032);
txtNumber.setText(my+"");
This gives you as a String. And if you want convert int to String using String class then you can use this way.
int my = infor.getInt("number", 032);
String myNumber = String.valueOf(my);
txtNumber.setText(myNumber);
If you want the value of the int as your text, make it a String first.
txtNumber.setText(String.valueOf(infor.getInt("number", 032)));

Categories

Resources