我已经开始进行 Android 开发,因此我正在从数据库请求 JSON 格式的数据,并且我得到了类似“{”users”:[{“child_name”:“John”}]}”的返回值,这是我用来显示响应的代码:
公开课欢迎 Activity 延伸至 Activity {
private static final String URL = "http://www.schools.weavearound.com/android_api/user_fetch.php";
private StringRequest request;
private RequestQueue requestQueue;
private Button log_out;
@Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.welcome_activity);
// email = (EditText) findViewById(R.id.email);
final String strJson="";
final TextView testTextView = (TextView) findViewById(R.id.display);
requestQueue = Volley.newRequestQueue(this);
final TextView nameView = (TextView) findViewById(R.id.result_txt);
nameView.setText(getIntent().getExtras().getString("username"));
// fetch the db here
request = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
//Log.e("tag", e.getMessage());
String data = "";
try {
JSONObject jsonObject = new JSONObject(response);
//Get the instance of JSONArray that contains JSONObjects
JSONArray jsonArray = jsonObject.optJSONArray("users");
//Iterate the jsonArray and print the info of JSONObjects
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject1 = jsonArray.getJSONObject(i);
String name = jsonObject1.optString("child_name").toString();
data += "Node" + i + " : name= " + name +" \n ";
}
testTextView.setText(data);
} catch (JSONException e) {
e.printStackTrace();
}
}
},new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
});
}
}
但 Activity 中没有显示任何值。请帮助我。
最佳答案
将请求
创建后添加到requestQueue
中,如下所示:
requestQueue.add(request);
关于java - 我想在 android Activity 中显示 json 对象的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35926121/