cursor adapter looses data when application minimized - android

I am using a cursor adapter to retrieve the data from the database and binding it to the spinner control.
It's working fine but the problem occurs when user sending the application in the background after that all the spinner control looses the data.
Help me,
Waiting for your valuable answers.

ya it will happen, for that you have to save object Instance using below methods 0f Activity
#Override
protected void onRestoreInstanceState(Bundle savedState) {
super.onRestoreInstanceState(savedState);
// retrieve stored data
savedState.get[...]
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
// and place it
outState.put[...]
}

Related

Instance state serializable loses data

In one of Activities I have HashSet<Integer> mSelectedPositions. I want to save state of this set on screen rotation.
#Override
protected void onSaveInstanceState(#NotNull Bundle outState) {
super.onSaveInstanceState(outState);
outState.putSerializable(SELECTED_TYPES_POSITIONS, mSelectedPositions);
}
And restore it
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(savedInstanceState!= null && savedInstanceState.containsKey(SELECTED_TYPES_POSITIONS)){
mSelectedPositions = (HashSet<Integer>) savedInstanceState.getSerializable(SELECTED_TYPES_POSITIONS);
}
...
}
The problem is, getSerializable(..) returns an empty HashSet, even then it wasn't empty in putSerializable(..).
What's even weirder, I have almost the same code (with other keys) in other Fragments, and it works fine.
Don't know if matters, but activity in question is a child of MainActivity.
Upd
Part of the problem is in selection flow. On destroy of activity action mode is finished.
#Override
protected void onDestroy() {
if(mActionMode != null){
mActionMode.finish();
}
super.onDestroy();
}
Which triggers
#Override
public void onDestroyActionMode(ActionMode mode) {
mAdapter.clearSelections();
mActivity.nullifyActionMode();
}
in SelectionCallback.
I think, next thing happens:
1. I put mSelectedPositions in outState Bundle, it stores reference
2. Activity is destroyed
3. SelectionCallback clears mSelectedPositions
4. Actual serialization happens with empty HashSet.
So I made some changes — new HashSet with copy of mSelectedPositions data
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putSerializable(SELECTED_TYPES_POSITIONS, new HashSet<>(mSelectedPositions));
}
And it works like it should.
Upd2
In Fragments I call mActionMode.finish() in onDetach(), which is not called on screen rotation, so mSelectedPositions there remains intact.
Try putting a Json instead of raw HashMap
#Override
protected void onSaveInstanceState(#NotNull Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString(SELECTED_TYPES_POSITIONS,new Gson().toJson(mSelectedPositions));
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(savedInstanceState!= null && savedInstanceState.containsKey(SELECTED_TYPES_POSITIONS)){
String data = savedInstanceState.getString(SELECTED_TYPES_POSITIONS);
if(data != null){
mSelectedPositions = new Gson().fromJson(str, new TypeToken<HashSet<Integer>>() { }.getType())
}
}
...
}
The funny thing is that serialization of outState happens after onDestroy() call. And I was erasing data passed to outState in onDestroy.
So, there are two ways to fix that:
• pass copy of data to outState
• don't erase data in onDestroy
Opted for second option. Erasing might be required in some cases in onDetach() of Fragments, but it is not necessary with Activity.

Persist RecycyclerViewAdapter data on activity recreation

I have an Activity with a Fragment inside.
In that fragment there are RecyclerView, and RecyclerViewAdapter.
In fragment's onCreate I'm doing this:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d("TAGGG", "onCreate: ");
// Database handler
Contract.DbHelper dbHelper = new Contract.DbHelper(getContext());
dERecyclerViewAdapter.setEntries(dbHelper.readAllEntries());
}
Everytime the Activity is recreated(up navigation, rotation changes) data is being read again from the database.
What is the correct way to store it?
You can use the savedInstanceState to store the data through a bundle. You can store it like this
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
//Use the bundle to store data
}
And retrieve it like this
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(savedInstanceState!=null)
{
//Use the savedInstanceState to get the stored result
}
}
Hope this helps !
You should look at the CursorLoader class. Your situation is exactly what this class was intended for.
The loader itself can persist between configuration changes, so that when you call onCreate, if the loader has already performed the query it will just provide the data it already read rather than re-query the database.
See https://developer.android.com/guide/components/loaders.html
Also http://www.androiddesignpatterns.com/2012/07/understanding-loadermanager.html

RecyclerView restore items and managing pagination after rotation

I'm wondering if there is a way to restore, after rotation, my list of results without retaining the fragment.
Basically I have a fragment which calls, through a presenter, some api (using RxJava and Retrofit). I added pagination so I can make a call only when I need more data scrolling down.
I'm in the following scenario:
- I scroll the list down in order to call the second page from the web
- I rotate the screen
In this case what I would need is to show all the items, from page 1 and 2, and then scrolling to the correct position (for this I can use the onSaveInstanceState of the LayoutManager).
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FwApplication.component(getActivity()).inject(this);
if (savedInstanceState != null) {
mRxRunning = savedInstanceState.getBoolean(EXTRA_RX);
mQuery = savedInstanceState.getString(QUERY_ARG);
mCurrentPage = savedInstanceState.getInt(CURRENT_PAGE);
}
}
#Override
public void onSaveInstanceState(Bundle outState) {
outState.putString(QUERY_ARG, mQuery);
outState.putInt(CURRENT_PAGE, mCurrentPage);
outState.putParcelable(LAYOUT_STATE, mRecyclerView.getLayoutManager().onSaveInstanceState());
super.onSaveInstanceState(outState);
}
#Override
public void onResume() {
super.onResume();
mPresenter.onResume(mRxRunning, mCurrentPage);
}
Is there a way to save the items without calling setRetainInstance? Moreover I would avoid to call the api in order to get all the items back.
The items are POJOs so it won't be a list of simple strings.
Try to edit the Manifest file. Add this line to block with activity:
android:configChanges="keyboardHidden|orientation|screenSize">
It will prevent Activity restart on such events (specially on orientation change)

SaveInstanceState on ListView objects

I have an activity that perform a search of movies and parse the JSON results into "Movie" Objects.
after the parsing the Movie objects are being inserted into a ListView Adapter.
When i change oriantation the activity restarts and the results are gone.
How can i prevent this from happen or save the Objects and restore them onRestoreInstanceState?
I have already tried onConfigurationChanged.
You need to do a little bit of refactoring.
First implement onSaveInstanceState and save your list to a bundle
#Override
protected void onSaveInstanceState (Bundle outState){
outState.putSerializable("mylist", mylist);
}
Then on your OnCreate check if your bundle has the list and opulate your listview without fetching again your list
#Override
protected void onCreate (Bundle savedInstanceState){
super.onCreate(savedInstanceState);
if(savedInstanceState!=null && savedInstanceState.getSerializable("mylist")!=null){
populateListView(savedInstanceState.getSerializable("mylist"));
}else{
fetchList();
}
}

Save Checkboxes state in ListView and Retrieve it back when come back to class using Shared preferences

I Got stucked in saving the Checkboxes state and getting back in listview, i want to save what all the items were checked and save it and get it back when the Activity is called again... Pls help me in this with sample code... any help will be very usefull for me.
Here is the sample code(But not using sharedPreferences)
public class SavedInstanceDemo extends Activity{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//retrieve values from savedInstanceState
Boolean isChecked=savedInstanceState.getBoolean("isChecked",false);
}
#Override
public void onSaveInstanceState (Bundle outState){
//save your requires values into this outState which can be retrieved on next time
outState.putBoolean("isChecked", true);
}
}

Categories

Resources