使用ListView Android JSON读取数据


Read Data Using ListView Android JSON

我正试图在android上使用listview显示数据库中表中的所有内容。我尝试了很多不同的方法,但似乎都不起作用,屏幕上一片空白。我不知道错误是在php文件中还是在android代码中。

package com.project.bsc.radianstores;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
public class AllComplaints extends Fragment{
    String myJSON;
    private static final String TAG_RESULTS="result";
    private static final String TAG_USERNAME = "Username";
    private static final String TAG_ITEMTYPE = "Complaint_Type";
    private static final String TAG_MESSAGE = "Message";
    private static final String TAG_Response = "Response";
    JSONArray peoples = null;
    ArrayList<HashMap<String, String>> personList;
    ListView list;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.d_complaints, container, false);
        list = (ListView) v.findViewById(R.id.listDComplaints);
        personList = new ArrayList<HashMap<String,String>>();
        getData();
        return v;
    }
    protected void showList(){
        try {
            JSONObject jsonObj = new JSONObject(myJSON);
            peoples = jsonObj.getJSONArray(TAG_RESULTS);
            for(int i=0;i<peoples.length();i++){
                JSONObject c = peoples.getJSONObject(i);
                String username = c.getString(TAG_USERNAME);
                String type = c.getString(TAG_ITEMTYPE);
                String content = c.getString(TAG_MESSAGE);
                String Response = c.getString(TAG_Response);
                HashMap<String,String> persons = new HashMap<String,String>();
                persons.put(TAG_USERNAME,username);
                persons.put(TAG_ITEMTYPE,type);
                persons.put(TAG_MESSAGE,content);
                persons.put(TAG_Response,Response);
                personList.add(persons);
            }
            ListAdapter adapter = new SimpleAdapter(
                    getActivity(), personList, R.layout.single_complaint, new String[]{TAG_USERNAME, TAG_ITEMTYPE, TAG_MESSAGE,
                    TAG_Response}, new int[]{R.id.PUsername, R.id.PItem, R.id.PMessage,
                    R.id.PResponse});
            list.setAdapter(adapter);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    public void getData(){
        class GetDataJSON extends AsyncTask<String, Void, String> {
            @Override
            protected String doInBackground(String... params) {
                DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
                HttpPost httppost = new HttpPost("http://192.168.1.102/webservice/d_complaints.php");
                // Depends on your web service
                httppost.setHeader("Content-type", "application/json");
                InputStream inputStream = null;
                String result = null;
                try {
                    HttpResponse response = httpclient.execute(httppost);
                    HttpEntity entity = response.getEntity();
                    inputStream = entity.getContent();
                    // json is UTF-8 by default
                    BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
                    StringBuilder sb = new StringBuilder();
                    String line = null;
                    while ((line = reader.readLine()) != null)
                    {
                        sb.append(line + "'n");
                    }
                    result = sb.toString();
                } catch (Exception e) {
                    // Oops
                }
                finally {
                    try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
                }
                return result;
            }
            @Override
            protected void onPostExecute(String result){
                myJSON=result;
                showList();
            }
        }
        GetDataJSON g = new GetDataJSON();
        g.execute();
    }
}
<?php
$host  = "localhost";
$user = "root";
$pass = "";
$db = "radian";
$con = mysqli_connect($host,$user,$pass,$db);
if(!$con)
{
 die("Error ".mysqli_connect_error());
 
}
else
{
 echo "<h3>connection success</h3>";
 
}
$sql = "select * from publiccomplaint;";
$res = mysqli_query($con,$sql);
$response = array();
while($row=mysqli_fetch_array($res))
{
 echo "<br>Username : ".$row[1];
 echo "<br>Complaint_Type : ".$row[2];
 echo "<br>Message : ".$row[3];
 echo "<br>Response : ".$row[4];
 
 array_push($response,array('Username'=>$row[1],'Complaint_Type'=>$row[2],'Message'=>$row[3],'Response'=>$row[4]));
}
echo json_encode(array('result'=>$response));
mysqli_close($con);
//echo "Hello world...";
?>?

自Lollipop以来,一些Http类已被弃用。因此,如果你不想使用Http类,一个好的替代解决方案是使用谷歌为请求创建的库:Volley库,它更容易发出请求。

你可以在网上找到这样的教程:http://code.tutsplus.com/tutorials/an-introduction-to-volley--cms-23800