Search code examples
androidsharedpreferences

How to save TextView Values in SharedPreferences


How to save TextView values in SharedPreferences, see my code below and let me know how to store to SharedPreferences and retrieve in onCreate(..)

my code looks like this:

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        txtOperative = (TextView) findViewById(R.id.currentOperative);
        txtEvent = (TextView) findViewById(R.id.currentEvent);

        intent = getIntent();
        strEventName = intent.getStringExtra("eventName");
        strOperativeName = intent.getStringExtra("operativeName");

        txtEvent.setText(strEventName);
        txtOperative.setText(strOperativeName);         
    }

I want to show these values always in TextViews, whenever user comes back to this activity


Solution

  • Simple use this for save your TextView value in sharedpreference

     SharedPreferences sp = getSharedPreferences("key", 0);
     SharedPreferences.Editor sedt = sp.edit();
     sedt.putString("textvalue", txtEvent.getText().toString());
     sedt.putString("txtopertaive", txtOperative.getText().toString());
     sedt.commit();
    

    Now after that retrieve it anywhere in your Activity class or any other Activity by

     SharedPreferences sp = getSharedPreferences("key", 0);
     String tValue = sp.getString("textvalue","");
     String tOperative = sp.getString("txtopertaive","");