0

I have an AsyncTask class in my Android app. My MainActivity calls a method in that class, but when I do, it has an issue with the ProgressDialog box in it.

This is the error I am getting:

java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources$Theme android.content.Context.getTheme()' on a null object reference
at android.app.AlertDialog.resolveDialogTheme(AlertDialog.java:222)
at android.app.AlertDialog.<init>(AlertDialog.java:200)
at android.app.AlertDialog.<init>(AlertDialog.java:196)
at android.app.AlertDialog.<init>(AlertDialog.java:141)
at android.app.ProgressDialog.<init>(ProgressDialog.java:77)
at com.example.maindec.sme.LoginSoapTask.<init>(LoginSoapTask.java:30)
at com.example.maindec.sme.MainActivity$3.onClick(MainActivity.java:103)
at android.view.View.performClick(View.java:5198)
at android.view.View$PerformClick.run(View.java:21147)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

Here is the main parts of the code in both classes:

MainActivity.java

public class MainActivity extends AppCompatActivity {

    private String username;
    private String password;

    private EditText usernameField;
    private EditText passwordField;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        usernameField = (EditText) findViewById(R.id.enterUsername);
        passwordField = (EditText) findViewById(R.id.enterPassword);

        passwordField.setTypeface(Typeface.DEFAULT);
        passwordField.setTransformationMethod(new PasswordTransformationMethod());


        loginButton.setOnClickListener(new OnClickListener() {

                public void onClick(View v) {

                    LoginSoapTask lert = new LoginSoapTask(getApplicationContext()); //THIS IS WHERE I'M HAVING THE PROBLEM (Line 103)
                   // lert.checkDetails(usernameField.getText().toString(), passwordField.getText().toString());
                }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

LoginSoapTask.java

public class LoginSoapTask extends AsyncTask<Void, Void, Void> {
    /*Web Service Details */

    private String xmlProlog = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";

    public String username, password;

    Context context;
    public LoginSoapTask(Context c) {
        context = c;
    }
    private final ProgressDialog dialog = new ProgressDialog(context); //THIS IS WHERE I AM HAVING THE PROBLEM!!!!!!!!! (Line 30)
    protected void onPreExecute() {

        this.dialog.setMessage("Verifying...");
        dialog.show();
    }


    @Override
    protected Void doInBackground(Void... params) {
        return null;
    }

    protected void onPostExecute(Void result) {
        // TextView tv = (TextView) findViewById(R.id.Result);
        //  tv.setText(test_string);
        System.out.println(test_string);
        if (this.dialog.isShowing()){
            this.dialog.dismiss();
         }
    }

    private String test_string;

    @SuppressWarnings("deprecation")
    public void WebServiceCallExample() {
        String finalInput = "1:" + username.length() + ":" + username + ":2:" + password.length() + ":" + password + ":";
        SoapObject Request = new SoapObject(NAMESPACE, METHOD_NAME);
        Request.addProperty("credentials", finalInput);

        /* Set the web service envelope */
        SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
        envelope.dotNet = true;
        envelope.setOutputSoapObject(Request);
        System.out.println("Request::" + Request.toString());

        HttpTransportSE httpTransport = new HttpTransportSE(URL);
        try{
            System.out.println("Lghung:" + SOAP_ACTION);
            httpTransport.debug=true;

            httpTransport.call(SOAP_ACTION, envelope);
            String ss=httpTransport.responseDump;
            //SoapObject sp = (SoapObject) envelope.getResponse();
             SoapPrimitive response = (SoapPrimitive) envelope.getResponse();

            SoapObject resultsRequestSOAP = (SoapObject) envelope.bodyIn;
            System.out.println("Response::" + resultsRequestSOAP.toString());
            System.out.println(Request.getName());
             test_string = xmlProlog + response.toString();
             System.out.println(test_string);
        }catch (Exception e){
            System.out.println("Testing");
            e.printStackTrace();
        }

    }

    public void checkDetails(String givenUsername, String givenPassword) {
        username = givenUsername;
        password = givenPassword;
        execute();
    }
}

I have inserted quotes, saying "THIS IS WHERE I AM HAVING THE PROBLEM", to give you a bit of a head-start.

If you know how to solve this, PLEASE don't post links for other solutions. Post an answer with code that can directly solve this problem. I've looked at other solutions that have to do with the context, but I am getting nowhere.

Sreehari
  • 5,621
  • 2
  • 25
  • 59
Chosen1
  • 279
  • 4
  • 18
  • create your progress dialogue in onPreExcute() – Nouman Ghaffar Apr 12 '16 at 12:32
  • also change context = c to this.context=c ; – Nouman Ghaffar Apr 12 '16 at 12:33
  • @Chosen1 You shouldn't be using the Application `Context`, try `this` instead. – Bryan Apr 12 '16 at 12:35
  • 1
    @Chosen1 Also, I don't think you should be creating a dialog from an `AsyncTask` in the first place. UI should be handled on the main thread, you may want to switch to a [`DialogFragment`](http://developer.android.com/reference/android/support/v4/app/DialogFragment.html), and call your `AsyncTask` from that fragment. – Bryan Apr 12 '16 at 12:41

4 Answers4

2

in MainActivity

replace

LoginSoapTask lert = new LoginSoapTask(getApplicationContext()); 

with

LoginSoapTask lert = new LoginSoapTask(MainActivity.this); 
Vanraj Ghed
  • 1,261
  • 11
  • 23
1

Turns out that I make a public instance of a MainActivity and transfer it over to LoginSoapTask. Slightly different to how you guys set it up. I used it as a different public method.

Chosen1
  • 279
  • 4
  • 18
0

instead of

LoginSoapTask lert = new LoginSoapTask(getApplicationContext());

try this

LoginSoapTask lert = new LoginSoapTask(MainActivity.this);
Slobodan Antonijević
  • 2,533
  • 2
  • 17
  • 27
0

Change your constructor slightly to also create the dialog inside it.

Context context;
private final ProgressDialog dialog;

public LoginSoapTask(Context c) {
    context = c;
    dialog = new ProgressDialog(context);
}

Also, you might find it easier to use the view (v) param's context in your clickListener, here is an example:

loginButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        LoginSoapTask lert = new LoginSoapTask(v.getContext());
        // lert.checkDetails(usernameField.getText().toString(), passwordField.getText().toString());
    }
});
petey
  • 16,914
  • 6
  • 65
  • 97