【发布时间】:2016-10-08 10:33:16
【问题描述】:
我正在尝试为我的 Android 应用创建响应侦听器。
我正在尝试从我的 php 代码中获得响应,如下所示:
Response.Listener<String> responseListener = new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try {
Log.i("tagconvertstr", "["+response+"]");
JSONObject jsonResponse = new JSONObject(response);
JSONArray success = jsonResponse.getJSONArray("success");
JSONArray success2 = jsonResponse.getJSONArray("no");
if (success.toString() == "{"success"}") {
Intent intent = new Intent(EnglishRegisterSite.this, UK.class);
EnglishRegisterSite.this.startActivity(intent);
} else if (success2.toString() == "{"no"}") {
AlertDialog.Builder builder = new AlertDialog.Builder(EnglishRegisterSite.this);
builder.setMessage("You are not 18 years old! kid!")
.setNegativeButton("Retry", null)
.create()
.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
PHP 响应如下所示:
$response = array();
$response["no"];
echo json_encode($response);
如果我将 php 数组更改为 $response["no"] = true; 并创建一个布尔值,那么我可以让它像这样工作:
boolean success2 = jsonResponse.getboolean("no");
但这不行,因为那样我只能有两种情况。要么失败,要么成功。但是我想要实现的是创建更多的场景来说明它是否失败然后指定它失败的原因。就像在这个例子中一样。如果用户正在尝试注册并且尚未满 18 岁,则会弹出一条消息,说明这是问题所在。
因此,我需要从 PHP 向 Java 发送某种 JSON 编码的消息,我可以在 Java 中检查这些消息。
有谁知道我如何做到这一点?
【问题讨论】:
标签: java php android json response