I have an activity setup with an edittext field and an add button. Essentially when the user makes changes to the edittext and hits Add, a new textview should be created with the edittext field. In addition i want the textviews created to be available even after i leave the screen or activity. The problem i have is that when i click add, a default values shows in the newly created textview each time, and when i leave the activity, all the textviews are gone altogether. Any suggestions?
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());
etDocNote.setOnKeyListener(new View.OnKeyListener() {
public boolean onKey(View v1, int keyCode1, KeyEvent event1) {
if ((event1.getAction() == KeyEvent.ACTION_DOWN) &&
(keyCode1 == KeyEvent.KEYCODE_ENTER)) {
getSharedPreferences("myprefs", 0).edit().putString("etDocNote", etDocNote.getText().toString()).commit();
return true;
}
return false;
}
});
}
private OnClickListener onClick() {
// TODO Auto-generated method stub
return new OnClickListener(){
public void onClick(View v) {
// TODO Auto-generated method stub
String newDocNote = getSharedPreferences("myprefs", 0).getString("etDocNote", "" );
nLayout.addView(createNewTextView(newDocNote));
}
};
}
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;
}
}
So your question has two parts:
Right now you have a timing issue. You are trying to save in shared preferences the text when someone punched keys. This is not necessary since you can retrieve the editText contents when the add button is clicked.
Here is what you need to do: Remove setOnKeyListener and change your onClick() function to be
Since your text is now saved in shared preferebnces. In your oncreate, you need to retrieve and restore your TextViews.