简体   繁体   中英

SharedPreferences for save the value of TextView?

i've a ViewPager with three fragments. In the first fragment i have a Button, If you press shows two TextView with a different text. If I go to the third fragment and then I go back to the first, do not I see more TextView. I understand that you have to use SharedPreferences to not lose the value, then I made this code, but it does not work.

    TextView1=(TextView)view.findViewById(R.id.textView1); 
    TextView2=(TextView)view.findViewById(R.id.textView2; 



    Button b1 = (Button) view.findViewById(R.id.button1);
    b1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

             // CODE HERE

            SharedPreferences prefs = this.getSharedPreferences(
                      "com.MyPackage.AppName", Context.MODE_PRIVATE);                 
              SharedPreferences.Editor editor = prefs.edit();
              editor.putString("TextView1",TextView1.getText().toString());
              editor.putString("TextView2",TextView2.getText().toString());
              editor.commit();

} );

Why does not it work? If when I close the application I want to delete the values ​​stored in SharedPreferences how can I do?

The code fragment you currently give is correct. I think that probably you miss some code to actually restore the stored values (get from the preferences by key and use setText ), or do not call it at the right time.

Try to put such code into the overridden onResume method of your activity.

It is unusual to store the state in response to pressing the button. Read more here about activity life cycle and which methods are automatically called for you at the certain times.

To write to a SharedPref you can use this code:

String text = "Your text here";    
Context context = getApplicationContext();
AppPrefs appPrefs = new AppPrefs(context);
appPrefs.setSessionId(text);

To read from a SharedPref you can use this:

String textViewTextHolder = appPrefs.getSessionId();

You should consider using static variables for what you want to do:

Example of static variables:

public static int i = 1;

To access this in another activity:

if(MainActivity.i == 1){
}

if you want to stick with shared preferences for any reason, you could clear them on the app launch , although I would advise not using shared preferences for what you are doing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM