Reena Reena - 5 months ago 9
Android Question

Changed text at the runtime in textview but after relaunching application retrieving default data in textview in android

I am using Shared Preferences to store data which is came from

EditText
and set preferences data back to
TextView
but when i reopen my application textview shows default value. How can set changed data to the
TextView
and data should not be lost after reopening application. I tried
onSaveInstanceState()
and
onSaveInstanceState()
but this works when orientation change of application.

Here in my code i store data into shared Preferences and getting that data back to the
TextView
PRESET_MESSAGE_ONE i am storing value of
EditText
.

public void customDialogOne() {
mDialog = new Dialog(_con);
mDialog.setContentView(R.layout.custom_dialog_message);
mDialog.getWindow().setBackgroundDrawableResource(R.color.black);
mDialog.setTitle("Edit Preset Message");

btnPresetDialogCancel = (Button) mDialog
.findViewById(R.id.btnPrDialogCancel);
edtPresetDialogMessage = (EditText) mDialog
.findViewById(R.id.edtPrDialogMessage);

btnPresetDialogSave = (Button) mDialog
.findViewById(R.id.btnPrDialogSave);
btnPresetDialogSave.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
SharedPref.writeString(SharedPref.PRESET_MESSGE_ONE,
edtPresetDialogMessage.getText().toString());
msgOne = SharedPref.readString(SharedPref.PRESET_MESSGE_ONE);
tm.showToast(msgOne);
tvFrPresetMsgOne.setText(msgOne);
mDialog.dismiss();

}
});
btnPresetDialogCancel.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
mDialog.dismiss();
}
});
mDialog.show();
}

Answer

My issue has resolved my sequence was wrong to store value in shared Preferences, I used following code:

btnPresetDialogSave.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            tvFrPresetMsgOne.setText(edtPresetDialogMessage.getText()
                    .toString());
            SharedPref.writeString(SharedPref.PRESET_MESSGE_ONE,
                    edtPresetDialogMessage.getText().toString());

            msgOne = SharedPref.readString(SharedPref.PRESET_MESSGE_ONE);
            tvFrPresetMsgOne.setText(msgOne);
            mDialog.dismiss();

        }
    });

and read SharePreferences string in onResume method()