How to implement ListView Pagination from SQLite database in Android? - android

I want to implement List-View from SQLite Database that i have done. But right now i want to implement pagination on List View setOnScrollListener.First time I'm displaying first 50 records after that when I scroll at the end of list run the progress bar some amount of second and after stop the progress bar another next 50 records append to the list.I'm trying lot of time since 5 days working on List View Pagination but it is not working properly.Can some one help me to resolve this issue.
Here is my code .
listView.addFooterView(footer);
// Implementing scroll refresh
listView.setOnScrollListener(new AbsListView.OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView absListView, int i) {
}
#Override
public void onScroll(AbsListView absListView, int firstItem, int visibleItemCount, final int totalItems) {
//Log.e("Get position", "--firstItem:" + firstItem + " visibleItemCount:" + visibleItemCount + " totalItems:" + totalItems + " pageCount:" + pageCount);
int total = firstItem + visibleItemCount;
Log.e("", "onScroll LocalPages=" + LocalPages);
// Total array list i have so it
if (pageCount < LocalPages) {
if (total == totalItems) {
// Execute some code after 8 seconds have passed
Handler handler = new Handler();
handler.postDelayed(new Runnable()
{
public void run()
{
listView.addFooterView(footer);
OFFSET = pageCount * 50 ;
//Log.e("","After OFFSET pageCount =" + pageCount + " OFFSET value ="+OFFSET);
List<All_Post> allDesc = dbhelper.getAllDescriptions(OFFSET);
for (All_Post all_Post : allDesc)
{
descArray.add(all_Post);
}
if(adapter != null)
{
adapter.notifyDataSetChanged();
listView.setAdapter(adapter);
listView.setSelection(totalItems);
pageCount += 1;
Log.e(""," pageCount =" + pageCount + " LocalPages="+LocalPages);
}
}
}, 2000);
}
} else {
Log.e("hide footer", "footer hide");
listView.removeFooterView(footer);
}
}
});

You can do this for following approach.
// create one final list
final ArrayList<String> temp = new ArrayList<String>();
temp.addAll(previous_data);
// call fxn for getting new value
// call your database query
// add new data into list
temp.addAll(new_Data);
// intailize static list of adapter showing data
// add data into list.
ActivityName.MainList = temp;
mAdapter.notifyDataSetChanged();
with your code also... thanks

Related

How to clear list in RecyclerView on ScrollUp

i want to make app With Rest Api and Retrofit. i want to load Random posts when user pull down the RecyclerView, i made it but one thing that is annoying, when i load Random posts. it display after the first 10 posts, i mean after home page's 10 posts but i want to clear the old posts and display random posts from row 1.
the code i am using for scroll up
else if (!recyclerView.canScrollVertically(-1) && dy < 0)
{
yourURL1 = baseURL + baseModel + "&orderby=rand&page=" + pageNo++;
getRetrofit1();
}
Retrofit
try {
List<Model> list = new ArrayList<>();
Call<List<WPPost>> call = service.getPostInfo( yourURL);
call.enqueue(new Callback<List<WPPost>>() {
#Override
public void onResponse(Call<List<WPPost>> call, Response<List<WPPost>> response) {
Log.d("==>>", " response "+ response.body());
mListPost = response.body();
progressBar.setVisibility(View.GONE);
if (response.body() != null) {
for (int i = 0; i < response.body().size(); i++ ) {
Log.d("==>>", " title " + response.body().get(i).getTitle().getRendered() + " " +
response.body().get(i).getId());
String tempdetails = String.valueOf((Html.fromHtml(response.body().get(i).getExcerpt().getRendered().toString())));
tempdetails = tempdetails.replace("<p>", "");
tempdetails = tempdetails.replace("</p>", "");
tempdetails = tempdetails.replace("[…]", "");
list.add(new Model(String.valueOf((Html.fromHtml(response.body().get(i).getTitle().getRendered()))),
tempdetails, response.body().get(i).getPostViews().toString(),
response.body().get(i).getImages().getMedium(),response.body().get(i).getContent().getRendered()));
}
if (loading){
loading = false;
adapter.showHideProgress(false);
}
adapter.addItemsToList(list);
progressBar.setVisibility(View.GONE);
} else {
progressBar.setVisibility(View.GONE);
}
}
#Override
public void onFailure(Call<List<WPPost>> call, Throwable t) {
}
});
}catch (Exception exception){
Log.d("tisha==>>"," "+exception.getLocalizedMessage());
}
In adapter
void addItemsToList(List<Model> newItems){
if (dataset.isEmpty()){
dataset.addAll(newItems);
notifyDataSetChanged();
Log.d("tisha==>>","First time List size = "+dataset.size());
}else {
int lastItemPosition = dataset.size() -1;
Log.d("tisha==>>","Old list size = "+dataset.size()+ "Last Item position= "+lastItemPosition);
dataset.addAll(newItems);
Log.d("tisha==>>","Update List size = "+dataset.size());
notifyItemRangeInserted(lastItemPosition,newItems.size());
}
}
how can i clear list ?
once this list is set you are adding items to list , you have to remove elements first notify item ranged removed then add new and update on notify item inserted
void addItemsToList(List<Model> newItems)
{ if (dataset.isEmpty())
{ dataset.addAll(newItems);
notifyDataSetChanged();
Log.d("tisha==>>","First time List size = "+dataset.size());
}
else
{
int lastItemPosition = dataset.size() -1;
Log.d("tisha==>>","Old list size = "+dataset.size()+ "Last Item position= "+lastItemPosition); dataset.addAll(newItems);
Log.d("tisha==>>","Update List size = "+dataset.size()); notifyItemRangeInserted(lastItemPosition,newItems.size()); } }

