Android:抛出 IllegalStateException
Android: IllegalStateException thrown
在 LoginActivity.java class 中,当用户单击注册按钮时,代码会将登录会话设置为 true,然后将 activity 从 LoginActivity 切换到 MainActivity。这是登录代码片段。
case(R.id.login):
String email = etEmail.getText().toString();
String password = etPassword.getText().toString();
if(email.trim().length() > 0 && password.trim().length() > 0) {
loginManager.checkLogin(email, password);
pDialog.setMessage("Logging in..");
showDialog();
session.setLogin(true);
if(loginManager.isLoginSuccessful()) {
hideDialog();
Toast.makeText(this, getResources().getString(R.string.welcome_msg), Toast.LENGTH_LONG).show();
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
finish();
} else {
Toast.makeText(this, loginManager.getErrorMessage(), Toast.LENGTH_LONG).show();
}
} else if(email.trim().length() < 1) {
Toast.makeText(this, "Please enter the email", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Please enter the password", Toast.LENGTH_SHORT).show();
}
break;
这是处理登录过程的 LoginManager.java 文件。我使用 OkHttp 作为 HTTP 库。
public class LoginManager {
private final String TAG_LOGIN = LoginManager.class.getSimpleName();
private OkHttpClient client = new OkHttpClient();
private final String loginURL = URL.getInstance().getUrlLogin();
private Request request = new Request.Builder().url(loginURL).build();
private static JSONObject jsonObject;
private boolean error;
public void checkLogin(final String email, final String password) {
client.newCall(request).enqueue(new Callback() {
// onFailure is called when the request could not be executed due to cancellation, a connectivity problem or timeout.
@Override
public void onFailure(Request request, IOException e) {
}
// onResponse is called when the HTTP response was successfully returned by the remote server.
// using POST request for login
@Override
public void onResponse(Response response) throws IOException {
Log.d(TAG_LOGIN, "Login response: " + response.body().string());
RequestBody body = new FormEncodingBuilder()
.add("tag", "login")
.add("email", email)
.add("password", password)
.build();
Request request = new Request.Builder().url(loginURL).post(body).build();
client.newCall(request).execute();
try {
jsonObject = new JSONObject(response.body().string());
error = jsonObject.getBoolean("error");
} catch(JSONException e) {
e.printStackTrace();
}
}
});
}
public boolean isLoginSuccessful() {
if(error) {
return false;
}
return true;
}
public String getErrorMessage() {
String errorMessage = null;
try {
jsonObject.getString("error_msg");
} catch(JSONException e) {
e.printStackTrace();
}
return errorMessage;
}
}
当我 运行 应用程序时,它显示欢迎消息并突然退出并显示以下错误日志。
java.lang.IllegalStateException: closed
at com.squareup.okhttp.internal.http.HttpConnection$FixedLengthSource.read(HttpConnection.java:454)
at okio.Buffer.writeAll(Buffer.java:574)
at okio.RealBufferedSource.readByteArray(RealBufferedSource.java:87)
at com.squareup.okhttp.ResponseBody.bytes(ResponseBody.java:56)
at com.squareup.okhttp.ResponseBody.string(ResponseBody.java:82)
at com.marshall.thequizshow.application.http.LoginManager.onResponse(LoginManager.java:51)
at com.squareup.okhttp.Call$AsyncCall.execute(Call.java:150)
at com.squareup.okhttp.internal.NamedRunnable.run(NamedRunnable.java:33)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:841)
所以,我一定是在 LoginManager.java 文件中 onResponse 方法下的 try-catch 短语存在错误。
try {
jsonObject = new JSONObject(response.body().string());
error = jsonObject.getBoolean("error");
} catch(JSONException e) {
e.printStackTrace();
}
我想问你我应该如何修复代码,使其不再捕获 IllegalStateException。
提前致谢。
作为一般答案,是:避免 RuntimeException 的正确方法是修复代码:在正常情况下,它们不应被程序捕获。
现在,让我们看看您的情况... IllegalStateException
的出现是因为 HttpConnection 在尝试使用它时似乎已关闭。难道是因为你调用了两次方法 response.body()
?
在错误的时间调用方法时抛出IllegalState 异常。检查流程的性质,然后重组代码以在适当的时间进行调用
在 LoginActivity.java class 中,当用户单击注册按钮时,代码会将登录会话设置为 true,然后将 activity 从 LoginActivity 切换到 MainActivity。这是登录代码片段。
case(R.id.login):
String email = etEmail.getText().toString();
String password = etPassword.getText().toString();
if(email.trim().length() > 0 && password.trim().length() > 0) {
loginManager.checkLogin(email, password);
pDialog.setMessage("Logging in..");
showDialog();
session.setLogin(true);
if(loginManager.isLoginSuccessful()) {
hideDialog();
Toast.makeText(this, getResources().getString(R.string.welcome_msg), Toast.LENGTH_LONG).show();
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
finish();
} else {
Toast.makeText(this, loginManager.getErrorMessage(), Toast.LENGTH_LONG).show();
}
} else if(email.trim().length() < 1) {
Toast.makeText(this, "Please enter the email", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Please enter the password", Toast.LENGTH_SHORT).show();
}
break;
这是处理登录过程的 LoginManager.java 文件。我使用 OkHttp 作为 HTTP 库。
public class LoginManager {
private final String TAG_LOGIN = LoginManager.class.getSimpleName();
private OkHttpClient client = new OkHttpClient();
private final String loginURL = URL.getInstance().getUrlLogin();
private Request request = new Request.Builder().url(loginURL).build();
private static JSONObject jsonObject;
private boolean error;
public void checkLogin(final String email, final String password) {
client.newCall(request).enqueue(new Callback() {
// onFailure is called when the request could not be executed due to cancellation, a connectivity problem or timeout.
@Override
public void onFailure(Request request, IOException e) {
}
// onResponse is called when the HTTP response was successfully returned by the remote server.
// using POST request for login
@Override
public void onResponse(Response response) throws IOException {
Log.d(TAG_LOGIN, "Login response: " + response.body().string());
RequestBody body = new FormEncodingBuilder()
.add("tag", "login")
.add("email", email)
.add("password", password)
.build();
Request request = new Request.Builder().url(loginURL).post(body).build();
client.newCall(request).execute();
try {
jsonObject = new JSONObject(response.body().string());
error = jsonObject.getBoolean("error");
} catch(JSONException e) {
e.printStackTrace();
}
}
});
}
public boolean isLoginSuccessful() {
if(error) {
return false;
}
return true;
}
public String getErrorMessage() {
String errorMessage = null;
try {
jsonObject.getString("error_msg");
} catch(JSONException e) {
e.printStackTrace();
}
return errorMessage;
}
}
当我 运行 应用程序时,它显示欢迎消息并突然退出并显示以下错误日志。
java.lang.IllegalStateException: closed
at com.squareup.okhttp.internal.http.HttpConnection$FixedLengthSource.read(HttpConnection.java:454)
at okio.Buffer.writeAll(Buffer.java:574)
at okio.RealBufferedSource.readByteArray(RealBufferedSource.java:87)
at com.squareup.okhttp.ResponseBody.bytes(ResponseBody.java:56)
at com.squareup.okhttp.ResponseBody.string(ResponseBody.java:82)
at com.marshall.thequizshow.application.http.LoginManager.onResponse(LoginManager.java:51)
at com.squareup.okhttp.Call$AsyncCall.execute(Call.java:150)
at com.squareup.okhttp.internal.NamedRunnable.run(NamedRunnable.java:33)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:841)
所以,我一定是在 LoginManager.java 文件中 onResponse 方法下的 try-catch 短语存在错误。
try {
jsonObject = new JSONObject(response.body().string());
error = jsonObject.getBoolean("error");
} catch(JSONException e) {
e.printStackTrace();
}
我想问你我应该如何修复代码,使其不再捕获 IllegalStateException。
提前致谢。
作为一般答案,是:避免 RuntimeException 的正确方法是修复代码:在正常情况下,它们不应被程序捕获。
现在,让我们看看您的情况... IllegalStateException
的出现是因为 HttpConnection 在尝试使用它时似乎已关闭。难道是因为你调用了两次方法 response.body()
?
在错误的时间调用方法时抛出IllegalState 异常。检查流程的性质,然后重组代码以在适当的时间进行调用