如何在Fragment中实现Endless listview?

时间:2017-04-28 10:35:21

标签: android listview android-fragments fragment endlessscroll

我在Fragment中实现了无尽的listview。当我为我的列表视图编写setOnScrollListener的代码时,我的应用程序崩溃并出现错误The content of the adapter has changed but ListView did not receive a notification. Make sure the content of your adapter is not modified from a background thread, but only from the UI thread. Make sure your adapter calls notifyDataSetChanged() when its content changes.我已尝试在我的适配器上应用notifyDataSetChanged()几乎所有内容。请帮我解决问题。

下面是我的代码。

 @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View rootView = inflater.inflate(R.layout.fragment_all_campaign, container, false);
        allCampaignList = (ListView) rootView.findViewById(R.id.allCampaignList);
        adapter = new CampaignListAdapter(getActivity(), CampaignDataArrayList);
        loadCampaignsData(offsetValue);

        allCampaignList.setOnScrollListener(new AbsListView.OnScrollListener() {

            @Override
            public void onScroll(AbsListView view,
                                 int firstVisibleItem, int visibleItemCount,
                                 int totalItemCount) {
                //Algorithm to check if the last item is visible or not
                final int lastItem = firstVisibleItem + visibleItemCount;
                if (lastItem == totalItemCount) {
                    // you have reached end of list, load more data
                    loadCampaignsData(offsetValue + 1);
                    offsetValue++;
                }
            }

            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                //blank, not using this
            }
        });

        return rootView;
    }

以下是方法loadCampaignsData():

 public void loadCampaignsData(final int offset) {
        pDialog.setMessage("Please wait..");
        pDialog.setTitle("Loading");
        showDialog();
        Handler h = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                if (msg.what != 1) {
                    hideDialog();// code if not connected
                    viewUtils.internertErrorMsgDialog();
                } else {
                    GetAllCampaign getAllCampaign = new GetAllCampaign();
                    getAllCampaign.execute(String.valueOf(offset));
                }
            }
        };
        viewUtils.isNetworkAvailable(h, 2000); // get the answser within 2000 ms
    }

下面是为获取webservice而编写的asynctask。

private class GetAllCampaign extends AsyncTask<String, Void, ArrayList<HashMap<String, String>>> {

        @Override
        protected ArrayList<HashMap<String, String>> doInBackground(String... params) {
            try {
                HttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(Constants.DADAMI_URL + Constants.ALL_CAMPAIGN);

                List<NameValuePair> list = new ArrayList<NameValuePair>();
                list.add(new BasicNameValuePair("cat_id", "0"));
                list.add(new BasicNameValuePair("user_id", ""));
                list.add(new BasicNameValuePair("offset", params[0]));

                httpPost.setEntity(new UrlEncodedFormEntity(list));
                HttpResponse httpResponse = httpClient.execute(httpPost);

                HttpEntity httpEntity = httpResponse.getEntity();
                return readResponse(httpResponse);
                //return null;
            } catch (Exception exception) {
                exception.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(ArrayList<HashMap<String, String>> result) {
            super.onPostExecute(result);
            hideDialog();
            if (result == null) {
                Toast.makeText(context, "Something went wrong.. Please try again..!!", Toast.LENGTH_LONG).show();
            } else {
                getActivity().runOnUiThread(new Runnable() {
                    public void run() {

                        allCampaignList.setAdapter(adapter);

                    }
                });


            }
        }
    }

    private ArrayList<HashMap<String, String>> readResponse(HttpResponse res) {
        InputStream is = null;
        try {
            is = res.getEntity().getContent();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is));
            StringBuffer sb = new StringBuffer();
            String line = "";
            while ((line = bufferedReader.readLine()) != null) {
                sb.append(line);
            }

            JSONObject mainObj = new JSONObject(sb.toString());
            JSONArray fundraiser_data = null;

            fundraiser_data = mainObj.getJSONArray("fundraiser_data");

            for (int i = 0; i < fundraiser_data.length(); i++) {
                JSONObject elem = fundraiser_data.getJSONObject(i);

                String fundraiser_photo = elem.getString("fundraiser_photo");
                String title = elem.getString("title");
                String fullname = elem.getString("fullname");


                HashMap<String, String> campaignData = new HashMap<>();

                campaignData.put("fundraiser_photo", Constants.DADAMI_IMAGE_URL + fundraiser_photo);
                campaignData.put("title", title);
                campaignData.put("fullname", fullname);


                CampaignDataArrayList.add(campaignData);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return CampaignDataArrayList;

    }

0 个答案:

没有答案