Android ListView not refreshing after notifyDataSetChanged is called

I have struggled to load more items on listview after calling notifyDataSetChanged() method
Here is the code block for setting user scroll action on listview
lv = (ListView) getActivity().findViewById(R.id.list);
adapter = new ItemListAdapter(getActivity(), getList(), 2);
progressDialog.show();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
lv.setAdapter(adapter);
progressDialog.dismiss();
adapter.notifyDataSetChanged();
}
}, SPLASH_TIME_OUT);
lv.setOnScrollListener(new AbsListView.OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL) {
userScrolled = true;
}
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
if (userScrolled) {
userScrolled = false;
progressDialog.getWindow().setGravity(Gravity.BOTTOM);
progressDialog.show();
updateListView();
}
}
});
And here is my updateListView method:
private void updateListView() {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
if (appPreference.getLoadStatus().equals("0")) {
for (int i = 0; i < getListMore().size(); i++) {
Log.i("MORE VALUES", "" + getListMore().get(i));
getList().add(getListMore().get(i));
}
appPreference.saveLoadStatus("1");
}
progressDialog.dismiss();
adapter.notifyDataSetChanged();
}
}, 100);
}
Here is my getList() method
public List<ItemList> getList() {
ContentResolver cr = getActivity().getContentResolver();
String where = Products.SYNCSTATUS + " != 3";
Cursor c = cr.query(Products.BASEURI, null, where, null, Products.ID + " DESC");
list = new ArrayList<ItemList>();
try {
if (c.getCount() > 0) {
c.moveToFirst();
do {
int colN = c.getColumnIndex(Products.PRODUCT);
int colP = c.getColumnIndex(Products.ON_HAND);
int colI = c.getColumnIndex(Products.ID);
int colD = c.getColumnIndex(Products.SKU);
int colPr = c.getColumnIndex(Products.PRICE);
int colUp = c.getColumnIndex(Products.UPDATE);
String n = c.getString(colNad);
String p = c.getString(colPle);
long i = c.getLong(colIMEI);
String d = c.getString(colDec);
String pr = c.getString(colProd);
String upd = c.getString(colUpdated);
if (!Validating.areSet(upd))
upd = getString(R.string.strnever);
if (tabletsize) {
list.add(new ItemList(n.toUpperCase(Locale.getDefault()), pr, p, i,
d, upd));
} else {
list.add(new ItemList(getString(R.string.strproduct).toUpperCase(Locale.getDefault()) + ": " +
n.toUpperCase(Locale.getDefault()),
getString(R.string.strprice).toUpperCase(Locale.getDefault()) + ": " +
pr.toUpperCase(Locale.getDefault()),
getString(R.string.strtotalqty).toUpperCase(Locale.getDefault()) + ": " + p, i,
getString(R.string.strsku).toUpperCase(Locale.getDefault()) + ": " + d,
getString(R.string.strlastsell).toUpperCase(Locale.getDefault()) + ": " + upd));
}
} while (c.moveToNext());
} else {
String n = getString(R.string.strnodata).toUpperCase(Locale.getDefault());
String p = " ";
long i = 0;
String d = null;
list.add(new ItemList(n, "", p, i, d));
}
} finally {
if (c != null) {
c.close();
}
}
return list;
}
My intention is to load more items using getListMore() method which load data from database, add them into getList() method which returns List<ItemList>
The problem comes when i scroll the listview there is no new data loaded onto it ,the logs shows the
Log.i("MORE VALUES", "" + getListMore().get(i)); returned the data from database but no data has been shown on listview.
Can anyone help with the issue as why the data is not loaded and how to fix it?
Thanks
Can you try changing:
new Handler().postDelayed(new Runnable() {
to:
new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
The method adapter.notifyDataSetChanged(); needs to be called from the main thread only.
You are actually fetching the data, adding it into list with getList() but not setting that list. you probably need to setlist() with new values.
Something like, setList(new updated list here) and then adapter.notifyDataSetChanged()
you need to make getList() more clear, see every time you get getList() and add new item in it, it reinstanitate the list, add the old items in it which you have added veru first time. better to make a change the method something like this.
public List<ItemList> getList() {
if(list != null || list.size() > 0) {
return list;
}
ContentResolver cr = getActivity().getContentResolver();
String where = Products.SYNCSTATUS + " != 3";
Cursor c = cr.query(Products.BASEURI, null, where, null, Products.ID + " DESC");
list = new ArrayList<ItemList>();
try {
if (c.getCount() > 0) {
c.moveToFirst();
do {
int colN = c.getColumnIndex(Products.PRODUCT);
int colP = c.getColumnIndex(Products.ON_HAND);
int colI = c.getColumnIndex(Products.ID);
int colD = c.getColumnIndex(Products.SKU);
int colPr = c.getColumnIndex(Products.PRICE);
int colUp = c.getColumnIndex(Products.UPDATE);
String n = c.getString(colNad);
String p = c.getString(colPle);
long i = c.getLong(colIMEI);
String d = c.getString(colDec);
String pr = c.getString(colProd);
String upd = c.getString(colUpdated);
if (!Validating.areSet(upd))
upd = getString(R.string.strnever);
if (tabletsize) {
list.add(new ItemList(n.toUpperCase(Locale.getDefault()), pr, p, i,
d, upd));
} else {
list.add(new ItemList(getString(R.string.strproduct).toUpperCase(Locale.getDefault()) + ": " +
n.toUpperCase(Locale.getDefault()),
getString(R.string.strprice).toUpperCase(Locale.getDefault()) + ": " +
pr.toUpperCase(Locale.getDefault()),
getString(R.string.strtotalqty).toUpperCase(Locale.getDefault()) + ": " + p, i,
getString(R.string.strsku).toUpperCase(Locale.getDefault()) + ": " + d,
getString(R.string.strlastsell).toUpperCase(Locale.getDefault()) + ": " + upd));
}
} while (c.moveToNext());
} else {
String n = getString(R.string.strnodata).toUpperCase(Locale.getDefault());
String p = " ";
long i = 0;
String d = null;
list.add(new ItemList(n, "", p, i, d));
}
} finally {
if (c != null) {
c.close();
}
}
return list;
}

Value incremented when Scroll to bottom of listview?

I have a listview in which when I scroll to bottom of listview a progress bar is visible to user and send server request in that request I send count value ,But problem is that when I fast scroll bottom and up this count value will be incremented every time when I scroll bottom before getting response from server sending another request to server.
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE && bBottomOfView) {
Log.i("Listview", "scrolling stopped...");
if (NetworkUtil.isConnected(getActivity())) {
sz_RecordCount = String.valueOf(m_n_DefaultRecordCount);// convert int value to string
sz_LastCount = String.valueOf(CLastCountData.getInstance().getS_szLastCount());// convert int value to string /////
Log.e(TAG, "Last Count::" + sz_LastCount);
Log.e(TAG, "Record count::" + sz_RecordCount);
loadmoreData();
} else {
CSnackBar.getInstance().showSnackBarError(m_MainLayout, "No internet connection available", getActivity());
m_ListView.removeFooterView(mFooter);
}
}
}
#SuppressLint("InflateParams")
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
bBottomOfView = (firstVisibleItem + visibleItemCount) == totalItemCount;
if (m_ListView.getFooterViewsCount() == 0) {
mFooter = ((LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.footer, null, false);
m_ListView.addFooterView(mFooter);
}
}

