Click here to Skip to main content
15,879,053 members
Home / Discussions / Android
   

Android

 
SuggestionRe: put orders from android and receive from PHP Pin
Richard MacCutchan22-Jun-18 21:27
mveRichard MacCutchan22-Jun-18 21:27 
GeneralRe: put orders from android and receive from PHP Pin
AndroidVH22-Jun-18 21:58
AndroidVH22-Jun-18 21:58 
GeneralRe: put orders from android and receive from PHP Pin
Richard MacCutchan22-Jun-18 23:14
mveRichard MacCutchan22-Jun-18 23:14 
SuggestionRe: put orders from android and receive from PHP Pin
David Crow24-Jun-18 10:36
David Crow24-Jun-18 10:36 
GeneralRe: put orders from android and receive from PHP Pin
AndroidVH24-Jun-18 18:58
AndroidVH24-Jun-18 18:58 
QuestionHow to broadcast audio 3gp format over wifi converting audio file in udp packets? Pin
Member 1114560021-Jun-18 18:36
Member 1114560021-Jun-18 18:36 
SuggestionRe: How to broadcast audio 3gp format over wifi converting audio file in udp packets? Pin
Richard MacCutchan21-Jun-18 21:03
mveRichard MacCutchan21-Jun-18 21:03 
QuestionFetching JSON data in recyclerview using retrofit and implement scroll to load or infinitescroll Pin
Arindam Mukherjee20-Jun-18 19:29
Arindam Mukherjee20-Jun-18 19:29 
I was trying to fetch JSON data into a RecyclerView using Retrofit 2. I also implemented pagination. Now for testing, I changed the JSON URL as if it will only show `5`items per page. The page number can be changed by adding "&page=`PAGE#`" at the end of the JSON URL (where PAGE# is integer value starting from 1 and if no Page no is mentioned, it will show by default the first page).

Problem: I have successfully added every page into the Recyclerview. But, it is adding the last page items twice, sometimes it is adding 3 times. Like this.
I am unable to find the problem. The step by step debugging does not help. Please help me. I am learning these so if you help me I would really appreciate it.

The JSON looks as follows:


Java
[{
        "id": 369,
        "guid": {
          "rendered": "URL?p=369"
        },
        "title": {
          "rendered": "Shudder"
        },
        "content": {
          "rendered": "<p>Shaking of body caused by fear.</p>\n<p>ভয়ের কাঁপুনি</p>\n<p> </p>\n",
          "protected": false
        },
        "post_categories": [
          "English",
          "Father's Help",
          "Madhyamik",
          "Prose",
          "Seen",
          "Word Nest"
        ]
      },
      {
        "id": 548,
        "guid": {
          "rendered": "URL?p=548"
        },
        "title": {
          "rendered": "Swami went ______ school feeling that he was ______ worst boy ______ earth."
        },
        "content": {
          "rendered": "<p>Swami went to school feeling that he was the worst boy on earth.</p>\n",
          "protected": false
        },
        "post_categories": [
          "Articles and Prepositions",
          "English",
          "Grammar",
          "Madhyamik"
        ]
      },
      {
        "id": 528,
        "guid": {
          "rendered": "URL?p=528"
        },
        "title": {
          "rendered": "Teacher said "Explain the law of gravitation"."
        },
        "content": {
          "rendered": "<p>Teacher ordered to explain the law of gravitation.</p>\n",
          "protected": false
        },
        "post_categories": [
          "English",
          "Grammar",
          "Madhyamik",
          "Narration"
        ]
      },
      {
        "id": 552,
        "guid": {
          "rendered": "URL?p=552"
        },
        "title": {
          "rendered": "Test Post "Image""
        },
        "content": {
          "rendered": "<p><img src=\"http://latex.codecogs.com/gif.latex?x^{2}+2xy+y^{2}&space;=&space;45\" alt=\"x^{2}+2xy+y^{2} = 45\" align=\"absmiddle\" /></p>\n<p> </p>\n<p><img src=\"http://aseducationsolution.com/wp-content/uploads/2018/06/blur-1868068_1920-150x150.jpg\" alt=\"\" width=\"150\" height=\"150\" class=\"alignnone wp-image-312 size-thumbnail\" /></p>\n<p> </p>\n<p>let us take  <img src=\"http://latex.codecogs.com/gif.latex?\\inline&space;\\fn_cm&space;\\small&space;\\left&space;(&space;a+b&space;\\right&space;)^{3}&space;+&space;\\alpha&space;\\lambda&space;\\varepsilon&space;\\Delta&space;ABC\" alt=\"\\inline \\fn_cm \\small \\left ( a+b \\right )^{3} + \\alpha \\lambda \\varepsilon \\Delta ABC\" align=\"absmiddle\" /></p>\n<p> </p>\n<p>another example  <img src=\"http://latex.codecogs.com/gif.latex?\\inline&space;\\small&space;a^{3}+b^{3}&space;=&space;123\" alt=\"\\inline \\small a^{3}+b^{3} = 123\" align=\"absmiddle\" />   check alignment is correct or not.</p>\n<p> </p>\n<p><img src=\"http://latex.codecogs.com/svg.latex?\\dpi{120}&space;\\small&space;\\frac{a}{b}+2c\" alt=\"\\dpi{120} \\small \\frac{a}{b}+2c\" align=\"absmiddle\" /> SVG</p>\n<p><img src=\"http://latex.codecogs.com/gif.latex?\\dpi{120}&space;\\small&space;\\sum&space;a+b+c+....\" alt=\"\\dpi{120} \\small \\sum a+b+c+....\" align=\"absmiddle\" /> GIF</p>\n<p> </p>\n<p>Equation example</p>\n<p> </p>\n<p> </p>\n",
          "protected": false
        },
        "post_categories": [
          "English",
          "Madhyamik"
        ]
      },
      {
        "id": 514,
        "guid": {
          "rendered": "URL?p=514"
        },
        "title": {
          "rendered": "Time when Swami complained of a headache _________?"
        },
        "content": {
          "rendered": "<p>9 A.M.</p>\n",
          "protected": false
        },
        "post_categories": [
          "English",
          "Father's Help",
          "Fill in from Text",
          "Madhyamik",
          "Prose",
          "Seen"
        ]
      }
    ]


Now, when there are no posts available as per the PAGE# of JSON URL, it will show the following JSON:


Java
{
      "code": "rest_post_invalid_page_number",
      "message": "The page number requested is larger than the number of pages available.",
      "data": {
        "status": 400
      }
    }


Now, if you look at my code for the fragment:

Java
private RecyclerView recyclerView;
    private ProgressBar progressBar;
    private LinearLayoutManager mLayoutManager;
    private ArrayList < Model > list;
    private RecycleAdapter adapter;
    private View rootView;
    private int pageNo = 2;
    ProgressBar progress;
    public String url = RetrofitArrayAPI.baseURL + RetrofitArrayAPI.EngHomeKey;


    public static List < WPPost > mListPost;
    Boolean isScrolling = false;
    int currentItems, scrolledItems, totalItems;


    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

      rootView = inflater.inflate(R.layout.search_englishhome, container, false);

      recyclerView = (RecyclerView) rootView.findViewById(R.id.postList);
      progressBar = (ProgressBar) rootView.findViewById(R.id.progressBar);
      mLayoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
      recyclerView.setLayoutManager(mLayoutManager);
      DividerItemDecoration itemDecor = new DividerItemDecoration(Objects.requireNonNull(getActivity()), mLayoutManager.getOrientation());
      recyclerView.addItemDecoration(itemDecor);
      list = new ArrayList < > ();
      progress = (ProgressBar) rootView.findViewById(R.id.recyclerprogress);
      progress.setVisibility(View.GONE);
      adapter = new RecycleAdapter(list, getActivity());
      recyclerView.setAdapter(adapter);
      //Get Retrofit
      getRetrofit();
      recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {

        @Override
        public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
          super.onScrollStateChanged(recyclerView, newState);
          if (newState == AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL) {
            isScrolling = true;
          }
        }

        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
          super.onScrolled(recyclerView, dx, dy);
          currentItems = mLayoutManager.getChildCount();
          totalItems = mLayoutManager.getItemCount();
          scrolledItems = mLayoutManager.findFirstVisibleItemPosition();

          if (isScrolling = (currentItems + scrolledItems == totalItems)) {
            isScrolling = false;
            url = RetrofitArrayAPI.baseURL + RetrofitArrayAPI.EngHomeKey + "&page=" + pageNo;

            progress.setVisibility(View.VISIBLE);
            if (mListPost != null) {
              getRetrofit();
            } else {

              progress.setVisibility(View.GONE);
            }

          }

        }
      });

      return rootView;

    }


    public void getRetrofit() {

      final Retrofit retrofit = new Retrofit.Builder()
        .baseUrl(RetrofitArrayAPI.baseURL)
        .addConverterFactory(GsonConverterFactory.create())
        .build();

      RetrofitArrayAPI service = retrofit.create(RetrofitArrayAPI.class);


      final Call < List < WPPost >> call = service.getPostInfo(url);
      call.enqueue(new Callback < List < WPPost >> () {
        @Override
        public void onResponse(Call < List < WPPost >> call, Response < List < WPPost >> response) {


          Log.e("EnglishHome", "Response" + response.body());

          mListPost = response.body();
          progressBar.setVisibility(View.GONE);


          if (response.body() != null) {
            pageNo++;
            for (int i = 0; i < response.body().size(); i++) {
              String tempCode = response.body().get(i).getCode();
              int tempID = response.body().get(i).getId();
              String tempTitle = response.body().get(i).getTitle().getRendered();
              tempTitle = tempTitle.replace(""", "\"");
              tempTitle = tempTitle.replace(""", "\"");
              String tempContent = response.body().get(i).getContent().getRendered();
              List < String > catitemnames = response.body().get(i).getPostCategories();

              catitemnames.remove("Madhyamik");
              catitemnames.remove("English");
              catitemnames.remove("Grammar");
              catitemnames.remove("Seen");
              catitemnames.remove("Prose");
              catitemnames.remove("Poem");

              String categorynames = catitemnames.toString();
              categorynames = categorynames.substring(1, categorynames.length() - 1);
              if (tempCode != null) {
                response.body().clear();
                list.clear();
                isScrolling = false;
                mListPost.clear();
                return;
              } else {
                list.add(new Model(tempID, tempTitle, tempContent, categorynames));

              }

            }
            mListPost.clear();
            progress.setVisibility(View.GONE);

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

        }

        @Override
        public void onFailure(Call < List < WPPost >> call, Throwable t) {

        }


      });

    }


    }


