只有创建视图层次结构的原始线程才能在asynctask中触及其视图错误



我使用的是View.OnClickListener。代码如下:

@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.appCompatButtonLogin:
AsyncTaskRunner runner = new AsyncTaskRunner();
runner.execute();
break;
case R.id.textViewLinkRegister:
// Navigate to RegisterActivity
Intent intentRegister = new Intent(getApplicationContext(), RegisterActivity.class);
startActivity(intentRegister);
break;
}
}  

我的AsyncTask类是这样的:

private class AsyncTaskRunner extends AsyncTask<String, String, String> {
ProgressDialog progressDialog = new ProgressDialog(LoginActivity.this);
@Override
protected void onPreExecute() {
if (progressDialog == null) {
progressDialog.setIndeterminate(false);
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.setCancelable(false);
progressDialog.setMessage("Please wait!");
progressDialog.show();
}
super.onPreExecute();
}
@Override
protected String doInBackground(String... strings) {
try {
verifyFromSQLite();
}
catch (Exception e) {
e.printStackTrace();
}
return null;
}
private void verifyFromSQLite() {
if (inputValidation.isInputEditTextFilled(textInputEditTextEmail, textInputLayoutEmail, getString(R.string.error_message_email))) {
return;
}
if (inputValidation.isInputEditTextEmail(textInputEditTextEmail, textInputLayoutEmail, getString(R.string.error_message_email))) {
return;
}
if (inputValidation.isInputEditTextFilled(textInputEditTextPassword, textInputLayoutPassword, getString(R.string.error_message_email))) {
return;
}
if (databaseHelper.checkUser(textInputEditTextEmail.getText().toString().trim()
, textInputEditTextPassword.getText().toString().trim())) {

Intent accountsIntent = new Intent(activity, UsersListActivity.class);
accountsIntent.putExtra("EMAIL", textInputEditTextEmail.getText().toString().trim());
emptyInputEditText();
startActivity(accountsIntent);

} else {
Toast.makeText(LoginActivity.this, "Please check your credentials", Toast.LENGTH_SHORT).show();
}
}
private void emptyInputEditText() {
textInputEditTextEmail.setText(null);
textInputEditTextPassword.setText(null);
}
@Override
protected void onPostExecute(String s) {
if (progressDialog.isShowing()) {
progressDialog.dismiss();
}
}
}  

当我运行代码时,我得到一个exception,如下所示:

只有创建视图层次结构的原始线程才能接触其视图

我试图在asynctask中将UI与非UI部分分离,如何解决此问题?

您不能在后台任务中更改UI
移动此代码:

Intent accountsIntent = new Intent(activity, UsersListActivity.class);
accountsIntent.putExtra("EMAIL", textInputEditTextEmail.getText().toString().trim());
emptyInputEditText();
startActivity(accountsIntent);

Toast.makeText(LoginActivity.this, "Please check your credentials", Toast.LENGTH_SHORT).show();

至CCD_ 4
您可以在doInBackground()中为这些情况设置boolean标志的值,并在onPostExecute()中进行检查并采取相应行动。

相关内容

  • 没有找到相关文章

最新更新