如何在listview android中加载下十个json数据

时间:2014-08-25 07:51:02

标签: android json facebook listview android-listview

我从URL解析了JSON数据,并显示了前十个Feed。当我滚动到列表视图中的第9个数据时,调用AsynTask并且无限加载所有其他数据,但是我需要通过递增下一页索引来加载JSON中的下十个数据。

当我滚动到页面末尾时,如何仅从JSON加载下十个数据?

以下是我的代码的MainActivity:

public class MainActivity extends Activity {

private static final String TAG = MainActivity.class.getSimpleName();
private ListView listView;
ProgressDialog pDialog;
private FeedListAdapter listAdapter;
private List<FeedItem> feedItems;
public String URL_FEED = "http://saverken.com/saverken/featuredpost/getPost?logged_in_user_id=6&start_index=0";
private int PAGE_NUM = 0;
public static JSONArray feedArray; 
boolean stillAvaialble=true;
@SuppressLint("NewApi")
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    listView = (ListView) findViewById(R.id.list);

    feedItems = new ArrayList<FeedItem>();

    listAdapter = new FeedListAdapter(this, feedItems);
    listView.setAdapter(listAdapter);

    // These two lines not needed,
    // just to get the look of facebook (changing background color & hiding the icon)
    getActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#3b5998")));
    getActionBar().setIcon(
               new ColorDrawable(getResources().getColor(android.R.color.transparent)));

    // We first check for cached request

    Cache cache = AppController.getInstance().getRequestQueue().getCache();
    Entry entry = cache.get(URL_FEED);
    if (entry != null) {
        // fetch the data from cache
        try {
            String data = new String(entry.data, "UTF-8");
            try {
                parseJsonFeed(new JSONObject(data));
            } catch (JSONException e) {
                e.printStackTrace();
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

    } else {
        // making fresh volley request and getting json
        JsonObjectRequest jsonReq = new JsonObjectRequest(Method.GET,
                URL_FEED, null, new Response.Listener<JSONObject>() {

                    @Override
                    public void onResponse(JSONObject response) {
                        VolleyLog.d(TAG, "Response: " + response.toString());
                        Log.v("response", ""+response);
                        if (response != null) {
                            parseJsonFeed(response);

                            stillAvaialble=true;
                            PAGE_NUM += 1;

                        }
                    }
                }, new Response.ErrorListener() {

                    @Override
                    public void onErrorResponse(VolleyError error) {
                        VolleyLog.d(TAG, "Error: " + error.getMessage());
                        stillAvaialble=false;
                    }
                });

        // Adding request to volley request queue
        AppController.getInstance().addToRequestQueue(jsonReq);
    }




    listView.setOnScrollListener(new OnScrollListener() {

        @Override
        public void onScrollStateChanged(AbsListView view, int scrollState) {
            // TODO Auto-generated method stub

        }

        @Override

        public void onScroll(AbsListView view, int firstVisibleItem,
                int visibleItemCount, int totalItemCount) {

                Log.d(TAG,"onScroll !!!!!");
                int lastInScreen = firstVisibleItem + visibleItemCount; 
            // TODO Auto-generated method stub
             if (PAGE_NUM != 0 && listView.getLastVisiblePosition() == totalItemCount - 1
                     && stillAvaialble && (lastInScreen == totalItemCount) ) {
                    new AsynThread().execute();
                 }
        }
    });


}

这是AsynTask:

public class AsynThread extends AsyncTask<Void, Void, Void>{

    protected void onPreExecute() {
        // Showing progress dialog before sending http request
        pDialog = new ProgressDialog(
                MainActivity.this);
        pDialog.setMessage("Please wait..");
       pDialog.setIndeterminate(true);
        pDialog.setCancelable(false);
        pDialog.show();
    }

    @Override
    protected Void doInBackground(Void... arg0) {
        runOnUiThread(new Runnable() {
             public void run() {
                URL_FEED = "http://saverken.com/saverken/featuredpost/getPost?logged_in_user_id=6&start_index=" + PAGE_NUM;

             Cache cache = AppController.getInstance().getRequestQueue().getCache();
                    Entry entry = cache.get(URL_FEED);
                    if (entry != null) {
                        // fetch the data from cache
                        try {
                            String data = new String(entry.data, "UTF-8");
                            try {
                                parseJsonFeed(new JSONObject(data));
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        } catch (UnsupportedEncodingException e) {
                            e.printStackTrace();
                        }

                    } else {
                        // making fresh volley request and getting json
                        JsonObjectRequest jsonReq = new JsonObjectRequest(Method.GET,
                                URL_FEED, null, new Response.Listener<JSONObject>() {

                                    @Override
                                    public void onResponse(JSONObject response) {
                                        VolleyLog.d(TAG, "Response: " + response.toString());
                                        Log.v("response", ""+response);
                                        if (response != null) {

                                            stillAvaialble=true;
                                            PAGE_NUM +=1;

                                            parseJsonFeed(response);
                                        }
                                    }
                                }, new Response.ErrorListener() {

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

                                        stillAvaialble=false;
                                        PAGE_NUM=0;
                                    }
                                });

                        // Adding request to volley request queue
                        AppController.getInstance().addToRequestQueue(jsonReq);
                    }
             }

        });

        return null;
    }

}

解析json响应并将数据传递给提要视图列表适配器

private void parseJsonFeed(JSONObject response) {

    try {


         feedArray = response.getJSONArray("post_details");

        Log.v("jsonarray", ""+feedArray.length());

        for (int i = 0; i < feedArray.length(); i++) {
            JSONObject feedObj = (JSONObject) feedArray.get(i);

            FeedItem item = new FeedItem();
            item.setPost_id(feedObj.getInt("post_id"));
            item.setName(feedObj.getString("firstname"));
            item.setCity(feedObj.getString("city"));
            item.setState(feedObj.getString("state"));
            item.setInterest(feedObj.getString("interest"));
            item.setSpecialty(feedObj.getString("specialty"));
            item.setEmail(feedObj.getString("email"));
            item.setSubject(feedObj.getString("subject"));
            // Image might be null sometimes
            String image = feedObj.isNull("video") ? null : feedObj
                    .getString("video");
            item.setImage("http://saverken.com/saverken/"+image);
            item.setStatus(feedObj.getString("posts"));
            String profilePic = feedObj.isNull("personal_photo") ? null : feedObj
                    .getString("personal_photo");
            item.setProfilePic("http://saverken.com/saverken/"+profilePic);
            item.setTimeStamp(feedObj.getString("date"));

            // url might be null sometimes
            String feedUrl = feedObj.isNull("url") ? null : feedObj
                    .getString("url");
            item.setUrl(feedUrl);

            feedItems.add(item);

        }

        // notify data changes to list adapater
        listAdapter.notifyDataSetChanged();
    } catch (JSONException e) {
        e.printStackTrace();
    }

参考:http://www.androidhive.info/2014/06/android-facebook-like-custom-listview-feed-using-volley

0 个答案:

没有答案