My RecyclerView Adapter looks like:

Java
public class RecycleAdapter extends RecyclerView.Adapter {

      private ArrayList < Model > dataset;
      private Context mContext;

      public RecycleAdapter(ArrayList < Model > mList, Context context) {

        this.dataset = mList;
        this.mContext = context;

      }

      public static class ListTypeViewHolder extends RecyclerView.ViewHolder {


        TextView title, categories;
        RelativeLayout relativeLayout;


        ListTypeViewHolder(View itemView) {
          super(itemView);

          this.title = (TextView) itemView.findViewById(R.id.texttitlesofrv);
          this.categories = (TextView) itemView.findViewById(R.id.textcategoryrv);
          this.relativeLayout = (RelativeLayout) itemView.findViewById(R.id.recyclerrow);
        }
      }

      @NonNull
      @Override
      public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_item, parent, false);

        return new ListTypeViewHolder(view);
      }

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

        ((ListTypeViewHolder) holder).title.setText(object.title);
        ((ListTypeViewHolder) holder).categories.setText(object.categoriesnames);


        ((ListTypeViewHolder) holder).relativeLayout.setOnClickListener(new View.OnClickListener() {
          @Override
          public void onClick(View v) {

            Intent intent = new Intent(mContext, FullPostView.class);
            intent.putExtra("itemPosition", holder.getAdapterPosition());
            intent.putExtra("postID", object.postid);
            intent.putExtra("postTitle", object.title);
            intent.putExtra("postContent", object.content);

            mContext.startActivity(intent);
          }
        });



      }


      @Override
      public int getItemViewType(int position) {
        return position;
      }

      @Override
      public long getItemId(int position) {
        return position;
      }

      @Override
      public int getItemCount() {

        return dataset.size();
      }
    }



