我是一名新程序员,我正在制作一个应用程序,它可以将数据从 MYSQL 获取到 php,然后在 android 上显示。我一直在努力寻找解决方案,但到目前为止我所看到的教程似乎都不适合我,我只设法将 json 中的一个对象放入单个 textview 中。但我真正需要的是让数据显示在列表视图的各个行上。
这是我的 JSON 输出,
[{"id":"1","name":"darrel","password":"pass1234"},{"id":"2","name":"garrett","password":"important"},{"id":"3","name":"neoys","password":"yseniopass"},{"id":"4","name":"john","password":"mikel123"},{"id":"5","name":"owen","password":"mike4l"}]
和我的 java 代码,它只让一个用户显示在 textview 上。
package com.darre.jsonreader;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.ListActivity;
import android.os.Build;
import android.os.Bundle;
import android.os.StrictMode;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
@TargetApi(Build.VERSION_CODES.GINGERBREAD)
public class Users extends ListActivity {
/** Called when the activity is first created. */
@TargetApi(Build.VERSION_CODES.GINGERBREAD)
@SuppressLint("NewApi")
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//listView.setOnItemClickListener(new OnItemClickListener() {
// public void onItemClick(AdapterView<?> parent, View view,
// int position, long id) {
// When clicked, show a toast with the TextView text
// Toast.makeText(getApplicationContext(),
// ((TextView) view).getText(), Toast.LENGTH_SHORT).show();
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://172.30.54.153/databases/");
TextView textView = (TextView)findViewById(R.id.textView1);
ListView listview = (ListView)findViewById(R.id.listView1);
try {
HttpResponse response = httpclient.execute(httppost);
String jsonResult = inputStreamToString(response.getEntity().getContent()).toString();
JSONArray mArray = new JSONArray(jsonResult);
for (int i = 0; i < mArray.length(); i++) {
JSONObject object = mArray.getJSONObject(i);
String name = object.getString("name");
String password = object.getString("password");
textView.setText(name + " - " + password);
}
}
catch (JSONException e) {
e.printStackTrace();
}
catch (ClientProtocolException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
}
提前致谢!!!