Question

I have a TextView. When the Activity is first created the Value of the textView is "", as in nothing. But the user can initiate some actions that can make the text="st". That works fine, once more that works fine. The problem is when I leave the page and come back instead of text="st" , it's " " as in nothing. So the user has to waste time and get the textView back to "st" through some actions.

I tried to save the TextView using SavePreferences but since the value of TextView is nothing when the activity starts SavePreferences does exactly what it's supposed to do and makes the TextView equal nothing. Isn't there some way for me to save the value of the TextView. I have other Views on my page I do not want to save, so how do I save just the TextView as it is when the user leaves the app or activity?

TextView s1;
s1 = (TextView)findViewById(R.id.s1);

//9 miles down the page
LoadPreferences();
SavePreferences("MEM46", s1.getText().toString());

LoadPreferences();} 
private void SavePreferences(String key, String value){
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.commit();}

private void LoadPreferences(){
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
String strSavedMem46 = sharedPreferences.getString("MEM46", "");
s1.setText(strSavedMem46);

lay1.setOnLongClickListener(new OnLongClickListener(){
public boolean onLongClick(View v){

AlertDialog.Builder alert = new AlertDialog.Builder(xxx.this);
alert.setTitle("Help"); //Set Alert dialog title here
alert.setSingleChoiceItems(items, 0, new DialogInterface.OnClickListener(){
public void onClick(DialogInterface d, int choice){ 

if(choice == 0) {
d.cancel();
}
else if(choice == 1){
TextView ss1=(TextView)findViewById(R.id.s1);
 ss1.setText("st");d.cancel();                                                                                                           } 
 else if(choice == 2)                                                                   {
 TextView ss1=(TextView)findViewById(R.id.s1);
 ss1.setText("");d.cancel();}});
 alert.show();
 return true;                                                                             

 }});
Was it helpful?

Solution

At which point exactly do you call LoadPreferences/SavePreferences?

Saving should happen only when the user leaves the activity, so onPause() must be overriden to call the savePreference(). Loading should be done in onStart().

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top