我正在创建一个具有3个EditTexts的android应用程序。 现在,当我关闭应用程序并返回它时,EditText中的值消失了,我必须返回上次输入的值。
如何在EditText中返回用户输入的值(按下按钮),以便用户在关闭和响应应用时不必一次又一次地输入整个文本?
提供代码的答案将有很大帮助!感谢。
答案 0 :(得分:1)
将此课程放在您的项目中
public class SaveData {
private static final String EDIT1 = "edit1";
private static final String EDIT2 = "edit2";
private static final String EDIT3 = "edit3";
SharedPreferences pref;
Editor editor;
Context mContext;
// Shared pref mode
int PRIVATE_MODE = 0;
public SaveData(Context context) {
this.mContext = context;
// Sharedpref file name
final String PREF_NAME = mContext.getString(R.string.app_name) + "_pref";
pref = mContext.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
editor = pref.edit();
}
public String getEditText1() {
return pref.getString(EDIT1, "");
}
public void setEditText1(String text) {
editor.putString(EDIT1, text);
editor.commit();
}
public String getEditText2() {
return pref.getString(EDIT2, "");
}
public void setEditText2(String text){
editor.putString(EDIT2, text);
editor.commit();
}
public String getEditText3() {
return pref.getString(EDIT3, "");
}
public void setEditText3(String text) {
editor.putString(EDIT3, text);
editor.commit();
}
}
现在onCreate把这个
SaveData saveData = new SaveData(this);
mEditText1.setText(saveData.getEditText1());
mEditText2.setText(saveData.getEditText2());
mEditText3.setText(saveData.getEditText3());
在onPause
SaveData saveData = new SaveData(this);
saveData.setEditText1(mEditText1.getText()+"");
saveData.setEditText2(mEditText2.getText()+"");
saveData.setEditText3(mEditText3.getText()+"");
答案 1 :(得分:0)
有几种方法可以存储此类型的数据,我个人会使用数据库表,特别是如果您准备好将数据库作为应用程序的一部分。如果不考虑写入和字符串数组来存档和阅读它。
如果您正在查看数据库选项,请执行类似
的操作// on create
String createTable = "CREATE TABLE texts (id INT NOT NULL,words TEXT)";
SQLiteDatabase db = MyDatabaseHelper.getDB(); // <- use the method you use to get a db.
db.exec(createTable);
db.close();
// on start up of your edit text activity
// create array of edit texts which you have initialized via their ids, it must be a member variable
EditText[] editTexts = new EditText[]{editText1,editText2,editText3};
SQLiteDatabase db;
String sql= "SELECT * from texts";
Cursor c = db.rawQuery(sql,null);
if(null !=c && c.moveToFirst())
{
for(int i = 0; i<c.getCount(); i++)
{
// get data from db
String text = c.getString(1);
int id = c.getInt(0);
editTexts[id].setText(text);
}
}
// to be called at the end of the activity or when then edit texts change
private void saveToDb(){
SQLiteDataBase db; // got from your sqlite helper method
for(int i =0; i<editTexts.length; i++)
{
// check for insert
String check = "SELECT * FROM texts WHERE id ="+i;
String ins;
Cursor c = db.rawQuery(check,null);
if(null != c && c.moveToFirst()){
// update
ins= "UPDATE texts SET words = '"+editTexts[i].getText().toString+"' WHERE id = "+i+";";
}else{
// insert
ins = "INSERT into texts (id,words) VALUES("+i+",'"+editTexts[i].getText().toString+"');";
}
db.exec(ins);
db.close();
}
}
我在没有将其作为指导测试的情况下编写了这个,我之前已经多次使用过这种模式并且效果很好