在listview android中显示所有数据json

时间:2016-06-12 13:24:49

标签: java php android json listview

我想用json从网站获取数据并在我的Android列表视图中显示它,但在我的程序中我只能在listview中看到json的第一个结果,并且没有向我展示listview中json的所有结果我不知道#39;知道如何检查arraylist的大小。

这是我的项目文件: android code => http://s7.picofile.com/file/8255498026/Travel.zip.html 和php和数据库=> enter link description here 要么 这是我的代码

主要活动代码:

package com.example.delta.travel;

import android.app.ListActivity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ListAdapter;
import android.widget.SimpleAdapter;
import android.widget.Toast;

import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class MainActivity extends ListActivity {

private ProgressDialog pd;
JSONParser jParser=new JSONParser();
ArrayList<HashMap<String,String>> P;
JSONArray s=null;
private final String url="http://192.168.1.3/upload/travel.php";

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
P = new ArrayList<>();
new travel().execute();

}

class travel extends AsyncTask<String,Void,String>{

@Override
protected void onPreExecute() {
    super.onPreExecute();
    pd=new ProgressDialog(MainActivity.this);
    pd.setMessage("login");
    pd.show();
}

@Override
protected String doInBackground(String... params) {

    List<NameValuePair> parms=new ArrayList<>();
    JSONObject json=jParser.makeHTTPRequest(url,"GET");

    try {
        int t=json.getInt("t");
        if(t==1){
            s=json.getJSONArray("travel");
            for(int i=0;i<s.length();i++){
                JSONObject c=s.getJSONObject(i);
                String companyname=c.getString("companyname");
                String cod=c.getString("cod");
                String bign=c.getString("bign");
                String stop=c.getString("stop");
                String date=c.getString("date");
                String time=c.getString("time");
                String price=c.getString("price");

                HashMap<String,String>map=new HashMap<String,String>();
                map.put("companyname",companyname);
                map.put("cod",cod);
                map.put("bign",bign);
                map.put("stop",stop);
                map.put("date",date);
                map.put("time",time);
                map.put("price",price);

                P.add(map);

            }
        }else {
            Toast.makeText(MainActivity.this,"No Data Found",Toast.LENGTH_SHORT).show();
        }


    } catch (JSONException e) {
        e.printStackTrace();
    }

    return null;
}

@Override
protected void onPostExecute(String s) {
    super.onPostExecute(s);
    pd.dismiss();
    runOnUiThread(new Runnable() {
        @Override
        public void run() {
            ListAdapter adapter = new SimpleAdapter(MainActivity.this, P, R.layout.item_list,
                    new String[]{"companyname", "cod", "bign", "stop", "date", "time", "price"},
                    new int[]{R.id.companyname, R.id.cod, R.id.bign, R.id.stop, R.id.date, R.id.time1, R.id.price});
            setListAdapter(adapter);
        }
    });

}
}
}

和我的json解析器代码:

package com.example.delta.travel;

import android.net.http.HttpResponseCache;
import android.util.Log;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.util.Date;
import java.util.List;

/**
 * Created by delta on 5/28/2016.
 */
public class JSONParser {

static InputStream is=null;
static JSONObject jObj=null;
static String json="";

// constructor
public JSONParser(){

}

// function get json from url
// by making HTTP POST or GET method
public JSONObject makeHTTPRequest(String urlString, String method) {

if(method.equals("POST")){

    URL url = null;
    try {
        url = new URL(urlString);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Accept", "application/json");

        BufferedReader br = new BufferedReader(new InputStreamReader(
                (conn.getInputStream())));
        String output;
        StringBuilder sb = new StringBuilder();
        while ((output = br.readLine()) != null) {
            sb.append(output);
        }
        conn.disconnect();
        json = sb.toString();

    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (ProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

}else if(method.equals("GET")){
    URL url = null;
    try {
        url = new URL(urlString);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setRequestProperty("Accept", "application/json");

        BufferedReader br = new BufferedReader(new InputStreamReader(
                (conn.getInputStream())));
        String output;
        StringBuilder sb = new StringBuilder();
        while ((output = br.readLine()) != null) {
            sb.append(output);
        }
        conn.disconnect();
        json = sb.toString();

    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (ProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

try {
    jObj = new JSONObject(json);
} catch (JSONException e) {
    e.printStackTrace();
}

return jObj;
}
}

和我的PHP代码:

<?php

$con=mysqli_connect("localhost","root","","travels");
mysqli_set_charset($con,"utf8");
$response=array();


$result=mysqli_query($con,"select * from travel");

if(mysqli_num_rows($result)>0){
while($row=mysqli_fetch_array($result)){
$temp=array();
$temp["companyname"]=$row["companyname"];
$temp["cod"]=$row["cod"];
$temp["bign"]=$row["bign"];
$temp["stop"]=$row["stop"];
$temp["date"]=$row["date"];
$temp["time"]=$row["time"];
$temp["price"]=$row["price"];

$response["travel"]=array();

array_push($response["travel"],$temp);
$response["t"]=1;
echo json_encode($response);

}



}
else{

$response["t"]=0;
$response["message"]="Not Found";
echo json_encode($response);

}
?>

1 个答案:

答案 0 :(得分:0)

在您的PHP代码中,您已将&#34; echo json_encode($ response);&#34; while循环中的语句,使其在每次迭代时打印。它应该在跟随括号之后在循环之外。