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