1

How do you preserve singleton database data in an activity after a screen rotation without using Content Provider or loaders?

This was an interview question I got stumped on.

ContentProvider with cursor loader was my first thought, but they said they didn't want that. Then I thought of saving the cursor returned from the singleton DB's query method, but I couldn't "put" a cursor in the out bundle in OnSavedInstance, so I have no idea.

I also asked them "isn't using a singleton database discouraged?" to which they said "yes, but this is just for interview purposes."

Maybe this can help someone in the future who encounters this question.

eric
  • 383
  • 1
  • 2
  • 10
  • "In an activity" sounds like I'm not allowed to pass all the stuff to the application class (which will not be destroyed on screen rotation). So I'd use a [retained Fragment](https://developer.android.com/guide/topics/resources/runtime-changes.html#RetainingAnObject) – Bö macht Blau Mar 23 '18 at 17:37
  • Retained fragment makes a lot of sense, thanks. By "passing to the application class", do you mean having something like "public static MyApplication varName" in MainActivity that I store info in? (You could answer my question and I'll give you the green checkmark btw) – eric Mar 23 '18 at 20:11

2 Answers2

1

"In an activity" sounds like I'm not allowed to pass all the stuff to the application class (which will not be destroyed on screen rotation). But just in case this is an option:

You write your own class which extends from Application. The official documentation tells you how to do it but states that you basically don't need to. Having said that, this Stack Overflow post is a collection of possible exceptions from the rule.

In the Activity, you access it like this:

MyApplication app = (MyApplication)getApplication();

But personally I'd keep data for one Activity not in the Application class but inside a retained Fragment. They survive configuration changes but keep in mind that they are not part of the back stack. So if you have a savedInstanceState != null, the retained Fragment may nevertheless have been recreated in its initial state e.g. if the app has been paused for a while.

The guide on Handling Configuration Changes shows how to use retained Fragments

Bö macht Blau
  • 12,820
  • 5
  • 40
  • 61
1

You can use fragments and use Fragment#setRetainInstance(true) for that. And all the data should be saved across configuration changes. Note that a retained fragment is not visual its placed along your Activity or Fragment This might help you: https://www.androiddesignpatterns.com/2013/04/retaining-objects-across-config-changes.html

Raykud
  • 2,488
  • 3
  • 21
  • 41