WPPOST POJO:


Java
public class WPPost {

      @SerializedName("code")
      @Expose
      private String code;
      @SerializedName("id")
      @Expose
      private Integer id;
      @SerializedName("guid")
      @Expose
      private Guid guid;
      @SerializedName("title")
      @Expose
      private Title title;
      @SerializedName("content")
      @Expose
      private Content content;
      @SerializedName("post_categories")
      @Expose
      private List < String > postCategories = null;

      public Integer getId() {
        return id;
      }

      public void setId(Integer id) {
        this.id = id;
      }

      public Guid getGuid() {
        return guid;
      }

      public void setGuid(Guid guid) {
        this.guid = guid;
      }

      public Title getTitle() {
        return title;
      }

      public void setTitle(Title title) {
        this.title = title;
      }

      public Content getContent() {
        return content;
      }

      public void setContent(Content content) {
        this.content = content;
      }

      public List < String > getPostCategories() {
        return postCategories;
      }

      public void setPostCategories(List < String > postCategories) {
        this.postCategories = postCategories;
      }
      public String getCode() {
        return code;
      }

      public void setCode(String code) {
        this.code = code;
      }

    }



MODEL Class:



Java
public class Model {

      public int postid;
      public String title;
      public String content;
      public String categoriesnames;


      public Model(int mID, String mTitle, String mContent, String mCategorynames) {

        this.postid = mID;
        this.title = mTitle;
        this.content = mContent;
        this.categoriesnames = mCategorynames;

      }

}



