开发者社区> 问答> 正文

从 PHP MySQL 中检索数据然后传到视图列表中

我想从 PHP MySQL 中检索一个数据,然后传到试图列表中。我使用的下面的代码,但是还是没把数据放到 List View 中,如何改这个问题。
贴出我的代码,大家看看是哪儿出错了。

Activity Codes
public class View extends Activity{
    // Progress Dialog
    // Creating JSON Parser object
    JSONParser jParser = new JSONParser();
    ArrayList<HashMap<String, String>> productsList;
   // url to get all products list
    private static String url_all_products = "http://atlantis-us.com/viewFile.php";
    // JSON Node names
    private static final String TAG_NAME = "name";
    ListView lv;
    // products JSONArray
    JSONArray products = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.all_products);


        // Get listview
        lv = (ListView) findViewById(R.id.list);

        // Hashmap for ListView
        productsList = new ArrayList<HashMap<String, String>>();
            new LoadAllProducts().execute();    
    }
    class LoadAllProducts extends AsyncTask<String, String, String> {

        @Override
        protected String doInBackground(String... arg0) {
            // TODO Auto-generated method stub
             // Building Parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();
                JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);
            Log.d("All Products: ", json.toString());
            ListAdapter adapter = new SimpleAdapter(
                    View.this, productsList,
                    R.layout.list_item, new String[] {
                            TAG_NAME},
                    new int[] {R.id.name });
            // updating listview
            lv.setAdapter(adapter);
            return null;
        }
    }
}


JSONParser Class
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();

            }else if(method == "GET"){
                // request method is GET
                DefaultHttpClient httpClient = new DefaultHttpClient();
                String paramString = URLEncodedUtils.format(params, "utf-8");
                url += "?" + paramString;
                HttpGet httpGet = new HttpGet(url);

                HttpResponse httpResponse = httpClient.execute(httpGet);
                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;
    }
}
log cat
10-26 14:57:53.673: I/Choreographer(1391): Skipped 61 frames!  The application may be doing too much work on its main thread.
10-26 14:57:54.653: D/All Products:(1391): {"products":[{"name":"Ghalia"},{"name":"yuan"},{"name":"kevin"},{"name":"kevin"},{"name":"kevin"},{"name":"Ghalia"},{"name":"Ghalia"},{"name":"dbgg"},{"name":"Ghalia"},{"name":"Ghalia"},{"name":"test"}]}
10-26 14:57:54.663: W/dalvikvm(1391): threadid=11: thread exiting with uncaught exception (group=0x40a13300)
10-26 14:57:54.684: E/AndroidRuntime(1391): FATAL EXCEPTION: AsyncTask #1
10-26 14:57:54.684: E/AndroidRuntime(1391): java.lang.RuntimeException: An error occured while executing doInBackground()
10-26 14:57:54.684: E/AndroidRuntime(1391):     at android.os.AsyncTask$3.done(AsyncTask.java:299)
10-26 14:57:54.684: E/AndroidRuntime(1391):     at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
10-26 14:57:54.684: E/AndroidRuntime(1391):     at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
10-26 14:57:54.684: E/AndroidRuntime(1391):     at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
10-26 14:57:54.684: E/AndroidRuntime(1391):     at java.util.concurrent.FutureTask.run(FutureTask.java:137)
10-26 14:57:54.684: E/AndroidRuntime(1391):     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
10-26 14:57:54.684: E/AndroidRuntime(1391):     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
10-26 14:57:54.684: E/AndroidRuntime(1391):     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
10-26 14:57:54.684: E/AndroidRuntime(1391):     at java.lang.Thread.run(Thread.java:856)
10-26 14:57:54.684: E/AndroidRuntime(1391): Caused by: android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
10-26 14:57:54.684: E/AndroidRuntime(1391):     at android.view.ViewRootImpl.checkThread(ViewRootImpl.java:4607)
10-26 14:57:54.684: E/AndroidRuntime(1391):     at android.view.ViewRootImpl.requestLayout(ViewRootImpl.java:835)
10-26 14:57:54.684: E/AndroidRuntime(1391):     at android.view.View.requestLayout(View.java:15129)
10-26 14:57:54.684: E/AndroidRuntime(1391):     at android.view.View.requestLayout(View.java:15129)
10-26 14:57:54.684: E/AndroidRuntime(1391):     at android.view.View.requestLayout(View.java:15129)
10-26 14:57:54.684: E/AndroidRuntime(1391):     at android.view.View.requestLayout(View.java:15129)
10-26 14:57:54.684: E/AndroidRuntime(1391):     at android.view.View.requestLayout(View.java:15129)
10-26 14:57:54.684: E/AndroidRuntime(1391):     at android.widget.AbsListView.requestLayout(AbsListView.java:1928)
10-26 14:57:54.684: E/AndroidRuntime(1391):     at android.widget.ListView.setAdapter(ListView.java:488)
10-26 14:57:54.684: E/AndroidRuntime(1391):     at com.example.mysql.View$LoadAllProducts.doInBackground(View.java:74)
10-26 14:57:54.684: E/AndroidRuntime(1391):     at com.example.mysql.View$LoadAllProducts.doInBackground(View.java:1)
10-26 14:57:54.684: E/AndroidRuntime(1391):     at android.os.AsyncTask$2.call(AsyncTask.java:287)
10-26 14:57:54.684: E/AndroidRuntime(1391):     at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
10-26 14:57:54.684: E/AndroidRuntime(1391):     ... 5 more

展开
收起
杨冬芳 2016-07-04 11:17:49 2628 0
1 条回答
写回答
取消 提交回答
  • IT从业

    在 doInBackground()中,你不能对任何试图直接执行更新操作,你在 doInBackground()这里出错了,所以在 onPostExecute()里面添加下面的代码:
    ListAdapter adapter = new SimpleAdapter(

                    View.this, productsList,
                    R.layout.list_item, new String[] {
                            TAG_NAME},
                    new int[] {R.id.name });
            // updating listview
            lv.setAdapter(adapter);
    
    2019-07-17 19:50:33
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
搭建电商项目架构连接MySQL 立即下载
搭建4层电商项目架构,实战连接MySQL 立即下载
PolarDB MySQL引擎重磅功能及产品能力盛大发布 立即下载

相关镜像