When I try to show a working dialog for an asynctask i get the following errors: java.lang.reflect.InvocationTargetException java.lang.NullPointerException
The code of the activity and asynctask is:
public class MainActivity extends Activity {
private ControlLogin ctlLogin;
private ProgressDialog dialog;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
ctlLogin = (ControlLogin)findViewById(R.id.controlLogin);
ctlLogin.setOnLoginListener(new OnLoginListener()
{
@Override
public void onLogin(String email, String password, Boolean saveAccount){
ProgressDialog dialog = new ProgressDialog(getApplicationContext());
dialog.setMessage("Signing...");
dialog.setIndeterminate(true);
dialog.setCancelable(false);
new Login().execute(email, password);
}
});
}
public class Login extends AsyncTask<String, Float, CloudApp> {
protected void onPreExecute(){
dialog.show();
}
@Override
protected CloudApp doInBackground(String... arg0) {
CloudApp api = new CloudAppImpl(arg0[0], arg0[1]);
return api;
}
protected void onPostExecute(CloudApp api){
dialog.dismiss();
try {
CloudAppAccount acc = api.getAccountDetails();
Toast toast = Toast.makeText(getBaseContext(), "test: " + acc.getEmail(), Toast.LENGTH_LONG);
toast.show();
} catch (CloudAppException e) {
e.printStackTrace();
}
}
}
}
Any help??? Thanks!!
You are hiding your member dialog
in your code by defining a local variable dialog
in your onLogin(...)
method. Because of this, dialog
is never initialized to anything and that is why you get an NPE in your Login
class.
@Override
public void onLogin(String email, String password, Boolean saveAccount){
//remove the leading ProgessDialog here...it is hiding your member 'dialog'
//dialog = new ProgressDialog(getApplicationContext());
ProgressDialog dialog = new ProgressDialog(getApplicationContext());
dialog.setMessage("Signing...");
dialog.setIndeterminate(true);
dialog.setCancelable(false);
new Login().execute(email, password);
}
Are you sure your dialog exist when you dismiss it? I think in the onLogin you recreate a new dialog variable with the same name as your activity field variable.
protected void onPostExecute(CloudApp api) {
dialog.dismiss(); // this one is not initialized
try {
CloudAppAccount acc = api.getAccountDetails();
You might play safe:
if (dialog != null) dialog.dismiss();
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.