Value incremented when Scroll to bottom of listview? - android

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);
}
}

Related

Load Next Page Posts With RecycleView

i am very new as Android Developers, and i am making app with json and retrofit to fetch posts from wordpress, i can see latest 10 posts but i want to load next 10 while scroll down, i use this code but it load same 10 posts again and again , this is my code in MainActivity
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener()
{
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy)
{
// Log.e("...", " onscroll dx " + dx +" dy "+ dy);
try{
if(dy > 0) //check for scroll down
{
visibleItemCount = mLayoutManager.getChildCount();
totalItemCount = mLayoutManager.getItemCount();
pastVisiblesItems = mLayoutManager.findFirstVisibleItemPosition();
if (loading)
{ // Log.e(TAG, " page count lock "+PageCountLock);
progressBar.setVisibility(View.VISIBLE);
if ( pastVisiblesItems >= (totalItemCount/3) ){
Log.e(TAG," on scroll visible - "+ visibleItemCount+" total "+ totalItemCount+" pastvisible "+pastVisiblesItems );
getRetrofit( );
}
if ( (visibleItemCount + pastVisiblesItems) >= totalItemCount)
{
// loading = false;
Log.e("...", "Last Item readed in list **** ");
}
}
}
}catch (Exception e){
Log.e(TAG,"scrooll action "+ e.toString());
}
}
});
please can you tell me how to fetch next posts ?
this is to get posts from Retrofit
public void getRetrofit(){
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(baseURL)
.addConverterFactory(GsonConverterFactory.create())
.build();
RetrofitArrayApi service = retrofit.create(RetrofitArrayApi.class);
Call<List<WPPost>> call = service.getPostInfo();
call.enqueue(new Callback<List<WPPost>>() {
#Override
public void onResponse(Call<List<WPPost>> call, Response<List<WPPost>> response) {
Log.e("mainactivyt", " response "+ response.body());
mListPost = response.body();
progressBar.setVisibility(View.GONE);
for (int i=0; i<response.body().size();i++){
Log.e("main ", " title "+ response.body().get(i).getTitle().getRendered() + " "+
response.body().get(i).getId());
String tempdetails = response.body().get(i).getExcerpt().getRendered().toString();
tempdetails = tempdetails.replace("<p>","");
tempdetails = tempdetails.replace("</p>","");
tempdetails = tempdetails.replace("[…]","");
list.add( new Model( Model.IMAGE_TYPE, response.body().get(i).getTitle().getRendered(),
tempdetails,
response.body().get(i).getLinks().getWpFeaturedmedia().get(0).getHref()) );
}
adapter.notifyDataSetChanged();
}
#Override
public void onFailure(Call<List<WPPost>> call, Throwable t) {
}
});
}
public static List<WPPost> getList(){
return mListPost;
}

Pagination using Android Firebase

I can display all the books from FireBase Database, but once I use pagination to load 10 books by 10, I have nothing displayed on my screen and I have no error in my Logcut.
Please help me to understand where I'm wrong in my code.
private boolean isLoading;
int mPageEndOffset = 0;
int mPageLimit = 10;
//OnCreate
listAdapter = new FeedListAdapter(getActivity(), feedItems);
listView.setAdapter(listAdapter);
listView.setOnItemClickListener(myClickListener);
listView.setOnScrollListener(new AbsListView.OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView absListView, int i) {
}
#Override
public void onScroll(AbsListView absListView, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
if (mPageEndOffset != 0) {
int lastInScreen = firstVisibleItem + visibleItemCount;
if ((lastInScreen == totalItemCount) && !(isLoading)) {
loadData();
}
}
}
});
//Load More Data from FireBase Database
private void loadData() {
ref.orderByChild("date_creation").limitToLast(mPageLimit).startAt(mPageEndOffset).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
isLoading = true;
for (DataSnapshot dataSnap : dataSnapshot.getChildren()) {
Book valueBook = dataSnap.getValue(Book.class);
keyId = dataSnap.getKey();
String titreLivreToDisplay = valueBook.getNom_livre();
String descLivreToDisplay = valueBook.getDesc_livre();
String prixLivreToDisplay = valueBook.getPrix_livre();
String timeToDisplay = valueBook.getDate_creation();
String filePathToDiplay = valueBook.getChemin_image();
String villeToDisplay = valueBook.getVille_livre();
String typeAnnToDisplat = valueBook.getType_annonce_selected();
String catAnnToDisplay = valueBook.getCat_selected();
}
valueBook.setNom_livre(titreLivreToDisplay);
valueBook.setDesc_livre(descLivreToDisplay);
valueBook.setPrix_livre(prixLivreToDisplay);
valueBook.setDate_creation(timeToDisplay);
valueBook.setChemin_image(filePathToDiplay);
valueBook.setVille_livre(villeToDisplay);
valueBook.setType_annonce_selected(typeAnnToDisplat);
valueBook.setCat_selected(catAnnToDisplay);
valueBook.setKeyIdNode(keyId);
feedItems.add(valueBook);
}
if (feedItems != null && feedItems.size() != 0) {
Collections.reverse(feedItems);
listAdapter.notifyDataSetChanged();
mPageEndOffset += mPageLimit;
isLoading = false;
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
String message = "Server error. Refresh page";
Toast.makeText(getActivity(), message, Toast.LENGTH_SHORT).show();
}
});
}
You use wrong startAt value for your date_creation field. startAt value should be formatted as date_creation.(e.g. now you have startAt=5, but date_creation=1499705022735 and they can not be compared. You should have startAt=1499705022735).
Try to use something like:
private long offset = 0;
private int limit = 10;
private boolean isLastPage = false;
if (!isLastPage) loadData(offset, limit);
//Condition for loaded data
if (books.size() > 0) {
if (books.size() < limit - 1) isLastPage = true;
else {
offset = books.get(books.size() - 1).getDate_creation();
books = books.subList(0, books.size() - 1);
}
} else isLastPage = true;
//for your firebase reference
ref.orderByChild("createdAt").startAt(offset).limitToFirst(limit);
Keep the value of the field date_creation of the last loaded list item, this will be your field startAt for the next request.
It does not look very nice, but this is the only possible solution for such cases in Firebase and it works.

