关闭并重新打开共享偏好中未显示的app保存数据?

时间:2017-08-15 11:44:46

标签: java android

我通过在android中使用sharedpreferences来保存android中的数据。

我能够成功保存数据,但我不知道是否显示关闭应用程序并重新打开保存的数据。

我的代码:

   public class MainActivity extends Activity {

EditText editText;
Button button;
Button button1;
TextView text;
public static final String mypreference = "MY_PREFS_NAME";
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);


    editText = (EditText) findViewById(R.id.editText);
    button = (Button) findViewById(R.id.button);
    button1 = (Button) findViewById(R.id.button2);
    text = (TextView) findViewById(R.id.textView);
    button.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {

            SharedPreferences shared = getSharedPreferences(mypreference, MODE_PRIVATE);
            SharedPreferences.Editor editor = shared.edit();
            editor.putString("mn",editText.getText().toString());
            editor.commit();

            SharedPreferences prefs = getSharedPreferences(mypreference, MODE_PRIVATE);
            String ap = prefs.getString("mn","");
            text.setText(ap);




        }

    });

1 个答案:

答案 0 :(得分:1)

您正在onClick

中执行此操作
SharedPreferences prefs = getSharedPreferences(mypreference, MODE_PRIVATE);
String ap = prefs.getString("mn","");
text.setText(ap);

所以下次不会自动onLoad。如果您想这样做,可以在clickListener实现之外的onCreate方法中移动这些行,如下所示。

 SharedPreferences prefs = getSharedPreferences(mypreference, MODE_PRIVATE);
 String ap = prefs.getString("mn","");
 text.setText(ap);
 button.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View view) {

        SharedPreferences shared = getSharedPreferences(mypreference, MODE_PRIVATE);
        SharedPreferences.Editor editor = shared.edit();
        editor.putString("mn",editText.getText().toString());
        editor.commit();

        SharedPreferences prefs = getSharedPreferences(mypreference, MODE_PRIVATE);
        String ap = prefs.getString("mn","");
        text.setText(ap);

    }

});