程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 更多編程語言 >> 編程綜合問答 >> json-從 PHP MySQL 中檢索數據然後傳到視圖列表中

json-從 PHP MySQL 中檢索數據然後傳到視圖列表中

編輯:編程綜合問答
從 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

最佳回答:


在 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);
  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved