I'm making an app with content structure somewhat similar to Reddit. In my MainActivity.java
I have a RecyclerView that could possibly have really much content. The content is loaded from the web, and I don't want to load it again everytime when the screen rotates.
So, I have a RecyclerView setup something like this:
MainActivity.java
List<CustomItem> data;
// Volley and GSON magic to load content from the web into data list
GsonRequest gsonRequest = new GsonRequest<CustomResponse>("http://example.json",
CustomResponse.class, null, new Response.Listener<CustomResponse>(){
@Override
public void onResponse(CustomResponse response) {
for(CustomItem item : response.getItems()){
data.add(item);
}
mAdapter = new CustomAdapter(data);
mRecycler.setAdapter(mAdapter);
},
new Response.ErrorListener(){
@Override
public void onErrorResponse(VolleyError error) {
Log.d("E", error.getMessage());
}
});
VolleySingleton.getInstance().getRequestQueue().add(gsonRequest);
CustomResponse.class
public class CustomResponse {
@SerializedName("items")
private List<CustomItem> items;
public List<CustomItem> getItems(){
return items;
}
CustomItem.java is something like this, although I have a lot more variables in it
public class CustomItem {
@SerializedName("id") // that awesome GSON magic
public long mID;
@SerializedName("title");
public String mTitle;
@SerializeName("another_item")
public AnotherItem mAnotherItem; // A custom object that I need
}
Obviously the data is loaded every time the screen orientation changes.
My question is: How do I persist the data on my RecyclerView when the configuration changes? What's the best way?
I'm thinking of only two options:
- making
List<CustomItem> data
Parcelable, and saving it inonSaveInstanceState()
and restore the data when needed - Using Sqlite to write the contents to a database, and populate my RecyclerView from there. Remove content from there when not needed.