我正在使用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部分分开,该如何解决?
答案 0 :(得分:2)
您不能在后台任务中更改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();
到onPostExecute()
。
您可以在boolean
中将这些情况的值设置为doInBackground()
标志,并在onPostExecute()
中检查它们并采取相应的措施。