POST与JSON处理和快速Android网络
问题描述:
我发送一些数据与服务器需要检查的文章。 它返回一个JSON对象是这样的:POST与JSON处理和快速Android网络
{"login":"true","error":"false"}
我要检查的"login"
值。 这是我关于这个任务的代码:
btnLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String email = inputEmail.getText().toString();
String passw = inputPassword.getText().toString();
pDialog.setMessage("Caricamento ...");
showDialog();
AndroidNetworking.post(AppConfig.URL_LOGIN)
.addHeaders("Content-Type", "application/json")
.addHeaders("Authorization", "Token token=cazzodigomma")
.addHeaders("Accept", "application/json")
.addBodyParameter("email", email)
.addBodyParameter("password", passw)
.setPriority(Priority.MEDIUM)
.build()
.getAsJSONObject(new JSONObjectRequestListener() {
@Override
public void onResponse(JSONObject response) {
hideDialog();
//Toast.makeText(getApplicationContext(),
//"Va tutto bene :D", Toast.LENGTH_SHORT).show();
Log.d(TAG, "JSON: " + response);
JSONObject jsobj = new JSONObject();
try {
String login_json = jsobj.getString("login");
} catch (JSONException e) {
e.printStackTrace();
}
if ("true".equals(login_json)) {
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
}
@Override
public void onError(ANError error) {
// handle error
hideDialog();
Toast.makeText(getApplicationContext(),
"ERROR", Toast.LENGTH_SHORT).show();
}
}
);
}
我想这个问题是:
try {
String login_json = jsobj.getString("login");
} catch (JSONException e) {
e.printStackTrace();
}
有了问题,我的意思是:
如果
login_json
里面try { }
我米无法使用它在我的IF如果
login_json
不在try { }
Android Studio给我一个Unandled异常错误。
答
这是非常简单的。我所要做的就是运动:
if ("true".equals(login_json)) {
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
内try { }
@Override
public void onResponse(JSONObject response) {
hideDialog();
//Toast.makeText(getApplicationContext(),
//"Va tutto bene :D", Toast.LENGTH_SHORT).show();
Log.d(TAG, "JSON: " + response);
JSONObject jsobj = new JSONObject();
try {
String login_json = response.getString("login");
if ("true".equals(login_json)) {
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
但是绞纱您的answears和评论!
答
你需要得到响应JSON对象的字符串,所以更改
String login_json = jsobj.getString("login");
到
String login_json = response.getString("login");
如果您告诉我们问题是什么,这将有所帮助。它看起来像是声明'String login_json'在与'onResponse'不同的范围内,所以你不能在try-catch之外访问它。为了解决这个问题,你可以在try catch之外声明'login_json',并在try-catch中设置它的值。 – nbokmans
正确缩进你的代码 –
如果我把login_json放在try catch外面Android Studio给了我Unandled异常错误,那就是为什么我把它放在了它的位置。 @nbokmans –