dongzhang8680 2014-11-30 14:47
浏览 66
已采纳

如何排序从phpMyAdmin获取数据的listview

I have a simple android application that gets data from phpMyAdmin DB and show it in a ListView. In my Database I've 2 column one for called place_name and the second is called numbers_of_visits. I can get the data from the database without any problem.

but i am having problems trying to sort the listview based on the highest number of visit(that is on the database), so the place with highest number of visits should be on the top and so on.

please guys help me to do this

Here is my Jvav code

        package com.example.ems_project;

    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.util.ArrayList;
    import java.util.Comparator;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;

    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;

    import android.app.Activity;
    import android.os.AsyncTask;
    import android.os.Bundle;
    import android.widget.ListView;
    import android.widget.SimpleAdapter;
    import android.widget.Toast;

    public class PlacesListView extends Activity {
        private String jsonResult;
        private String url = "http://ibrahimaldosari.t15.org/listview.php";
        private ListView listView;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.listview_main2);
            listView = (ListView) findViewById(R.id.listview);
            accessWebService();
        }

        // Async Task to access the web
        private class JsonReadTask extends AsyncTask<String, Void, String> {
            @Override
            protected String doInBackground(String... params) {
                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost(params[0]);
                try {
                    HttpResponse response = httpclient.execute(httppost);
                    jsonResult = inputStreamToString(response.getEntity().getContent()).toString();
                }

                catch (ClientProtocolException e) { 
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return null;
            }

            private StringBuilder inputStreamToString(InputStream is) {
                String rLine = "";
                StringBuilder answer = new StringBuilder();
                BufferedReader rd = new BufferedReader(new InputStreamReader(is));

                try {
                    while ((rLine = rd.readLine()) != null) {
                        answer.append(rLine);
                    }
                }

                catch (IOException e) {
                    // e.printStackTrace();
                    Toast.makeText(getApplicationContext(), "Error..." + e.toString(), Toast.LENGTH_LONG).show();
                }
                return answer;
            }

            @Override
            protected void onPostExecute(String result) {
                ListDrwaer();
            }
        }// end async task

        public void accessWebService() {
            JsonReadTask task = new JsonReadTask();
            // passes values for the urls string array
            task.execute(new String[] { url });
        }

        // build hash set for list view
        public void ListDrwaer() {
            List<Map<String, String>> employeeList = new ArrayList<Map<String, String>>();

            try {
                JSONObject jsonResponse = new JSONObject(jsonResult);
                JSONArray jsonMainNode = jsonResponse.optJSONArray("placestable");

                for (int i = 0; i < jsonMainNode.length(); i++) {


                    JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
                    String name = jsonChildNode.optString("name");
                    int number = jsonChildNode.optInt("visit");

                    String outPut = name + "---" + number;
                    employeeList.add(createEmployee("places", outPut));

                }
            } catch (JSONException e) {
                Toast.makeText(getApplicationContext(), "Error" + e.toString(),Toast.LENGTH_SHORT).show();
            }

            SimpleAdapter simpleAdapter = new SimpleAdapter(this, employeeList, android.R.layout.simple_list_item_1, new String[] { "places" }, new int[] { android.R.id.text1 });

            listView.setAdapter(simpleAdapter);

        }

        private HashMap<String, String> createEmployee(String name, String number) {
            HashMap<String, String> employeeNameNo = new HashMap<String, String>();
            employeeNameNo.put(name, number);
            return employeeNameNo;
        }
    }

and this the php file i am using

<?php
  $host="mysql.freehostingnoads.net"; //replace with database hostname 
   $username="u746805016_ibrr1"; //replace with database username 
  $password="113281188"; //replace with database password 
  $db_name="u746805016_ibrr1"; //replace with database name

  $con=mysql_connect("$host", "$username", "$password")or die("cannot connect"); 
  mysql_select_db("$db_name")or die("cannot select DB");
  $sql = "select * from placestable"; 
  $result = mysql_query($sql);
  $json = array();

  if(mysql_num_rows($result)){
  while($row=mysql_fetch_assoc($result)){
  $json['placestable'][]=$row;
  }
  }
  mysql_close($con);
  echo json_encode($json); 
  ?> 
  • 写回答

1条回答 默认 最新

  • drnysdnnb2909701 2014-11-30 15:05
    关注

    You can make this in 2 ways. 1. On server side, by little changing select query to something like this:

    $sql = "select * from placestable ORDER BY visit DESC";

    or 2. By sorting this on app side. But then I would create Employee class with fields: name and visit, and implement there Comparable interface.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 LiBeAs的带隙等于0.997eV,计算阴离子的N和P
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 matlab有关常微分方程的问题求解决,来真人,不要ai!
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?
  • ¥100 求三轴之间相互配合画圆以及直线的算法