如何保存文本字段响应而不清除

时间:2017-09-13 21:14:19

标签: java android android-sharedpreferences

我正在尝试创建一个简单的待办事项列表样式应用。我已经使用SharedPreferences成功保存了字符串,因为我可以在日志中引用它,但我想这样做,以便字符串保持附加到文本字段而不是每次重新打开应用程序时清除(直到更改或被用户删除)。任何其他建议将不胜感激。

(MainActivity)

public void go(View view) {

    Intent intent1 = new Intent(SecondActivity.this, myPreferences.class);

    String passGoal1 = goal1.getText().toString();

    intent1.putExtra("goal1", passGoal1);

    startActivity(intent1);
}

还实现了第一个答案中引用的myPreferences类。

public class myPreferences {

    private SharedPreferences pref;

    private SharedPreferences.Editor editor;

    private Context context;

    int PRIVATE_MODE = 0;

    private static final String PREF_NAME = "MyPreferencesName";

    public final static String KEY_NAME = "key_value";

    public myPreferences(Context context) {

        this.context = context;

        pref = context.getSharedPreferences(PREF_NAME,PRIVATE_MODE);

        editor = pref.edit();
    }

    public void setFunction(String data) {

        editor.putString(KEY_NAME, data);
    }
}

1 个答案:

答案 0 :(得分:1)

在您的共享首选项中创建一个get函数,用于获取存储的数据并在textfield中每次查看

public class MyPreferences {

private SharedPreferences pref;

// Editor for Shared preferences
private SharedPreferences.Editor editor;

// Context
private Context context;

// Shared pref mode
int PRIVATE_MODE = 0;

// Sharedpref file name
private static final String PREF_NAME = "MyPreferencesName";

public final static String KEY_NAME = "key_value";

public MyPreferences(Context context) {
    this.context = context;
    pref = context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
    editor = pref.edit();
}

public void setFunction(String data) {
    editor.putString(KEY_NAME, data);
    editor.commit();
}

public String getFunction() {
    return pref.getString(KEY_NAME, "");
}
}

在您的活动中初始化SharedPreferences并执行以下操作:

private MyPreferences myPreferences;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    myPreferences = new MyPreferences(this);

    //To set EditText data from SavedPreferences
    textField.setText(myPreferences.getFunction());
}

//To save the latest data from EditText.
@Override
protected void onStop() {
    Log.d("LifeCycle", "onStop: ");
    super.onStop();
    myPreferences.setFunction(editText.getText().toString());
}