SQlite Pagination on ListView scrolling in Android

I'm Stuck in implementing Pagination in Android.I need help to creating pagination with Sq-lite local database at the end of List-view Scrolling.I'm trying to add 10 items per page and increase the local page index up to 5 times on List view Scrolling at the end and append the next 10 Sq-lite data rows in List-view , but something is wrong with my code.Only 1 page size creating when I scrolling 2nd time page size does not increase by 1 and progress-bar is running contentiously . Can some one help me to solve this .
Here is my Code for ListView Scrolling.
listView.addFooterView(footer);
// Implementing scroll refresh
listView.setOnScrollListener(new AbsListView.OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView absListView, int i) {
}
#Override
public void onScroll(AbsListView absListView, int firstItem, int visibleItemCount, final int totalItems) {
//Log.e("Get position", "--firstItem:" + firstItem + " visibleItemCount:" + visibleItemCount + " totalItems:" + totalItems + " pageCount:" + pageCount);
int total = firstItem + visibleItemCount;
Log.e("", "onScroll LocalPages=" + LocalPages);
// Total array list i have so it
if (pageCount < LocalPages) {
if (total == totalItems) {
// Execute some code after 8 seconds have passed
Handler handler = new Handler();
handler.postDelayed(new Runnable()
{
public void run()
{
listView.addFooterView(footer);
OFFSET = pageCount * 10 ;
//Log.e("","After OFFSET pageCount =" + pageCount + " OFFSET value ="+OFFSET);
List<All_Post> allDesc = dbhelper.getAllDescriptions(OFFSET);
for (All_Post all_Post : allDesc)
{
descArray.add(all_Post);
}
if(adapter != null)
{
adapter.notifyDataSetChanged();
listView.setAdapter(adapter);
listView.setSelection(totalItems);
pageCount += 1;
Log.e(""," pageCount =" + pageCount + " LocalPages="+LocalPages);
}
}
}, 8000);
}
} else {
Log.e("hide footer", "footer hide");
listView.removeFooterView(footer);
}
}
});
Thanks in advanced .

