GMX GMX - 1 month ago 18
Android Question

How handle internet connection change on BIG AyncTask

I'm developing an Android application that do a big work in a AsyncTask (can be 5 minutes of AsyncTask activity).

This Task need the internet connection so at the start I check if the device is online or not.

BUT IF the user change connection from wi-fi to mobile connection or go offline when the GraphRequest is running i got a crash with this error:


Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'org.json.JSONObject org.json.JSONObject.getJSONObject(java.lang.String)' on a null object reference


Here is the part of the code where crash:

// I Check if the device is online, if yes:

for(j=0; j<n_foto_pub;j++) {

GraphRequest request2 = GraphRequest.newGraphPathRequest(
AccessToken.getCurrentAccessToken(),
"MY_QUERY",
new GraphRequest.Callback() {
@Override
public void onCompleted(GraphResponse response) {

try {
JSONObject obj1 = response.getJSONObject();
JSONObject obj2 = obj1.getJSONObject("data1"); <--- CRASH HERE
JSONObject obj33 = obj2.getJSONObject("data2");
int ris = obj3.getInt("ris");
..........

} catch (JSONException e) {
e.printStackTrace();
}

}
});
request2.executeAndWait();
}


I have a catch but crash anyways.

How can i avoid the app crash and instead maybe kick the user back on the previous activity?

Answer

See below code , u will get better idea.

    @Override
  protected String doInBackground(String... params) {
  {
    try
    {
        //Your operation always inside try catch block to avoid crash.
        for(j=0; j<n_foto_pub;j++) 
        {
           if(checkInternet()) //check internet for each loop
           {

           }
           else
           {
             callBackActivity();
           }
        }
    }
    catch(Exception e)
    {
        e.printStackTrace();
         callBackActivity();
    }
  }
Comments