How to move scroll of ListView on to the new data added in ListView in Android

I am developing an app in which I have a listview in which 5 data are visible to user.when I scroll bottom of listview and a progress bar at the bottom of listview is visible to me and server request is send at this point and 5 more data are added in data set, Here I want to make this new data visible to user when added in data set. i.e. move scroll position on new data set.
code:-
#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);
}
}
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, m_DealListingURL, jsonObject, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.i(TAG, "Server Response:-" + response);
if (mSwipeRefresh.isRefreshing()) {
mSwipeRefresh.setRefreshing(false);
}
try {
int nResultCodeFromServer = Integer.parseInt(response.getString("resultcode"));
if (nResultCodeFromServer == CStaticVar.m_kTRANSACTION_SUCCESS) {
JSONArray posts = response.optJSONArray("dealList");// GETTING DEAL LIST
for (int i = 0; i < posts.length(); i++) {
JSONObject post = posts.getJSONObject(i);// GETTING DEAL AT POSITION AT I
item = new CDealAppDatastorage();// object create of DealAppdatastorage
item.setM_szHeaderText(post.getString("dealname"));//getting deal name
item.setM_szsubHeaderText(post.getString("dealcode"));// getting deal code
item.setM_szDealValue(post.getString("dealvalue"));
if (!s_oDataset.contains(item)) {
s_oDataset.add(item);
}
}
m_oAdapter.notifyDataSetChanged();
arrayCount = posts.length();
int add = CLastCountData.getInstance().getS_szLastCount() + arrayCount;
CLastCountData.getInstance().setS_szLastCount(add);
Log.e(TAG, "ArrayCount::" + arrayCount);
m_ListView.removeFooterView(mFooter);
}
Just use listView.setSelection(position of item you want to scroll)
Following code will help you to maintain the scroll position of your listview:
First off all you have to get the current child position of listview from below code:
// this code should be written before updating adapter in your listview
int lastViewedPosition = listView.getFirstVisiblePosition();
//get offset of first visible view
View v = listView.getChildAt(0);
int topOffset = (v == null) ? 0 : v.getTop();
then after updating your data in adapter you have to call this:
listView.setSelectionFromTop(lastViewedPosition, topOffset);
Like in your code:
Log.i(TAG, "Server Response:-" + response);
if (mSwipeRefresh.isRefreshing()) {
mSwipeRefresh.setRefreshing(false);
}
try {
int nResultCodeFromServer = Integer.parseInt(response.getString("resultcode"));
if (nResultCodeFromServer == CStaticVar.m_kTRANSACTION_SUCCESS) {
int lastViewedPosition = listView.getFirstVisiblePosition();
//get offset of first visible view
View v = listView.getChildAt(0);
int topOffset = (v == null) ? 0 : v.getTop();
JSONArray posts = response.optJSONArray("dealList");// GETTING DEAL LIST
for (int i = 0; i < posts.length(); i++) {
JSONObject post = posts.getJSONObject(i);// GETTING DEAL AT POSITION AT I
item = new CDealAppDatastorage();// object create of DealAppdatastorage
item.setM_szHeaderText(post.getString("dealname"));//getting deal name
item.setM_szsubHeaderText(post.getString("dealcode"));// getting deal code
item.setM_szDealValue(post.getString("dealvalue"));
if (!s_oDataset.contains(item)) {
s_oDataset.add(item);
}
}
m_oAdapter.notifyDataSetChanged();
listView.setSelectionFromTop(lastViewedPosition, topOffset);
arrayCount = posts.length();
int add = CLastCountData.getInstance().getS_szLastCount() + arrayCount;
CLastCountData.getInstance().setS_szLastCount(add);
Log.e(TAG, "ArrayCount::" + arrayCount);
m_ListView.removeFooterView(mFooter);

How to implement ListView Pagination from SQLite database in 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

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 .

Categories

Resources