`
byandby
  • 浏览: 1689086 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

android ProgressDialo异常 no dialog with id 0 was ever shown via Activity#showDialog

阅读更多
  公司的项目今天测试登录的时候出现一个问题。 验证用户名 还有密码 这个过程是通过 AsyncTask 异步完成的, 当用户登录的时候会弹出一个ProgressDialog 如下图:

图片加载中..........

大家可以看到屏幕中央有一个ProgressDialog 提示正在验证账户,验证的过程是通过一个异步任务来完成的,但是如果这时我不停的点击Back键--》一定要不停的点,就会抛出一个异常,异常见下图。



  这个异常的意思就是说没有一个 id为0的dialog 已经通过 showDialog()方法显示了。出现这个异常的原因是:当我们点击Back键的时候ProgressDialog 其实已经被结束了,它在当前的那个 Activity已经不存在了,然而后台的AsyncTask任务其实还在继续执行 。。然后我们又在onPostExecute() 方法取消显示这个Dialog,但是 这个时候 这个dialog已经没了啊,因为当我们点击Back键的时候 就会结束那个Dialog!! 找不到它了 所以抛出了这个异常。

   解决办法就是 设置那个Dialog的onCancel事件,并且在onCancel方法里边判断 如果那个AsyncTask任务对象不等于null ,就结束它,代码片段如下。
private AccountVerifyAsyncTask mAccountVerifyTask;


if(mAccountVerifyTask == null || mAccountVerifyTask.getStatus() == AsyncTask.Status.FINISHED || mAccountVerifyTask.isCancelled()){
			mAccountVerifyTask = (AccountVerifyAsyncTask) new AccountVerifyAsyncTask().execute(username,password);
		}


class AccountVerifyAsyncTask extends AsyncTask<String ,Integer, Integer>{
		
		@Override
	    protected void onPreExecute() {
			showDialog(VERIFY_DIALOG_KEY);
	    }


		@Override
		protected Integer doInBackground(String... params) {
			String username = params[0];
			String password = params[1];
			int result = AccountManager.instance().accountVerify(username, password);
			return result;
		}
		
		@Override
		protected void onPostExecute(Integer result) {
			dismissDialog(VERIFY_DIALOG_KEY);
			int code = result;
			AccountManager.instance().handleVerifyResult(code);
			if(AccountManager.SUCCESS == code){
				AccountManager.QUERY_CANCELED = false;
				onAccountChanged();
			}
		}
	}

  
switch(id){
		case VERIFY_DIALOG_KEY: {
			final ProgressDialog dialog = new ProgressDialog(this);
			dialog.setMessage(getResources().getString(R.string.account_verify_account));
			dialog.setIndeterminate(true);
			dialog.setCancelable(true);
			dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
				
				@Override
				public void onCancel(DialogInterface dialog) {
					if(mAccountVerifyTask != null){
						mAccountVerifyTask.cancel(true);
					}
				}
			});
			//mVerifyDialog = dialog;
			return dialog;
		}


  • 大小: 46.2 KB
  • 大小: 31.3 KB
分享到:
评论
1 楼 droid_dfh 2012-04-12  
这样判断不行吗,if(dialog != null && dialog.isShowing){
                    dialog.dismiss();
}

相关推荐

Global site tag (gtag.js) - Google Analytics