json看起来像这样:
[{"id":"1","name":"Mihai","email":"mihai@yahoo.com","password":"1234","phone":"765889345"},{"id":"2","name":"Robin","email":"robin@yahoo.com","password":"1234","phone":"765453434"}]
代码
// Json
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.detectAll()
.penaltyLog()
.penaltyDialog()
.build());
StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().detectAll()
.penaltyLog()
.build());
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.detectDiskReads()
.detectDiskWrites()
.detectNetwork() // or .detectAll() for all detectable problems
.penaltyLog()
.build());
StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
.detectLeakedSqlLiteObjects()
.penaltyLog()
.penaltyDeath()
.build());
TextView uid = (TextView) findViewById(R.id.titlu_anunt1);
TextView name1 = (TextView) findViewById(R.id.descriere_anunt1);
TextView email1 = (TextView) findViewById(R.id.telefon_anunt1);
JSONObject json = null;
String str = "";
HttpResponse response;
HttpClient myClient = new DefaultHttpClient();
HttpPost myConnection = new HttpPost("http://appz.esy.es/get_user.php");
try {
response = myClient.execute(myConnection);
str = EntityUtils.toString(response.getEntity(), "UTF-8");
}
catch (ClientProtocolException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
try {
JSONArray jArray = new JSONArray(str);
json = jArray.getJSONObject(0);
uid.setText(json.getString("id"));
name1.setText(json.getString("name"));
email1.setText(json.getString("email"));
}
catch (JSONException e) {
e.printStackTrace();
}
如何将所有对象添加到文本视图中?现在我只能在第一个textview中显示json中的一个对象,我想增加id。我想在textview中显示id1信息:名称,位置和其他内容1.之后我想在id2中显示名称和位置到textviews 2。
答案 0 :(得分:0)
您可以使用排球库,它易于使用,您可以专注于您的应用,而不是如何获取数据。您可以在this tutorial之后将库添加到项目中,或者如果您使用的是AndroidStudio,则可以将其添加到您的gradle as seen here。
要发出请求,您只需要添加:
//I think a StringRequest is more convenient in your case cause you can
//make a new JSONArray straight from the String
StringRequest request = new StringRequest(url, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
//Here is where you process your data, you could call a method to parse your data
parseData(response);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
//Here is where you handle the errors
}
});
RequestQueue queue = Volley.newRequestQueue(Here_goes_a_Context_object);
//This will send the request
queue.add(request);
public void parseData(String response) {
try {
//Your JSONArray doesn't have a name so you can't find it with the USER_TAG
//You need to make your JSONObject a String and then make a new JSONArray with that String
user = new JSONArray(response);
//The rest of the code looks good to me
...
}
}