How to implement undo/redo and preserve the value on orientation change in android EditText?

1.2k Views Asked by At

I am using the TextViewUndoRedo class for undo/redo operations and it works but I want the value preserved after orientation/onConfigurationChange.

There are two methods in that class: storePersistentState(Editor editor, String prefix) and restorePersistentState(SharedPreferences sp, String prefix), what do they do?

I guess, these are for onConfigurationChanged and implement in the following way, but they didn't work?

@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);

    vNoteText = vEditNote.getText().toString();

    //----------------------------------------------------------------//

    SharedPreferences sp = getSharedPreferences("unforedopref", 0);
    SharedPreferences.Editor editor;
    editor = sp.edit();

    mTextViewUndoRedo.storePersistentState(editor, "undoredokey");

    //----------------------------------------------------------------//

    setContentView(R.layout.notepadmain);


    vEditNote.setText(vNoteText);

    //----------------------------------------------------------------//    

    mTextViewUndoRedo.restorePersistentState(sp, "undoredokey");
}       

If you provide a undo redo technique which works onOrientationChange with example, it would be helpful.

1

There are 1 best solutions below

0
On
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
  super.onSaveInstanceState(savedInstanceState);
  SharedPreferences sp = getSharedPreferences("unforedopref", 0);

  mTextViewUndoRedo.storePersistentState(sp.edit(), "undoredokey");
}

@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
  super.onRestoreInstanceState(savedInstanceState);

  SharedPreferences sp = getSharedPreferences("unforedopref", 0);
  mTextViewUndoRedo.restorePersistentState(sp, "undoredokey");
}

You need to save and restore state in lifecycle methods of your activity