Anirudh
Anirudh

Reputation: 3358

Value stored in shared preferences is not being reflected

package com.example.shared;

import android.app.Activity;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends Activity {
Button bshared;
TextView tv;
String x;
SharedPreferences pref;
Editor edit;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    bshared = (Button) findViewById(R.id.bshared);
    tv = (TextView) findViewById(R.id.tv);

    tv.setText(x);
    bshared.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
                  pref=getApplicationContext().getSharedPreferences("details",1);
            edit = pref.edit();
            edit.clear();
            edit.putString("name", "These are new values");
            edit.commit();
            x = pref.getString("name", "");

        }
    });

}
}

When i click on the button the value of textview must change to 'These are new values', but that is not happening. Can someone help me find my mistake ?

Upvotes: 0

Views: 905

Answers (2)

Renjith
Renjith

Reputation: 5803

The textview is setting the text before you change your text. So it will not be reflected in the textview. add this line to last of onclick method after you change value of the string.

tv.setText(x);

EDIT:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    bshared = (Button) findViewById(R.id.bshared);
    tv = (TextView) findViewById(R.id.tv);

    pref=getApplicationContext().getSharedPreferences("details",1);
    x = pref.getString("name", "");

    tv.setText(x);
    bshared.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            edit = pref.edit();
            edit.clear();
            edit.putString("name", "These are new values");
            edit.commit();
            x = pref.getString("name", "");
            tv.setText(x);


        }
    });

}
}

Upvotes: 2

Chirag
Chirag

Reputation: 56925

In on Click Method you have to set value to textview like below code.

pref=getApplicationContext().getSharedPreferences("details",1);
x = pref.getString("name", "");
tv.setText(x);
bshared.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) 
        {
            edit = pref.edit();
            edit.clear();
            edit.putString("name", "These are new values");
            edit.commit();
            x = pref.getString("name", "");
            tv.setText(x);
        }
    });

Upvotes: 2

Related Questions