0

I have an android app where I'm displaying results from my RESTfull webservice in an Activity with a RecyclerView (wrapped in a SwipeRefreshLayout). In onCreate I set up the Adapter etc. and start a request with volley. When I change the orientation of my device that same request is started.

How can I prevent my app from unnecessary web requests on orientation change?

I mean all my data is already loaded so no request is necessary.

Edit: This is my try in avoiding the requests, but after change of orientation there are still requests:

private ArrayList<Item> mDataSet;

protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//...
if (mDataSet== null){
mDataSet = new ArrayList<>();
}

if (mDataSet.size() == 0) {
startRequest();
}
//...
}
Froggie
  • 55
  • 7
  • oh come on ... cache the data ... if cache == null then call volley ... naive implementation: some static container ... less naive: retainable fragment ... other: storage cache(SP, file, db) – Selvin Jul 14 '15 at 13:53
  • I edited it with my try of caching the data... – Froggie Jul 14 '15 at 14:06
  • 1
    as i wrote: *static container* ... orientation changing create new instance of Activity .... so, in short: mDataSet will be always null in onCreate – Selvin Jul 14 '15 at 14:08
  • Ah damn. Just added that little magic word `static` to the declaration of my `mDataSet` and it worked. How can I accept your "answer"? – Froggie Jul 14 '15 at 14:16

2 Answers2

0

You can try using a loader which works in the background and survives orientation change.

Nathan Tuggy
  • 2,237
  • 27
  • 30
  • 38
LoveBhardwaj
  • 1
  • 1
  • 1
0

You can take a look at this post.

Basically what you need to do is saving the state of your application when orientation changes.

private static final String KEY_TEXT_VALUE = "textValue";
private ArrayList<Item> mDataSet;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (savedInstanceState != null) {
        /* use Gson for returning a JSON object */
        /* for lists we have to use a Type Object */
        Type listType = new TypeToken<ArrayList<Item>>(){}.getType();
        String listJson = savedInstanceState.getString(KEY_TEXT_VALUE);
        mDataSet = new Gson().fromJson(listJson, listType);
    } else {
        // make call to get fresh data!
    }
}

@Override
protected void onSaveInstanceState (Bundle outState) {
    super.onSaveInstanceState(outState);
    /* we are using Gson to write object as JSON! For me works better than Serialization :) */
    Gson gson = new Gson();
    outState.putString(KEY_TEXT_VALUE, gson.toJson(mDataSet));
}
Community
  • 1
  • 1