Saving EditText and retrieve it automatically

2019-03-06 17:01发布

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 activity stops. All off this will work using a save button.(The values of the widget are inputed by the user).

3条回答
够拽才男人
2楼-- · 2019-03-06 17:34
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();
    }

}
查看更多
祖国的老花朵
3楼-- · 2019-03-06 17:44

If you want to save single value like name, address, phone_no etc then use SharedPreferences or want to save like same value multiple times then use Sqlite.

References : Sqlite , SharedPreferences

查看更多
迷人小祖宗
4楼-- · 2019-03-06 17:46

You should use the shared preference ,shared preference is used to store the data in locally app whenever need you can access it . use this link https://www.journaldev.com/9412/android-shared-preferences-example-tutorial

to use it. after on button click you can get the value . its help me

查看更多
登录 后发表回答