我有一项活动,允许用户输入注释并将其存储在动态创建的文本视图中。但是,当用户离开活动并返回时,所有创建的文本视图都会消失。每当我返回活动时,我如何存储商店或检索所有这些创建的文本视图?此外,我认为每次添加新的textview时我的共享偏好都会被覆盖。有什么建议吗?
public class DocNoteActivity extends Activity {
private LinearLayout nLayout;
private EditText etDocNote;
private Button btnAdd1;
public static final String PREFS_NAME = "MyPrefsFile";
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.adddocnote);
etDocNote = (EditText) findViewById(R.id.editDocNote);
btnAdd1 = (Button) findViewById(R.id.btnAdd1);
nLayout = (LinearLayout) findViewById(R.id.linearLayout);
TextView tvNote = new TextView(this);
tvNote.setText("");
btnAdd1.setOnClickListener(onClick());
}
private OnClickListener onClick() {
// TODO Auto-generated method stub
return new OnClickListener(){
public void onClick(View v) {
// TODO Auto-generated method stub
String newDocNote = etDocNote.getText().toString();
nLayout.addView(createNewTextView(newDocNote));
getSharedPreferences("myprefs", 0).edit().putString("etDocNote", newDocNote).commit();
}
};
}
private TextView createNewTextView(String newText) {
// TODO Auto-generated method stub
LayoutParams lparams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
TextView tvNote = new TextView(this);
tvNote.setLayoutParams(lparams);
tvNote.setText(newText);
return tvNote;
}
}
答案 0 :(得分:0)
如果要检索Notes,则必须使用数据库(即SQLite),因为每次将注释保存在SharedPreferences中时,它都将被覆盖。所以我建议你使用数据库。为此,我认为有一些有用的资源可以帮助你。
1 - http://www.androidhive.info/2011/11/android-sqlite-database-tutorial/
2 - http://www.vogella.com/articles/AndroidSQLite/article.html
3 - http://android-er.blogspot.in/2011/06/simple-example-using-androids-sqlite_02.html
注意 - SharedPreferences用于存储键值对数据。主要是我们可以用Android方式说一种会话管理。我主要存储用户名&在SharedPreferences中使用密码类型的数据。
希望这有帮助。