Thursday, 17 May 2018

How to make Pagination Listview in Android

- First To download 3 class of package and put in your package.
https://drive.google.com/file/d/1ysWRLALl19LkOr7vH4ykAswXCQJPO545/view?usp=sharing

- To add following line in string.xml file

    <string name="xlistview_header_hint_normal">Refresh dropdown</string>
    <string name="xlistview_header_hint_ready">Refresh data release</string>
    <string name="xlistview_header_hint_loading">Loading ...</string>
    <string name="xlistview_header_last_time">Last updated:</string>
    <string name="xlistview_footer_hint_normal">View more</string>
    <string name="xlistview_footer_hint_ready">Loosen Load more</string>


- To make xml file name is xlistview_header.xml and add following code inside it.

   <?xml version="1.0" encoding="utf-8"?>
   <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
     android:layout_width="fill_parent"
     android:layout_height="wrap_content"
     android:gravity="bottom">

    <RelativeLayout
        android:id="@+id/xlistview_header_content"
        android:layout_width="fill_parent"
        android:visibility="gone"
        android:layout_height="60dp">

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:gravity="center"
            android:orientation="vertical"
            android:id="@+id/xlistview_header_text">

            <TextView
                android:id="@+id/xlistview_header_hint_textview"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/xlistview_header_hint_normal" />

            <LinearLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="3dp">

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="@string/xlistview_header_last_time"
                    android:textSize="12sp" />

                <TextView
                    android:id="@+id/xlistview_header_time"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:textSize="12sp" />
            </LinearLayout>
        </LinearLayout>

        <ImageView
            android:id="@+id/xlistview_header_arrow"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignLeft="@id/xlistview_header_text"
            android:layout_centerVertical="true"
            android:layout_marginLeft="-35dp"
            android:src="@drawable/xlistview_arrow" />

        <ProgressBar
            android:id="@+id/xlistview_header_progressbar"
            android:layout_width="30dp"
            android:layout_height="30dp"
            android:layout_alignLeft="@id/xlistview_header_text"
            android:layout_centerVertical="true"
            android:layout_marginLeft="-40dp"
            android:visibility="invisible" />
    </RelativeLayout>
   </LinearLayout>

 - To make xml file name is xlistview_footer.xml and add following code inside it.

   <?xml version="1.0" encoding="utf-8"?>
   <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
      android:layout_width="fill_parent"
      android:layout_height="wrap_content">

    <RelativeLayout
        android:id="@+id/xlistview_footer_content"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:padding="10dp">

        <ProgressBar
            android:id="@+id/xlistview_footer_progressbar"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:visibility="invisible" />

        <TextView
            android:id="@+id/xlistview_footer_hint_textview"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:visibility="gone"
            android:text="@string/xlistview_footer_hint_normal" />
     </RelativeLayout>
    </LinearLayout>

 - To Add following code in main.xml file.

  <LinearLayout
        android:id="@+id/linear_news_main"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <com.packagename.xlistview.XListView
            android:id="@+id/list_news"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:divider="@null"></com.packagename.xlistview.XListView>
    </LinearLayout>

- Add Following Code in Your Main Java Class.

-  First Declare variable first
   //XListview
    private XListView mListView;
    private Handler mHandler;
    int lastValueSize;
    NewsAdapter adapter;
    int pagenumber = 1;
    List<NewsPostConstant> list_array;
    ProgressDialog pDialog;

 - Add following code in onCreate Method.
     
      //To Initialize Array list
        list_array = new ArrayList<NewsPostConstant>();

       mListView = (XListView) view.findViewById(R.id.list_news);
       mListView.setPullLoadEnable(true);
       mListView.setXListViewListener(this);
       mHandler = new Handler();

       geneItems();

      mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                Intent intent = new Intent(getActivity(), DescriptionActivity.class);
                String listSerializedToJson = new Gson().toJson(list_array);
                intent.putExtra("Data_Array", listSerializedToJson);
                intent.putExtra("Position", position);
                startActivity(intent);
            }
        });

