This code starts a new thread for login and reacts according to the JSON result returned by the server.
I think this code has too many conditionals, exception handlers, and nested functions.
public void Login() {
mButton.setClickable(false);
mButton.setText("Loading...");
final String username = mUserName.getText().toString().trim();
final String password = mPassWord.getText().toString().trim();
new Thread() {
public void run() {
final String result = NetUtil.loginByGet(username, password);
if (result != null) {
try {
JSONTokener jsonTokener = new JSONTokener(result);
JSONObject jsonObject = (JSONObject) jsonTokener.nextValue();
final String message = jsonObject.getString("message");
if (jsonObject.getInt("error") == 0) {
String token = jsonObject.getString("token");
boolean isSaveSuccess = InfoUtil.saveUserInfo(LoginActivity.this,token);
if (isSaveSuccess) {
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(LoginActivity.this, "登录成功", Toast.LENGTH_SHORT).show();
initIntent(MainActivity.class);
finish();
}
});
}else {
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(LoginActivity.this, "保存登录信息失败", Toast.LENGTH_SHORT).show();
mButton.setClickable(true);
mButton.setText("登录");
}
});
}
} else if(jsonObject.getInt("error") == 1) {
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(LoginActivity.this, "" + message,
Toast.LENGTH_SHORT).show();
mButton.setClickable(true);
mButton.setText("登录");
}
});
}
}catch (Exception e) {
e.printStackTrace();
}
} else {
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(LoginActivity.this, "请求失败", Toast.LENGTH_SHORT).show();
mButton.setClickable(true);
mButton.setText("登录");
}
});
}
}
}.start();
}
displayToast
) for those repetitiverunOnUiThread
parts? \$\endgroup\$runOnUiThread
But I don't know how to go by passing a parameter to distinguish between thoseToast
\$\endgroup\$