Search code examples
javaandroidandroid-savedstate

Error on doing a background task after returning from child task


I'm not sure I fully understand what needs to be done to retrieve data after returning from a child activity. I don't need to pass data to the parent activity. I used this for reference, they do mention onPause and onResume as well as possible solutions but should I use saved preferences instead of onSaveInstanceState and onRestoreInstanceState? It fails at the background task of checking the boolean. I also used this this for further assistance.

Code Below:

@Override 
public void onSaveInstanceState(Bundle savedInstanceState) {
    super.onSaveInstanceState(savedInstanceState);
    // Save UI state changes to the savedInstanceState.
    // This bundle will be passed to onCreate if the process is
    // killed and restarted.
    savedInstanceState.putString("type",type);
}

@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
    // Restore UI state from the savedInstanceState.
    // This bundle has also been passed to onCreate.
    super.onRestoreInstanceState(savedInstanceState);
    type = savedInstanceState.getString("type");
}

public class getFeed extends AsyncTask<String, Void, Void>{
    @Override
    protected Void doInBackground(String... strings) {
        ParseQuery<ParseObject> contentFeed = new ParseQuery<>("UserCommentary");
        if(type.equals("object1")){
            //Query for object1
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }
    else if(type.equals("object2")){
        //Query for object2
    }

    return null;
}

@Override
protected void onPostExecute(Void aVoid) {
    super.onPostExecute(aVoid);
    mySwipeRefreshLayout.setRefreshing(false);
    commentary.setAdapter(vCommentDetailAdapter);
    vCommentDetailAdapter.notifyDataSetChanged();
}

EDIT: Added more info to code


Solution

  • In hindsight of your comment that the getFeed AsyncTask is getting executed in onCreate().

    You are basically calling it too earlier. See here for the Android Activity lifecycle.

    onCreate() / onStart() gets called before onRestoreInstanceState(). So put the execution of the Task in your onResume() method.