Save user input to SharedPrefernces and set Value to EdiText

北战南征 提交于 2019-12-08 14:06:27

File f = new File(PREF_FILE_NAME); just has the name of the preference so f.exists() will always returns false

Solution : Remove

File f = new File(PREF_FILE_NAME);
if (f.exists()){

because if you don't have any value then simply use the default value

@Override
public void onStart(){
    super.onStart();
    //File f = new File(PREF_FILE_NAME); // not a right path
    //if (f.exists()){ // false
        idType = prefs.getInt("idType", 0);
        idNumber = prefs.getString("idNumber", "");
        expiryDate = prefs.getString("expiryDate", "");

        edtIdNumber = (EditText) findViewById(R.id.edtIdNumber);
        txtDate = (TextView) findViewById(R.id.txtDate);
        txtDate.setText(expiryDate);
        edtIdNumber.setText(idNumber);
        edtIdNumber.setText(idNumber);
        txtDate.setText(expiryDate);

    //}
}

Alternatively you can use contains

To Achive your work: First of all try to understand difference between onCreate() and onStart() method of Activity in android, follow following url: https://developer.android.com/guide/components/activities/activity-lifecycle.html -: use onCreate() method instead of onStart() for setting ui variables;

secondly change in your code like:

public void onClick(View view) {
            expiryDate = txtDate.getText().toString();
            edtIdNumber = (EditText) findViewById(R.id.edtIdNumber);
            idNumber = edtIdNumber.getText().toString();
            SharedPreferences.Editor editor = prefs.edit();
            editor.putInt("idType", idType);
            editor.putString("idNumber", idNumber);
            editor.putString("expiryDate", expiryDate);
            editor.commit();
        }

just remove if (f.exists()) condition from Onstart() because File f = new File(PREF_FILE_NAME); just has the name of the preference so f.exists() will always returns false

like below code

     @Override
public void onStart(){
    super.onStart();
   /* File f = new File(PREF_FILE_NAME);
    if (f.exists()){*/
        idType = prefs.getInt("idType", 0);
        idNumber = prefs.getString("idNumber", "");
        expiryDate = prefs.getString("expiryDate", "");

        edtIdNumber = (EditText) findViewById(R.id.edtIdNumber);
        txtDate = (TextView) findViewById(R.id.txtDate);
        txtDate.setText(expiryDate);
        edtIdNumber.setText(idNumber);
        txtDate.setText(expiryDate);


}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!