0

我能够从我的 php mysql 检索数据到我的 android,但是当我试图将其放入我的列表视图时,它们似乎是我的代码的问题。

这是我的活动代码

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 类

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 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;

    }
}

这就是日志猫说的

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

有没有人有想法是什么导致了错误?任何建议将不胜感激。谢谢你。

4

1 回答 1

2

在 doInBackground() 内部,不能直接对 Any View 执行更新操作

所以你在这里做错了doInBackground()

 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);

所以把这段代码写在里面onPostExecute()

于 2012-10-26T07:02:51.047 回答