通过Volley获取数据后Listview是空的?

时间:2015-08-09 09:38:23

标签: android listview android-volley

我正在做一个基本的异步任务,通过Volley Library获取数据。我面临的问题是,即使arrayList包含一些值,listview也总是空的。

public class MainActivity extends AppCompatActivity  {

    String url = "...";
    String tag_json_obj = "json_obj_req";
    ProgressDialog pDialog;
    String TAG = MainActivity.class.getSimpleName();
    ListView listView;
    ArrayList<String> stringArrayList;
    ArrayAdapter<String> adapter;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        listView = (ListView)findViewById(R.id.listView);
        stringArrayList = new ArrayList<String>();
        new Volleyoperation().execute();

    }





    public class Volleyoperation extends AsyncTask<Void, Void, ArrayList<String>> {

        ArrayList<String> arrayList = new ArrayList<>();

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(MainActivity.this);
            pDialog.setTitle("Volley Operation");
            pDialog.setMessage("Loading...");
            pDialog.show();
        }

        @Override
        public ArrayList<String> doInBackground(Void... voids) {

            JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.GET,
                    url, (String)null,
                    new Response.Listener<JSONObject>() {

                        @Override
                        public void onResponse(JSONObject response) {
                            Log.d(TAG, response.toString());

                            try {
                                JSONArray jsonArray = response.getJSONArray("posts");
                                for (int i = 0; i < jsonArray.length(); i++){
                                    JSONObject object = jsonArray.getJSONObject(i);
                                    Log.d("track", "" + object.getString("title_plain"));

                                    stringArrayList.add(object.getString("title_plain"));
                                }

                            } catch (JSONException e) {
                                e.printStackTrace();
                            }


                            Log.d("track", "done");
                           // pDialog.hide();
                        }
                    }, new Response.ErrorListener() {

                @Override
                public void onErrorResponse(VolleyError error) {
                    VolleyLog.d(TAG, "Error: " + error.getMessage());
                   VolleyLog.d(TAG, "error msg" +error.networkResponse);
                    Log.d("track", "Error");

                    if(error.networkResponse == null){
                        Log.d("track","Time out");
                    }

                    // hide the progress dialog
              //      pDialog.hide();
                }
            });

            jsonObjReq.setRetryPolicy(new DefaultRetryPolicy(5000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

            AppController.getInstance().addToRequestQueue(jsonObjReq, tag_json_obj);
            return stringArrayList;
        }

        @Override
        protected void onPostExecute(ArrayList<String> result) {
            super.onPostExecute(result);
            Log.d("trrrrr", "on post execute");

            adapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1, stringArrayList);
            listView.setAdapter(adapter);
            pDialog.hide();
        }
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }


}

Logcat:

08-09 14:46:26.820    3207-3207/com.yuvaraj.volleytutorial D/track﹕ Monsoon mocktails
08-09 14:46:26.820    3207-3207/com.yuvaraj.volleytutorial D/track﹕ MANDAVELLI MARKET
08-09 14:46:26.821    3207-3207/com.yuvaraj.volleytutorial D/track﹕ Full Volume &#8211; Musical Game and Karaoke Night
08-09 14:46:26.821    3207-3207/com.yuvaraj.volleytutorial D/track﹕ Bake frost and decorate fondant cake
08-09 14:46:26.821    3207-3207/com.yuvaraj.volleytutorial D/track﹕ Purasawalkam Food Ride
08-09 14:46:26.821    3207-3207/com.yuvaraj.volleytutorial D/track﹕ LIFESTYLE SHOPPING FEST 2015
08-09 14:46:26.822    3207-3207/com.yuvaraj.volleytutorial D/track﹕ DANCE FOR LIFE‬
08-09 14:46:26.822    3207-3207/com.yuvaraj.volleytutorial D/track﹕ Act Fast
08-09 14:46:26.822    3207-3207/com.yuvaraj.volleytutorial D/track﹕ Yes, I Will &#8211; The Stage Fright Cure Workshop
08-09 14:46:26.822    3207-3207/com.yuvaraj.volleytutorial D/track﹕ Murphy&#8217;s Wedding
08-09 14:46:26.822    3207-3207/com.yuvaraj.volleytutorial D/track﹕ done

我无法找到我犯错的地方。

3 个答案:

答案 0 :(得分:2)

您在异步方法中使用异步方法,因此您不必等待AsyncTask中的结果。

JsonObjectRequest已经是一个异步方法,您只需使用相应的回调onResponseonErrorResponse来分派结果。

TLDR;在此特定示例中,不要将AsynTask与异步网络请求一起使用

答案 1 :(得分:1)

正如Simon回答的那样,在设置适配器之前,您无需等待阵列列表填充。

这可以通过将doInBackground方法的Json解析移动到onPostExecute方法来解决。并使用onResponse方法设置适配器。

无论如何,这是一种更好的做法。

答案 2 :(得分:0)

您使用了两种Asynchronous方法,因此ListView无法显示任何数据。

仅使用一个Async Task