简体   繁体   中英

Handle NPE Gracefully and Display AlertDialog in OnPostExecute / AsyncTask When Internet Connection Is Lost - Android / Java

I'm getting a NPE (as expected) in my AsyncTask during a loss of internet connectivity. I've attempted to do a bit of null checking then display an alertDialog if the result is null - however I the program is still crashing and is not stopping gracefully. How might this be avoided / what am I missing in this code?

Source:

@Override
protected void onPostExecute(FunctionResult result) {
    if (result != null) {
        listener.callback(result);
    }
    else {
        String errorMsg = "Failed";
        AlertDialog.Builder builder = new AlertDialog.Builder(null);
        builder.setMessage(errorMsg)
       .setTitle("Error")
       .setNeutralButton("OK", new DialogInterface.OnClickListener() {
           public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();                                                    
           }
        }).create().show();

    }
}

LogCat:

05-27 17:13:11.250: E/AndroidRuntime(23343): FATAL EXCEPTION: main
05-27 17:13:11.250: E/AndroidRuntime(23343): java.lang.NullPointerException
05-27 17:13:11.250: E/AndroidRuntime(23343):    at com.example.login.wstasks.WebTask.onPostExecute(WebTask.java:65)
05-27 17:13:11.250: E/AndroidRuntime(23343):    at com.example.login.wstasks.WebTask.onPostExecute(WebTask.java:1)
05-27 17:13:11.250: E/AndroidRuntime(23343):    at android.os.AsyncTask.finish(AsyncTask.java:631)
05-27 17:13:11.250: E/AndroidRuntime(23343):    at android.os.AsyncTask.access$600(AsyncTask.java:177)
05-27 17:13:11.250: E/AndroidRuntime(23343):    at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
05-27 17:13:11.250: E/AndroidRuntime(23343):    at android.os.Handler.dispatchMessage(Handler.java:99)
05-27 17:13:11.250: E/AndroidRuntime(23343):    at android.os.Looper.loop(Looper.java:137)
05-27 17:13:11.250: E/AndroidRuntime(23343):    at android.app.ActivityThread.main(ActivityThread.java:5041)
05-27 17:13:11.250: E/AndroidRuntime(23343):    at java.lang.reflect.Method.invokeNative(Native Method)
05-27 17:13:11.250: E/AndroidRuntime(23343):    at java.lang.reflect.Method.invoke(Method.java:511)
05-27 17:13:11.250: E/AndroidRuntime(23343):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
05-27 17:13:11.250: E/AndroidRuntime(23343):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
05-27 17:13:11.250: E/AndroidRuntime(23343):    at dalvik.system.NativeStart.main(Native Method)
05-27 17:13:21.240: V/TaskManager(23343): In executeTask() on BACKGROUND THREAD
05-27 17:13:21.290: D/dalvikvm(23343): GC_CONCURRENT freed 406K, 9% free 4779K/5224K, paused 4ms+3ms, total 31ms
05-27 17:13:21.340: V/TaskManager(23343): In logTaskInfo() on BACKGROUND THREAD
05-27 17:13:21.340: V/TaskManager(23343): -------------------
05-27 17:13:21.340: V/TaskManager(23343): -------------------

Replace

AlertDialog.Builder builder = new AlertDialog.Builder(null);

with

AlertDialog.Builder builder = new AlertDialog.Builder(YOUR_ACTIVITY_NAME.this);

EDIT : you need to handle it in activity itself as mentioned:

protected void onPostExecute(FunctionResult result) {
                    listener.callback(result);
    }

and

KeepAliveData data = new KeepAliveData();
                            FunctionResult keepAliveResponse = null;
                            try {
                                    keepAliveResponse = new KeepAliveTask(variables.login, data)
                                                    .execute().get();




if (keepAliveResponse == null) {
        String errorMsg = "KeepAlive Failed";
        AlertDialog.Builder builder = new AlertDialog.Builder(ActivityMain.this);
        builder.setMessage(errorMsg)
       .setTitle("Error")
       .setNeutralButton("OK", new DialogInterface.OnClickListener() {
           public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();                                                    
           }
        }).create().show();

    }

                            } catch (Exception e) {
                                    e.printStackTrace();
                                    return false;
                            }

I do not know the exact line of the NPE raised, but the problem is probably related to this line:

new AlertDialog.Builder(null);

You cant pass null here. You should put an instance of android.content.Context here (your Activity for example which started this task).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM