为什么ListView每次向下滚动时都会重复数据

时间:2015-11-08 11:07:35

标签: php android json listview

我正在做Zodiac app android。从json获取数据,每页显示6个新闻,当我向下滚动时,它应该显示下一个6个新闻。 http://sentienich.aviostore.com/api/cunghoangdao/danhsach_baiviet.php?theloai=4

这个网址: http://sentienich.aviostore.com/api/cunghoangdao/danhsach_baiviet.php?theloai=4&page=2

应该给我第2页的json数据的下一页 我使用了惊人的列表视图。

MainActivity

public class PaginationDemoActivity extends Activity {
    AmazingListView lsComposer;
    PaginationComposerAdapter adapter;
    ArrayList<Composer> list =new ArrayList<Composer>();
    ArrayList<Composer> list1 = new ArrayList<Composer>();
    private String url = "http://sentienich.aviostore.com/api/cunghoangdao/danhsach_baiviet.php?theloai=4";

    private static int pageCount = 1 ;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pagination_demo);

        lsComposer = (AmazingListView) findViewById(R.id.lsComposer);
        lsComposer.setLoadingView(getLayoutInflater().inflate(R.layout.loading_view, null));
        lsComposer.setAdapter(adapter = new PaginationComposerAdapter());

        try {
            list = new docJSon().execute().get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        adapter.notifyMayHaveMorePages();

    }

    public void bRefresh_click(View v) {
        adapter.reset();
        adapter.resetPage();
        adapter.notifyMayHaveMorePages();
    }

    class PaginationComposerAdapter extends AmazingAdapter {

        private AsyncTask<Integer, Void, Pair<Boolean, List<Composer>>> backgroundTask;

        public void reset() {
            if (backgroundTask != null) backgroundTask.cancel(false);
            //list = Data.getRows(1).second;
            notifyDataSetChanged();
        }

        @Override
        public int getCount() {
            return list.size();
        }

        @Override
        public Composer getItem(int position) {
            return list.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        protected void onNextPageRequested(int page) {
            Log.d(TAG, "Got onNextPageRequested page=" + page);

            //tren nay la khi vuot xuong load them
            if( pageCount < 1)
                pageCount++;
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    try {
                        list1 = new docJSon().execute().get();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } catch (ExecutionException e) {
                        e.printStackTrace();
                    }
                }
            });
            if (backgroundTask != null) {
                backgroundTask.cancel(false);
            }

            backgroundTask = new AsyncTask<Integer, Void, Pair<Boolean, List<Composer>>>() {
                @Override
                protected Pair<Boolean, List<Composer>> doInBackground(Integer... params) {
                    int page = params[0];
                    return Data.getRows(page);
            }

                @Override
                protected void onPostExecute(Pair<Boolean, List<Composer>> result) {
                    if (isCancelled()) return;
                // đoạn này là khi vuốt xuống nó add vào cái list đầu tiên
                    list.addAll(list1);
                    nextPage();
                    notifyDataSetChanged();
                    if (result.first) {
                        // still have more pages
                        notifyMayHaveMorePages();
                    } else {
                        notifyNoMorePages();
                    }
                };
            }.execute(page);
        }

        @Override
        protected void bindSectionHeader(View view, int position, boolean displaySectionHeader) {}

        @Override
        public View getAmazingView(int position, View convertView, ViewGroup parent) {
            View res = convertView;
            if (res == null) res = getLayoutInflater().inflate(R.layout.item_composer, null);

            // we don't have headers, so hide it
            res.findViewById(R.id.header).setVisibility(View.GONE);

            TextView lName = (TextView) res.findViewById(R.id.lName);
            TextView lYear = (TextView) res.findViewById(R.id.lYear);

            Composer composer = getItem(position);
            lName.setText(composer.name);
            lYear.setText(composer.year);

            return res;
        }

        @Override
        public void configurePinnedHeader(View header, int position, int alpha) {
        }

        @Override
        public int getPositionForSection(int section) {
            return 0;
        }

        @Override
        public int getSectionForPosition(int position) {
            return 0;
        }

        @Override
        public Object[] getSections() {
            return null;
        }

    }

    public class docJSon extends AsyncTask<String, Integer, ArrayList<Composer>> {
        @Override
        protected ArrayList<Composer> doInBackground(String... arg) {
            url = "http://sentienich.aviostore.com/api/cunghoangdao/danhsach_baiviet.php?theloai=4&page=" +pageCount;

            Parser jParser = new Parser();
            String json = jParser.getJSONData(url);
            try{
                Composer b;
                JSONArray mang = new JSONArray(json);
                for (int i = 0; i < mang.length(); i++) {
                    b = new Composer();
                    JSONObject cunghoangdao = mang.getJSONObject(i);
                    b.setName(cunghoangdao.getString("tieude"));
                    b.setYear(cunghoangdao.getString("id"));
                    list.add(b);
                }
            }catch(JSONException e){
                e.printStackTrace();
            }
            return list;

        }
        protected void onPostExecute(ArrayList<Composer> s){
        }
    }
}

Parser class

public class Parser {
    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";
    public String getJSONData(String url){
        try{
            DefaultHttpClient client = new DefaultHttpClient();
            HttpPost post = new HttpPost(url);
            HttpResponse response = client.execute(post);
            HttpEntity entity = response.getEntity();
            is = entity.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());
        }

        return json;
    }
}

activity_pagination_demo.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent">
<LinearLayout android:layout_height="wrap_content" android:id="@+id/linearLayout1" android:layout_width="fill_parent" android:background="#eee">
    <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Click the button to refresh to page 1" android:layout_weight="1"></TextView>
    <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Refresh" android:onClick="bRefresh_click"></Button>
</LinearLayout>
<com.example.zkyun.amazinglistviewtest.AmazingListView android:layout_width="fill_parent" android:layout_height="fill_parent" android:id="@+id/lsComposer" />

1 个答案:

答案 0 :(得分:0)

每次你要求

alert: 'lol'

from subprocess import check_output import re with open('so-expiration.txt', 'wt') as fout: for line in check_output(["whois", "stackoverflow.com"]).split('\n'): if re.match(r'Registrar Registration Expiration Date', line): fout.write(line) 设置为1.要使其正常工作,您需要使用url = "http://.../danhsach_baiviet.php?theloai=4&page=" + pageCount; 的{​​{1}}参数,并以某种方式将其传递给pageCount

此外,您最好将page的实施与onNextPageRequested(int page)的实施合并。目前,您正在使用

阻止UI线程
docJSon

也可以解决您当前的问题。