- Add Following Method Outside of Oncreate Method.

      private void geneItems() {
        getAllData();    }

    private void onLoad() {
        mListView.stopRefresh();
        mListView.stopLoadMore();
        mListView.setRefreshTime("刚刚");
    }

    @Override
    public void onRefresh() {
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {

                try {
                    if (android.os.Build.VERSION.SDK_INT > 9) {
                        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
                        StrictMode.setThreadPolicy(policy);
                    }
                    pagenumber++;
                    geneItems();
                    adapter.notifyDataSetChanged();
                    onLoad();
                } catch (Exception e) {
                    onLoad();
                    Toast.makeText(getActivity(), "No more item found.", Toast.LENGTH_LONG).show();
                }
            }
        }, 1000);
    }


    @Override
    public void onLoadMore() {
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                try {
                    if (android.os.Build.VERSION.SDK_INT > 9) {
                        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
                        StrictMode.setThreadPolicy(policy);
                    }
                    pagenumber++;
                    geneItems();
                    adapter.notifyDataSetChanged();
                    onLoad();
                } catch (Exception e) {
                    onLoad();
                    Toast.makeText(getActivity(), "No more item found.", Toast.LENGTH_LONG).show();
                }

            }
        }, 1000);
    }


    public void getAllData() {
        if (pagenumber == 1) {
            pDialog = new ProgressDialog(getActivity());
            pDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            pDialog.setCancelable(false);
            pDialog.setMessage("Please wait");
            pDialog.show();
        }
        APIInterface apiService =
                ApiClientAnother.getClient().create(APIInterface.class);

        Call<TestConstant> call = apiService.getTestCategory(Category_id, pagenumber);

        call.enqueue(new Callback<TestConstant>() {
            @Override
            public void onResponse(Call<TestConstant> call, Response<TestConstant> response) {
                // Log.d("List size", new Gson().toJson(response.body()));
                String str_success = response.body().getStatus();
                Log.e("Url is",""+response.raw().request().url());
                if (str_success.equals("ok")) {
                    if (pagenumber == 1) {
                        if (pDialog.isShowing()) {
                            pDialog.dismiss();
                        }
                    }
                    //Get Login Response
                    List<NewsPostConstant> list_post = response.body().getPosts();
                    for (int i = 0; i < list_post.size(); i++) {
                        int id = list_post.get(i).getId();
                        String title = list_post.get(i).getTitle();
                        String description = list_post.get(i).getContent();
                        String date = list_post.get(i).getDate();
                     
                        NewsPostConstant newsPostConstant = new NewsPostConstant();
                        newsPostConstant.setId(id);
                        newsPostConstant.setTitle(title);
                        newsPostConstant.setContent(description);
                        newsPostConstant.setDate(date);
                        list_array.add(newsPostConstant);
                    }
                    lastValueSize = mListView.getLastVisiblePosition() - 1;

                    adapter = new NewsAdapter(getActivity(), list_array);
                    mListView.setAdapter(adapter);
                    if (pagenumber != 1) {
                        mListView.setSelection(lastValueSize);
                    }
                } else {
                    if (pagenumber == 1) {
                        if (pDialog.isShowing()) {
                            pDialog.dismiss();
                        }
                    }
                    //Toast.makeText(getApplicationContext(), "No Data Found", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<TestConstant> call, Throwable t) {
                if (pagenumber == 1) {
                    if (pDialog.isShowing()) {
                        pDialog.dismiss();
                    }
                }
                Toast.makeText(getActivity(), "Data Not Available", Toast.LENGTH_SHORT).show();
            }
        });
    }

    public class NewsAdapter extends BaseAdapter {

        private List<NewsPostConstant> array_list;
        private Context context;

        public NewsAdapter(Context context, List<NewsPostConstant> array_list) {
            this.context = context;
            this.array_list = array_list;

        }

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

        @Override
        public Object getItem(int position) {
            // TODO Auto-generated method stub
            return position;
        }

        @Override
        public long getItemId(int Position) {
            // TODO Auto-generated method stub
            return 0;
        }

        @Override
        public View getView(int position, View convert, ViewGroup arg2) {
            // TODO Auto-generated method stub
            View gv;
            if (convert == null) {
                LayoutInflater lf = (LayoutInflater) context
                        .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                gv = new View(context);
                gv = lf.inflate(R.layout.text_category_list, null);
            } else {
                gv = (View) convert;
            }

            TextView text_category_name = (TextView) gv.findViewById(R.id.text_title);
            TextView text_date = (TextView) gv.findViewById(R.id.text_date);

            String title = array_list.get(position).getTitle();
            text_category_name.setText("" + Html.fromHtml(title));

            String date = array_list.get(position).getDate();
            StringTokenizer tokens = new StringTokenizer(date, " ");
            String first = tokens.nextToken();
            String second = tokens.nextToken();
            text_date.setText("" + Html.fromHtml(first));

            return gv;
        }
    }



No comments:

Post a Comment