Saving EditText and retrieve it automatically

前端 未结 3 655
遇见更好的自我
遇见更好的自我 2021-01-29 10:50

hi I\'m trying to save the EditText widget values in the internal memory of the phone/tablet so that they can be retrieved automatically by the app when it closes or the activit

3条回答
  •  鱼传尺愫
    2021-01-29 11:33

    public class MainActivity extends AppCompatActivity {
        private Button button;
        private EditText editText;
        private final String KEY = "edittextValue";
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            editText = (EditText) findViewById(R.id.edittext);
            editText.setText(getValue());
    
            button = (Button) findViewById(R.id.button1);
            button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    saveFromEditText(editText.getText().toString());
                }
            });
    
        }
    
        private String getValue() {
            SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
            String savedValue = sharedPref.getString(KEY, ""); //the 2 argument return default value
    
            return savedValue;
        }
    
        private void saveFromEditText(String text) {
            SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
            SharedPreferences.Editor editor = sharedPref.edit();
            editor.putString(KEY, text);
            editor.apply();
        }
    
    }
    

提交回复
热议问题