Thank you in advance.
QuestionCurrent Android Studio // Is it 2017 ? Pin
C-P-User-313-Jun-18 22:41
C-P-User-313-Jun-18 22:41 
AnswerRe: Current Android Studio // Is it 2017 ? Pin
Richard Deeming14-Jun-18 2:36
mveRichard Deeming14-Jun-18 2:36 
AnswerRe: Current Android Studio // Is it 2017 ? Pin
Ganza Charles20-Jun-18 22:42
Ganza Charles20-Jun-18 22:42 
GeneralRe: Current Android Studio // Is it 2017 ? Pin
C-P-User-311-Nov-18 20:46
C-P-User-311-Nov-18 20:46 
Question(ANDROID) -->How can data be send from the run method of a thread in a service to a client using Handler and Messeger? Pin
Member 119110659-Jun-18 22:36
Member 119110659-Jun-18 22:36 
AnswerRe: (ANDROID) -->How can data be send from the run method of a thread in a service to a client using Handler and Messeger? Pin
Richard MacCutchan10-Jun-18 4:18
mveRichard MacCutchan10-Jun-18 4:18 
GeneralRe: (ANDROID) -->How can data be send from the run method of a thread in a service to a client using Handler and Messeger? Pin
Member 1191106510-Jun-18 9:24
Member 1191106510-Jun-18 9:24 
GeneralRe: (ANDROID) -->How can data be send from the run method of a thread in a service to a client using Handler and Messeger? Pin
Richard MacCutchan10-Jun-18 22:06
mveRichard MacCutchan10-Jun-18 22:06 
SuggestionRe: (ANDROID) -->How can data be send from the run method of a thread in a service to a client using Handler and Messeger? Pin
David Crow11-Jun-18 2:16
David Crow11-Jun-18 2:16 
QuestionAddition,Sub,Mul & divide issue Pin
Member 1126111131-May-18 2:22
Member 1126111131-May-18 2:22 
AnswerRe: Addition,Sub,Mul & divide issue Pin
Richard MacCutchan2-Jun-18 2:44
mveRichard MacCutchan2-Jun-18 2:44 
QuestionXamarin WebView please help. Pin
Member 1335044424-May-18 6:03
Member 1335044424-May-18 6:03 
AnswerRe: Xamarin WebView please help. Pin
David Crow24-May-18 9:34
David Crow24-May-18 9:34 
GeneralRe: Xamarin WebView please help. Pin
Member 1335044425-May-18 11:07
Member 1335044425-May-18 11:07 
QuestionRe: Xamarin WebView please help. Pin
David Crow28-May-18 15:59
David Crow28-May-18 15:59 
QuestionAndroid code obfuscating Pin
AndroidVH21-May-18 23:14
AndroidVH21-May-18 23:14 
SuggestionRe: Android code obfuscating Pin
Jochen Arndt21-May-18 23:54
professionalJochen Arndt21-May-18 23:54 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.