【问题标题】:Read Data Using ListView Android JSON使用 ListView Android JSON 读取数据
【发布时间】:2016-04-11 13:06:18
【问题描述】:

我正在尝试使用 android 上的列表视图显示数据库中表中的所有内容。我尝试了许多不同的方法,但似乎没有任何效果,屏幕只是空白。我不知道错误是在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...";



?>?

【问题讨论】:

  • 删除所有的 echo 语句,只在 PHP 文件中保留最后一个带有 echo json_encode ... 的语句。此外,始终在 catch 块中打印堆栈跟踪以查看异常。您可以从中了解更多关于错误的信息。

标签: php android json listview


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-04-14
    • 2023-03-21
    • 1970-01-01
    • 1970-01-01
    • 2011-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多