问题
Whenever i relaunch my app, getting old values into TextView if some stored by me, but facing a small issue, now after relaunching my app once i do tap on button, it deletes earlier stored data from TextView and shows new one.
I am using SharedPreferences in my program to store textview data, which works just fine for me.
May i know where i am doing mistake ?
see my code below:
public class MainActivity extends ActionBarActivity {
TextView textViewResult;
EditText editTextInput;
String strInput = "";
Button btnInput;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(this);
textViewResult = (TextView) findViewById(R.id.textResult);
editTextInput = (EditText) findViewById(R.id.editInput);
textViewResult.setText(prefs.getString("autoSave", ""));
textViewResult.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
}
@Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
@Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
prefs.edit().putString("autoSave", s.toString()).commit();
}
});
btnInput = (Button) findViewById(R.id.button1);
btnInput.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
String check = editTextInput.getText().toString();
if(check.equalsIgnoreCase("ABC"))
{
strInput = strInput+","+check;
Toast.makeText(getApplicationContext(), "done", Toast.LENGTH_LONG).show();
textViewResult.setText(strInput);
editTextInput.setText("");
}
else {
Toast.makeText(getApplicationContext(), "error", Toast.LENGTH_LONG).show();
}
}
});
}
}
回答1:
Try this..
btnInput.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
String check = editTextInput.getText().toString();
if(check.equalsIgnoreCase("ABC"))
{
strInput = textViewResult.getText().toString()+","+check;
Toast.makeText(getApplicationContext(), "done", Toast.LENGTH_LONG).show();
textViewResult.setText(strInput);
editTextInput.setText("");
}
else {
Toast.makeText(getApplicationContext(), "error", Toast.LENGTH_LONG).show();
}
}
});
EDIT
Use split("")
String[] total_abc = textViewResult.getText().toString().split(",");
int total = total_abc.length;
回答2:
put prefs.edit().putString("autoSave", s.toString()).commit(); on the OnClick event
and remove textViewResult.setText(prefs.getString("autoSave", "")); instead of it write textViewResult.setText(prefs.getString("autoSave")); you just specify the key value when getting from sharedpreferences thats why you get blank
来源:https://stackoverflow.com/questions/24096173/on-button-click-deletes-existing-data-from-textview-after-re-launching