Show number of Notifications on the side navigation menu

I am using Horizontal ScrollView to get facebook like side navigation
Like this:
But how to show that "2" beside the Event item in the menu?
In my application i am using a ViewUtil class to get this menu:
public class ViewUtils {
private ViewUtils() {
}
public static void setViewWidths(View view, View[] views) {
int w = view.getWidth();
int h = view.getHeight();
for (int i = 0; i < views.length; i++) {
View v = views[i];
v.layout((i + 1) * w, 0, (i + 2) * w, h);
printView("view[" + i + "]", v);
}
}
public static void printView(String msg, View v) {
System.out.println(msg + "=" + v);
if (null == v) {
return;
}
System.out.print("[" + v.getLeft());
System.out.print(", " + v.getTop());
System.out.print(", w=" + v.getWidth());
System.out.println(", h=" + v.getHeight() + "]");
System.out.println("mw=" + v.getMeasuredWidth() + ", mh="
+ v.getMeasuredHeight());
System.out.println("scroll [" + v.getScrollX() + "," + v.getScrollY()
+ "]");
}
public static void initListView(Context context, ListView listView,
String prefix, int numItems, int layout) {
// By using setAdpater method in listview we an add string array in
// list.
String[] arr = new String[numItems];
arr[0] = "Feed";
arr[1] = "Friends";
arr[2] = "Notifications";
arr[3] = "Feedback";
arr[4] = "Logout";
listView.setAdapter(new ArrayAdapter<String>(context, layout, arr));
}
}
and set the adapter like this in the Activity:
ViewUtils.initListView(this, myListView, "Menu ", 5,
android.R.layout.simple_list_item_1);
I what my "Notifications" Text to be something like "Notification n" where n is like the "2" in the above pic. I tried to use Spannable String but i cannot set the Spannable String to the String Array "arr"
Thank You
I'm assuming those categories (News Feed, Messages,...) are items of a ListView.
Also, for displaying that "2" I'm assuming you will need a custom adapter.
In this case you just need to add a TextView to your row XML file and set the appropriate value in the getView() method of your custom Adapter, or, if you are create the TextView programaticaly in the getView() method.

Categories

Resources