0

i need your help badly , i am working on it for more than week still couldn't find the solution.. i make app with json api Retrofit and Wordpress as backend, first 10 posts works smooth, when i click on those posts i can see the post details, but when i scroll to get more posts, i can see the posts with featured image , but when i click on it i see this error:

Caused by: java.lang.IndexOutOfBoundsException: Index: 10, Size: 10
at java.util.ArrayList.get(ArrayList.java:437)
at com.punjabidharti.myapplication.PostDetails.onCreate(PostDetails.java:30)

and this is how i get more posts on scroll

recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {

        @Override
        public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
            super.onScrollStateChanged(recyclerView, newState);
        }
        @Override
        public void onScrolled(RecyclerView recyclerView, int position, 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&page=2";
                        getRetrofit();

                         loading = true;
                    }
                }
            }
        }
    });

and this is how i get data from retrofit: i use Dyanmic Url

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("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("[&hellip;]", "");
                    list.add(new Model(Model.IMAGE_TYPE, response.body().get(i).getTitle().getRendered(),
                            tempdetails,
                            response.body().get(i).getLinks().getWpAttachment().get(0).getHref()));
                }

                progressBar.setVisibility(View.GONE);
            } else {
                progressBar.setVisibility(View.GONE);
            }


            adapter.notifyDataSetChanged();
        }
        @Override
        public void onFailure(Call<List<WPPost>> call, Throwable t) {
        }
    });

this is bindviewholder in adapter

 public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int position) {
    final Model object = dataset.get(position);

    ( (ImageTypeViewHolder) holder).title.setText( object.title );
    ( (ImageTypeViewHolder) holder).subtitle.setText( object.subtitle );




    Glide.with(mContext)
            .load(object.Image)
            .dontAnimate()
            .placeholder(R.drawable.icon)
            .into(((ImageTypeViewHolder) holder).imageView);




    ( (ImageTypeViewHolder) holder).title.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(mContext, PostDetails.class);
            intent.putExtra("itemPosition", position);
            mContext.startActivity(intent);
        }
    });
    ( (ImageTypeViewHolder) holder).subtitle.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(mContext, PostDetails.class);
            intent.putExtra("itemPosition", position);
            mContext.startActivity(intent);
        }
    });
    ( (ImageTypeViewHolder) holder).imageView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(mContext, PostDetails.class);
            intent.putExtra("itemPosition", position);
            mContext.startActivity(intent);
        }
    });



    /// dataset.get(position)
}

this is PostDetails Class

  @Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.post);
    Intent i = getIntent();
    int position = i.getExtras().getInt("itemPosition");
    Log.e("PostDetails ", "title is " + MainActivity.mListPost.get(position).getTitle().getRendered());
    this.title = (TextView) findViewById(R.id.title);
    title.setText(Html.fromHtml(MainActivity.mListPost.get(position).getTitle().getRendered()));
    String data = String.valueOf((Html.fromHtml(MainActivity.mListPost.get(position).getContent().getRendered())));

    WebView webview = (WebView)this.findViewById(R.id.postwebview);
    webview.getSettings().setJavaScriptEnabled(true);
    webview.loadData(data, "text/html; charset=utf-8", "UTF-8");

i found this error in Debug:

enter image description here

please help

  • Does this answer your question? [What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?](https://stackoverflow.com/questions/5554734/what-causes-a-java-lang-arrayindexoutofboundsexception-and-how-do-i-prevent-it) – Gokul Nath KP Mar 28 '21 at 10:10
  • no , sir , this does not help me @GokulNathKP – Punjabi Dharti Mar 28 '21 at 10:30

1 Answers1

1

You are saying that 10 items in the list are displayed without any problem. Indexes from 0 to 9 seem full. However, when you try to access index 10, you will get IndexOutOfBoundsException.

In this case, you may not have more than 10 items in your list. Therefore, your lists may not load properly. Please first check the directory for the list you are using the list.get() method. As follows:

if (index < myList.size()) (
    // there is a index
} else {
     // index does not exist
}

You can add a log in the "else" step to see where the error is.


I think you can use a library like in the example for the structure you are trying to use. I have not used this library before, I do not accept any responsibility. I recommend your research. https://github.com/pwittchen/InfiniteScroll


Also can you try the code below? Else I recommend debugging the OnCreate method in case the code is working on your guy.

@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.post);

    this.title = (TextView) findViewById(R.id.title);
    WebView webview = (WebView)this.findViewById(R.id.postwebview);
    webview.getSettings().setJavaScriptEnabled(true);

    Intent i = getIntent();
    int position = i.getExtras().getInt("itemPosition");

    if (position < MainActivity.mListPost.size()) {

        WPPost post = MainActivity.mListPost.get(position);

        title.setText(Html.fromHtml(post.getTitle().getRendered()));
        
        String data = String.valueOf((Html.fromHtml(post.getContent().getRendered()))); 
        webview.loadData(data, "text/html; charset=utf-8", "UTF-8");
    } else {
        Log.e("PostDetails", "No index. List size: " + MainActivity.mListPost.size());
    }
}
Ümit Bülbül
  • 512
  • 2
  • 15
  • i can see the all posts, even when i scroll i can see the new posts as well, but when i click on 11th post i got that error – Punjabi Dharti Mar 28 '21 at 11:55
  • Can you share the PostDetails class? At least the onCreate() method. – Ümit Bülbül Mar 28 '21 at 12:02
  • I updated my answer. Can you try the onCreate part I posted on PostDetails? – Ümit Bülbül Mar 28 '21 at 12:40
  • still the same issue Caused by: java.lang.IndexOutOfBoundsException: Index: 11, Size: 10 at java.util.ArrayList.get(ArrayList.java:437) at com.punjabidharti.myapplication.PostDetails.onCreate(PostDetails.java:33) – Punjabi Dharti Mar 28 '21 at 12:44
  • We did not remove the logging code before the control. I updated the answer. Can you make the last change too? – Ümit Bülbül Mar 28 '21 at 15:26
  • now postdetails.class open but no post details and titie of post :(( – Punjabi Dharti Mar 28 '21 at 15:41
  • i can see this in log "E/PostDetails: No index. List size: 10" – Punjabi Dharti Mar 28 '21 at 15:47
  • We removed the Crash. Now: I think you can pull information successfully with Retrofit. But I guess you didn't assign the information coming for MainActivity.mListPost? You should review the onResponse method inside with this approach. – Ümit Bülbül Mar 28 '21 at 15:54
  • as i mentioned before , first 9 posts works , but next not.. – Punjabi Dharti Mar 28 '21 at 15:57
  • can you please tell me how to do that ? please ? – Punjabi Dharti Mar 28 '21 at 16:03
  • Please review the text below first if you are not familiar with "debug": https://developer.android.com/studio/debug 1) Then debug "onResponse" to make sure the data comes in as you scroll the list. 2) Make sure that you have properly added the new data that comes later to the list you want to use. Check this with debug. After these steps I think you will see where the error is. – Ümit Bülbül Mar 29 '21 at 06:12
  • Didn't you check the other options I mentioned? Is the data from the service loaded correctly into the list you want to use? – Ümit Bülbül Mar 29 '21 at 07:38
  • please check my updated question, i have posted image from debug – Punjabi Dharti Mar 29 '21 at 07:43