On Mar 3, 5:30 pm, Jesse McGrew <[email protected]> wrote:
> I'm writing a simple app based on on the NotePad V3 example. In my
> activity to edit a record, I have these methods:
>
>     @Override
>     protected void onSaveInstanceState(Bundle outState) {
>         super.onSaveInstanceState(outState);
>         if (mRowId != null)
>                 outState.putLong(MyDbAdapter.KEY_ROWID, mRowId);
>     }
>
>     @Override
>     protected void onPause() {
>         super.onPause();
>         saveState();
>     }
>
> saveState() is defined pretty much as it is in the example: if mRowId
> is set, it updates the existing database row, otherwise it creates a
> new row and sets mRowId to point to it.
>
> The problem I'm having is that when I change the screen orientation
> during this activity, I get duplicate rows. A row is inserted when I
> flip the screen, then another row is inserted when I leave the
> activity.
>
> Presumably, onSaveInstanceState() is being called first when the
> activity is destroyed for the configuration change. Since there's no
> row ID yet, it doesn't store a row ID in the bundle. Then onPause() is
> called, which creates a new row, but it's too late to save the row ID
> for next time. When the activity is recreated in the new orientation,
> the bundle has no row ID, so the activity thinks it's creating a new
> record instead of editing the one it just saved.
>
> What's the recommended fix here? Should I persist to the database in
> onSaveInstanceState() as well as onPause()? Or is there some way for
> onPause() to store the row ID where the activity can find it later
> after being recreated?

FWIW, I ended up making it save the row in either onSaveInstanceState
() or onPause(), whichever one runs first.

I also looked at the notepad app in the SDK samples, which uses a
content provider. The way that one works is it creates the row as soon
as you start editing a note, and then deletes the row if you leave
without entering anything. I decided not to use that approach - I only
want valid rows in the database.

Jesse
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google
Groups "Android Beginners" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/android-beginners?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to