当我尝试显示asynctask的工作对话框时,我收到以下错误: java.lang.reflect.InvocationTargetException 显示java.lang.NullPointerException
活动和asynctask的代码是:
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();
}
}
}
}
任何帮助???谢谢!
答案 0 :(得分:1)
您通过在dialog
方法中定义局部变量dialog
,将您的成员onLogin(...)
隐藏在代码中。因此,dialog
永远不会初始化为任何内容,这就是您在Login
课程中获得NPE的原因。
@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);
}
答案 1 :(得分:0)
当你解雇它时,你确定你的对话存在吗?我认为在onLogin中,您重新创建一个与活动字段变量同名的新对话框变量。
protected void onPostExecute(CloudApp api) {
dialog.dismiss(); // this one is not initialized
try {
CloudAppAccount acc = api.getAccountDetails();
你可以安全地玩:
if (dialog != null) dialog.dismiss();