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;
}
Related
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()); } }
i am noob and want to make app with json api and WordPress as backend. i can fetch the posts and it works fine untill first page posts, when i click on each post i can see the post detail as well, but on next page post or when scroll to next page, click doesn't work and app crashes,but i can see the post images as well in next page but not post details. i have searched lot but nothing seems to work for me. the error i got is this:
java.lang.IndexOutOfBoundsException: Index: 11, Size: 10
when i click on 12th post i see this
java.lang.IndexOutOfBoundsException: Index: 12, Size: 10
i don't know how can i make size more than 10 as well..
i have searched lot on google but did not get any solution..
this is my code to load more posts
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
if (dy > 0) { //check for scroll down
visibleItemCount = mLayoutManager.getChildCount();
totalItemCount = mLayoutManager.getItemCount();
pastVisiblesItems = mLayoutManager.findFirstVisibleItemPosition();
if (loading) {
if ((visibleItemCount + pastVisiblesItems) >= totalItemCount) {
loading = false;
Log.v("...", "Last Item Wow !");
// Do pagination.. i.e. fetch new data
yourURL = "https://punjabidharti.com/wp-json/wp/v2/posts/categories=4514&per_page=10" + "&page=" + pageNo++;
getRetrofit();
recyclerView.setAdapter(adapter);
and GetRetrofit
public void getRetrofit(){
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(baseURL)
.addConverterFactory(GsonConverterFactory.create())
.build();
RetrofitArrayApi service = retrofit.create(RetrofitArrayApi.class);
String yourURl = yourURL.replace(baseURL,"");
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.e("mainactivyt", " response "+ response.body());
mListPost = response.body();
progressBar.setVisibility(View.GONE);
if (response.body() != null) {
for (int i = 0; i < response.body().size(); i++ ) {
Log.e("size", list.size() + "");
System.out.println("The shortest word i is:" + 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).getImages().getMedium()));
}
progressBar.setVisibility(View.GONE);
} else {
progressBar.setVisibility(View.GONE);
}
adapter.notifyDataSetChanged();
change loop:
for (int i = 0; i <= mListPost .size(); i++ )
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.
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;
}
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);
}
}