从JSONEncode PHP获取价值并将其显示到listview中

时间:2015-07-20 06:11:03

标签: php android json

是否有任何实用且简单的教程可以从PHP获取值并将其存储到列表视图中?

所以这就是活动流程:

1. Input number in textview
2. Submit via button and send the value from textview into website
3. The website give the result in json_encode form.
4. Set the value from JSON into listview or multiline text maybe.

这是PHP代码:

$username = $_POST['username'];
$query_search1 = "SELECT `schedule`.`kode_schedule` ,`schedule`.`kode_matkul` ,`matakuliah`.`title` ,`schedule`.`ruang` ,`kelas`.`latitude` ,`kelas`.`longitude` ,`kelas`.`lantai` ,`schedule`.`hari`,`schedule`.`jam` FROM schedule LEFT JOIN `u466318196_track`.`matakuliah` ON `schedule`.`kode_matkul` = `matakuliah`.`kode_matkul` LEFT JOIN `u466318196_track`.`kelas` ON `schedule`.`ruang` = `kelas`.`ruang` WHERE(( kode_schedule = '".$username."'))";
$query_exec1 = mysqli_query($conn, $query_search1) or die(mysqli_error($conn));

while ($data2 = mysqli_fetch_assoc($query_exec1))
{
 $response['length'][] = $data2;
}

print json_encode($response);

这是PHP的结果:

{
"length":
[
  {
      "kode_schedule":"sch0001",
      "kode_matkul":"TIB01",
      "title":"Basis Data",
      "ruang":"501",
      "latitude":"-6.18861653446272",
      "longitude":"106.801122526546",
      "lantai":"5",
      "hari":"Selasa",
      "jam":"17:45:00"
  },          
  {
      "kode_schedule":"sch0001",
      "kode_matkul":"TIB02",
      "title":"Pemrograman Berorientasi Objek",
      "ruang":"LABB",
      "latitude":"-6.18864706134991",
      "longitude":"106.801161122636",
      "lantai":"5",
      "hari":"Selasa",
      "jam":"19:30:00"
   }
]
}

我还是关于android的新手。请给我一些完整的教程或代码。

最好的问候。

编辑:

我做了很多研究但仍然无法成功。所以这并不像我没有做任何事情。

这是我的代码:

public void login()
{
    try
    {
        httpClient=new DefaultHttpClient();
        httpPost= new HttpPost("http://studentstracking.hol.es/installation.php");
        nameValuePairs = new ArrayList<NameValuePair>(1);
        nameValuePairs.add(new BasicNameValuePair("username", txtNim.getText().toString().trim()));
        httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        response=httpClient.execute(httpPost);
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        final String response = httpClient.execute(httpPost, responseHandler);
        final JSONArray array = new JSONArray(response);
        String kode_matkul;
        String title;
        String ruang;
        String lantai;
        String hari;
        int jam;
        Double latitude,longitude;
        ListAdapter setListAdapter;
        listView = (ListView) findViewById(R.id.listView2);
        ArrayList items = new ArrayList<>();
        for(int i=0; i < array.length() ; i++) {
            JSONObject row = array.getJSONObject(i);
            kode_matkul = row.getString("kode_matkul");
            title = row.getString("title");
            ruang = row.getString("ruang");
            latitude = row.getDouble("latitude");
            longitude = row.getDouble("longitude");
            lantai = row.getString("lantai");
            hari = row.getString("hari");
            jam = row.getInt("jam");
            items.add(kode_matkul);
            items.add(title);
            items.add(ruang);
            items.add(latitude);
            items.add(longitude);
            items.add(lantai);
            items.add(hari);
            items.add(jam);
        }
        ArrayAdapter mArrayAdapter = new ArrayAdapter(this,R.layout.activity_installation,R.id.listView2);
        listView.setAdapter(mArrayAdapter);
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(Installation.this, "Welcome : " + array , Toast.LENGTH_LONG).show();
            }
        });

    }catch(Exception e){
        System.out.println("Exception : " + e.getMessage());
    }
}

1 个答案:

答案 0 :(得分:1)

你快到了。这里有一些提示,

步骤1:创建一个JSON解析器类来处理网络操作,

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 mehtod
    public JSONObject makeHttpRequest(String url, String method,
            List<NameValuePair> params) {

        // Making HTTP request
        try {

            // check for request method
            if(method == "POST"){
                // request method is POST
                // defaultHttpClient
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(url);
                httpPost.setEntity(new UrlEncodedFormEntity(params));

                HttpResponse httpResponse = httpClient.execute(httpPost);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();

            }       
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            json = sb.toString();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // return JSON String
        return jObj;

    }
}

第2步:从您的活动中使用AsyncTask调用PHP API,

    class GetLength extends AsyncTask<String, String, String> {

        protected String doInBackground(String... params) {

            try {
                // Building Parameters
                List<NameValuePair> params = new ArrayList<NameValuePair>();
                params.add(new BasicNameValuePair("username", txtNim.getText().toString()));
                JSONObject json = jsonParser.makeHttpRequest("http://studentstracking.hol.es/installation.php", "POST", params);
                JSONArray array = json.getJSONArray("length");
                for (int i = 0; i < array.length(); i++) {
                    JSONObject row = array.getJSONObject(i);
                    kode_matkul = row.getString("kode_matkul");
                    title = row.getString("title");
                    ruang = row.getString("ruang");
                    latitude = row.getDouble("latitude");
                    longitude = row.getDouble("longitude");
                    lantai = row.getString("lantai");
                    hari = row.getString("hari");
                    jam = row.getInt("jam");
                    items.add(kode_matkul);
                    items.add(title);
                    items.add(ruang);
                    items.add(latitude);
                    items.add(longitude);
                    items.add(lantai);
                    items.add(hari);
                    items.add(jam);
                }
            }
            );

            return null;
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            // set your list adapter here 
        }
    }