当用户无法登录其帐户时,我正在尝试执行警报。也就是说,当我试图用下面的代码实现这一点时,我会抛出以下错误:
原因:java.lang.RuntimeException:无法在内部创建处理程序尚未调用的thread线程[AncTask#1,5,main]Looper.prepare((
如何修复此问题?请参阅下面的代码。
登录活动
private class MyNetwork extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... voids) {
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("username", "admin");
jsonObject.put("password", "test#5Q");
} catch (JSONException e) {
e.printStackTrace();
}
OkHttpClient client = new OkHttpClient();
MediaType JSON = MediaType.parse("application/json; charset=utf-8");
// put your json here
RequestBody body = RequestBody.create(JSON, jsonObject.toString());
Request request = new Request.Builder()
.url("http://myurl.com/wp-json/wp/v2/custom-plugin/login")
.post(body)
.build();
Response response = null;
try {
response = client.newCall(request).execute();
String resStr = response.body().string();
Log.i("The response is", String.valueOf(response));
int responseCode = response.code();
Log.i("Check response code", String.valueOf(responseCode));
if (responseCode == 200) {
Log.i("We're logged in!", String.valueOf(responseCode));
Intent i = new Intent(LoginActivity.this, DashboardActivity.class);
startActivity(i);
}
if (responseCode == 500) {
Log.i("User or pass incorrect.", String.valueOf(responseCode));
AlertDialog alertDialog = new AlertDialog.Builder(LoginActivity.this).create();
alertDialog.setTitle("Oops!");
alertDialog.setMessage("Your username or password is incorrect. Please check your credentials and try again.");
alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getApplicationContext(), "You clicked on OK", Toast.LENGTH_SHORT).show();
}
});
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
public void launchDashboard (View v) {
new MyNetwork().execute();
}
我通过将AlertDialog包装在中修复了上述错误
runOnUiThread(new Runnable() {
public void run() {
}