简体   繁体   中英

My AsyncTask in another class is causing NullPointerException when it is called in this class

I am quite new to android development and I am facing a NullPointerException when I am trying to call an AsyncTask which is an inner class in another class.

I believe it is the way I am instantiating it but this is what I have:

 // This onClick is in my adapter class - which is a separate Java File and class
 @Override
        public void onClick(View v) {
            UploadRes uploadRes = new UploadRes();
            UploadRes.UploadResConfirm uploadResConfirm = uploadRes.new UploadResConfirm(v.getContext());
            uploadResConfirm.execute(fileName, filePath);
        }

public class UploadResConfirm extends AsyncTask<String, String, String> {
    Dialog dialog;
    Context context;

    public UploadResConfirm(Context context){
        this.context = context;
    }

    @Override
    protected void onPreExecute(){
        dialog = new Dialog(UploadRes.this);
        dialog.setTitle("Currently uploading");
        dialog.show();
    }

I believe it has got something to do with the dialog box itself being instantiated in the AsyncTask class.

The error stack trace on Logcat - its the Dialog , I think its in the wrong place...

   java.lang.NullPointerException
            at codeman.androapp.UploadRes$UploadResConfirm.onPreExecute(UploadRes.java:246)
            at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586)
            at android.os.AsyncTask.execute(AsyncTask.java:534)
            at android.view.View.performClick(View.java:4240)
            at android.view.View$PerformClick.run(View.java:17721)
            at android.os.Handler.handleCallback(Handler.java:730)
            at android.os.Handler.dispatchMessage(Handler.java:92)
            at android.os.Looper.loop(Looper.java:137)
            at android.app.ActivityThread.main(ActivityThread.java:5103)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:525)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
            at dalvik.system.NativeStart.main(Native Method)

Some help if any would be much obliged.

Instead of dialog = new Dialog(UploadRes.this);

Try

dialog = new Dialog(context);

your are passing a wrong context to create dialog.

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