Need help to solve sharedPreference probem


Ask by : HFherasen November 05, 2013 11:42

I am working on this app where I have one EditText field where you can write something and then it get saved and added to a list(TextView). I save the content of the EditText in this way :

saved += "*" + editTextFelt.getText().toString() + ". \n";

saved is a String. Everything works fine, I can even reload the app and it's still displayed in the TextView, but if I try to write something and save it everything that was there, now dissapear. anyone know why ? It's kind of confusing, and I have to get it to work! Thank's!!

CODE: init Method()

sp = getSharedPreferences(fileName, 0);
betaView = (TextView)findViewById(R.id.betaTextView);

Ive got a button to send the text, and this is like: p

ublic void onClick(View v) {
        switch(v.getId()){
        case R.id.btnSend:
            saved += "*" + editTextFelt.getText().toString() + ". \n";
            SharedPreferences.Editor editor = sp.edit();
            editor.putString("SAVED", saved);
            editor.commit();

            betaView.setText(sp.getString("SAVED", "Empty"));   
View original question

Answer by : Adil SoomroNovember 04, 2012 16:55

How are you saving it? because when you save a text against a variable it replaces the previous one.

So you need to get the previous one and then append the new one and then again save it to SharedPreferences, something like this:

SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
String saved = sp.getString("YourVariable", "");
saved += "*" + editTextFelt.getText().toString() + ". \n"; //appending previous
//Editor to edit
SharedPreferences.Editor editor = preferences.edit();
editor.putString("YourVariable",saved);
editor.commit(); //don't forget to commit.

now set this appended text to your TextView like this:

betaView.setText(saved);
View original answer