2016-03-31 10 views
0

Ich benutze Recyclerview, in dem ich mehr Daten vom Server mit Json abrufen. Szenario ist so etwas: - Auf den ersten Treffer möchte ich 5 Seite in der Liste anzeigen und eine Schaltfläche mehr anzeigen Recyclerview ist dort, wenn Benutzer klicken Sie auf mehr Schaltfläche auf zweiten Treffer anzeigen 5 mehr pages.how kann ich tunWie lade ich mehr Daten in Recyclerview in Android

hier meine init():

public void init() { 
    mProgressBar = (ProgressBar) m_Main.findViewById(R.id.progressBar1); 
    mProgressBar.setVisibility(View.GONE); 

    m_showMore = (AppCompatButton) m_Main.findViewById(R.id.show_more); 
    m_showMore.setBackgroundColor(Color.TRANSPARENT); 
    m_showMore.setVisibility(View.GONE); 
    // Getting the string array from strings.xml 
    m_n_FormImage = new int[]{ 
      R.drawable.amazon, 
      R.drawable.whatsapp, 
      R.drawable.zorpia, 
      R.drawable.path, 
      R.drawable.app_me, 
      R.drawable.evernote, 
      R.drawable.app_me}; 

    m_RecyclerView = (RecyclerView) m_Main.findViewById(R.id.my_recycler_view);//finding id of recyclerview 
    m_RecyclerView.setItemAnimator(new DefaultItemAnimator());//setting default animation to recyclerview 
    m_RecyclerView.setHasFixedSize(true);//fixing size of recyclerview 
    mLayoutManager = new LinearLayoutManager(getActivity()); 
    m_RecyclerView.setLayoutManager(mLayoutManager);//showing odata vertically to user. 


    sz_RecordCount = String.valueOf(m_n_DefaultRecordCount);// increment of record count 
    sz_LastCount = String.valueOf(m_n_DeafalutLastCount);// increment of last count... 

    m_Handler = new Handler(); 
} 

public void implementScroll() {// on scroll load more data from server............. 
    m_RecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() { 
     @Override 
     public void onScrollStateChanged(RecyclerView recyclerView, int newState) { 
      super.onScrollStateChanged(recyclerView, newState); 
      if (newState == RecyclerView.SCROLL_STATE_IDLE) { 

      } 
     } 

     @Override 
     public void onScrolled(RecyclerView recyclerView, int dx, int dy) { 
      super.onScrolled(recyclerView, dx, dy); 
      if (dy > 0) { 

       m_showMore.setVisibility(View.VISIBLE); 
       m_showMore.setOnClickListener(new View.OnClickListener() { 
        @Override 
        public void onClick(View v) { 
         //change boolean value 
         m_showMore.setVisibility(View.GONE); 
         m_n_DefaultRecordCount = m_n_DefaultRecordCount + 5;// increment of record count by 5 on next load data 
         m_n_DeafalutLastCount = m_n_DeafalutLastCount + 5;// same here.....as above 

         sz_RecordCount = String.valueOf(m_n_DefaultRecordCount);// convert int value to string 
         sz_LastCount = String.valueOf(m_n_DeafalutLastCount);// convert int value to string ///// 
         new DealNext().execute(m_DealListingURL);// POST DATA TO SERVER TO LOAD MORE DATA...... 
        } 
       }); 
      } else { 
       m_showMore.setVisibility(View.GONE); 
      } 
     } 
    }); 
} 

hier ist mein erster serevr hit: -

//sending deal data to retreive response from server 
public String DealListing(String url, CRegistrationDataStorage login) { 
    InputStream inputStream = null; 
    m_oJsonsResponse = new CJsonsResponse(); 
    try { 
     // 1. create HttpClient 
     HttpClient httpclient = new DefaultHttpClient(); 
     // 2. make POST request to the given URL 
     HttpPost httpPost = new HttpPost(url); 
     String json = ""; 
     // 3. build jsonObject 
     JSONObject jsonObject = new JSONObject(); 
     jsonObject.put("agentCode", m_szMobileNumber); 
     jsonObject.put("pin", m_szEncryptedPassword); 
     jsonObject.put("recordcount", sz_RecordCount); 
     jsonObject.put("lastcountvalue", sz_LastCount); 
     //jsonObject.put("emailId", "[email protected]"); 
     // 4. convert JSONObject to JSON to String 
     json = jsonObject.toString(); 
     // 5. set json to StringEntity 
     StringEntity se = new StringEntity(json); 
     // 6. set httpPost Entity 
     httpPost.setEntity(se); 
     // 7. Set some headers to inform server about the type of the content 
     httpPost.setHeader("Content-type", "application/json"); 
     // 8. Execute POST request to the given URL 
     HttpResponse httpResponse = httpclient.execute(httpPost); 
     HttpEntity entity = httpResponse.getEntity(); 
     // 9. receive response as inputStream 
     inputStream = entity.getContent(); 
     System.out.println("InputStream....:" + inputStream.toString()); 
     System.out.println("Response....:" + httpResponse.toString()); 

     StatusLine statusLine = httpResponse.getStatusLine(); 
     System.out.println("statusLine......:" + statusLine.toString()); 
     ////Log.d("resp_body", resp_body.toString()); 
     int statusCode = statusLine.getStatusCode(); 
     // 10. convert inputstream to string 
     if (statusCode == 200) { 
      // 10. convert inputstream to string 
      if (inputStream != null) 
       s_szresult = m_oJsonsResponse.convertInputStreamToString(inputStream); 
      //String resp_body = 
      EntityUtils.toString(httpResponse.getEntity()); 
     } else 
      s_szresult = "Did not work!"; 
    } catch (Exception e) { 
     Log.d("InputStream", e.getLocalizedMessage()); 
    } 
    System.out.println("resul.....:" + s_szresult); 
    // 11. return s_szResult 
    return s_szresult; 
} 

public void getResponse() throws JSONException {// getting response from serevr .................. 
    if (m_oResponseobject.getString("resultdescription").equalsIgnoreCase("Transaction Successful")) {// server based condition 

     m_oAdapter = new CDealAppListingAdapter(s_oDataset);// create adapter object and add arraylist to adapter 
     m_oAdapter.notifyDataSetChanged(); 
     m_RecyclerView.setAdapter(m_oAdapter);//adding adapter to recyclerview 
    } else if (m_oResponseobject.getString("resultdescription").equalsIgnoreCase("Connection Not Available")) {//server based conditions 
     CToastMessage.getInstance().showToast(getActivity(), "Connection not avaliable"); 
    } else if (m_oResponseobject.getString("resultdescription").equalsIgnoreCase("Deal List Not Found")) {// serevr based conditions ..... 
     CToastMessage.getInstance().showToast(getActivity(), "No More Deals Available"); 
    } 
} 

// sending deal data to server and retreive response...... 
class CDealDataSent extends AsyncTask<String, Void, String> { 
    public CRegistrationDataStorage oRegisterStorage; 
    public CDealAppDatastorage item; 

    @Override 
    protected void onPreExecute() { 
     super.onPreExecute(); 
     CProgressBar.getInstance().showProgressBar(getActivity(), "Please wait while Loading Deals..."); 
    } 

    @Override 
    protected String doInBackground(String... urls) { 
     return DealListing(urls[0], oRegisterStorage);// sending data to server... 

    } 

    // onPostExecute displays the results of the AsyncTask. 
    @Override 
    protected void onPostExecute(final String result) { 
     new Thread(new Runnable() { 
      @Override 
      public void run() { 
       m_Handler.post(new Runnable() { 
        @Override 
        public void run() { 
         CProgressBar.getInstance().hideProgressBar();// hide progress bar after getting response from server....... 
         try { 
          m_oResponseobject = new JSONObject(result);// getting response from server 
          JSONArray posts = m_oResponseobject.optJSONArray("dealList"); 

          s_oDataset = new ArrayList<CDealAppDatastorage>(); 
          for (int i = 0; i < posts.length(); i++) { 
           JSONObject post = posts.getJSONObject(i); 
           item = new CDealAppDatastorage(); 
           item.setM_szHeaderText(post.getString("dealname")); 
           item.setM_szsubHeaderText(post.getString("dealcode")); 
           item.setM_n_Image(m_n_FormImage[i]); 
           s_oDataset.add(item); 

          } 
          getResponse(); 
         } catch (JSONException e) { 
          e.printStackTrace(); 
         } 
        } 
       }); 
      } 
     }).start(); 

    } 
} 

hier ist meine zweite serevr

hit
// sending data and receive reponse on second hit T LOAD MORE DATA when show more Btn clicked.............. 
private class DealNext extends AsyncTask<String, Void, String> { 
    public CRegistrationDataStorage oRegisterStorage; 

    @Override 
    protected void onPreExecute() { 
     super.onPreExecute(); 

     mProgressBar.setVisibility(View.VISIBLE);// SHOW PROGRESS BAR 
    } 

    @Override 
    protected String doInBackground(String... urls) { 
     //My Background tasks are written here 
     synchronized (this) { 
      return DealListing(urls[0], oRegisterStorage);// POST DATA TO SERVER 
     } 
    } 

    @Override 
    protected void onPostExecute(final String result) { 
     super.onPostExecute(result); 
     new Thread(new Runnable() { 
      @Override 
      public void run() { 
       m_Handler.post(new Runnable() { 
        @Override 
        public void run() { 
         mProgressBar.setVisibility(View.INVISIBLE);// DISMISS PROGRESS BAR.......... 
         try { 
          m_oResponseobject = new JSONObject(result);// getting response from server 
          final JSONArray posts = m_oResponseobject.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_n_Image(m_n_FormImage[i]);// static image for testing purpose not original.... 
           s_oDataset.add(item);// add items to arraylist.... 
           m_oAdapter.notifyItemInserted(s_oDataset.size());// notify adapter when deal added to recylerview 
          } 
          getResponse();// getting response from server.....and also here response based logics... 


         } catch (JSONException e) { 
          e.printStackTrace(); 
         } 
        } 
       }); 
      } 
     }).start(); 


    } 
} 

hier ist meine Adapterklasse:

public class CDealAppListingAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> { 
public static CDealAppDatastorage list; 
private static ArrayList<CDealAppDatastorage> s_oDataset; 
private final int VIEW_TYPE_ITEM = 0; 
private final int VIEW_TYPE_LOADING = 1; 

public CDealAppListingAdapter(ArrayList<CDealAppDatastorage> mDataList) { 
    s_oDataset = mDataList; 

} 

@Override 
public int getItemViewType(int position) { 
    return s_oDataset.get(position) == null ? VIEW_TYPE_LOADING : VIEW_TYPE_ITEM; 
} 

@Override 
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) { 
    if (i == VIEW_TYPE_ITEM) { 
     View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.deallisting_card_view, viewGroup, false); 
     return new DealAppViewHolder(view); 
    } else if (i == VIEW_TYPE_LOADING) { 
     View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.layout_loading_item, viewGroup, false); 
     return new LoadingViewHolder(view); 
    } 
    return null; 

} 

@Override 
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { 
    if (holder instanceof DealAppViewHolder) { 
     list = s_oDataset.get(position);// receiving item on position on index i 
     DealAppViewHolder dealAppViewHolder = (DealAppViewHolder) holder; 
     dealAppViewHolder.s_szAppImage.setImageResource(list.getM_n_Image()); 
     dealAppViewHolder.s_szheadingText.setText(list.getM_szHeaderText()); 
     dealAppViewHolder.s_szSubHeader.setText(list.getM_szsubHeaderText()); 
    } else if (holder instanceof LoadingViewHolder) { 
     LoadingViewHolder loadingViewHolder = (LoadingViewHolder) holder; 
     loadingViewHolder.progressBar.setIndeterminate(true); 
    } 

} 

@Override 
public int getItemCount() { 
    return (s_oDataset == null ? 0 : s_oDataset.size());//counting size of odata in ArrayList 
} 

static class LoadingViewHolder extends RecyclerView.ViewHolder { 
    public ProgressBar progressBar; 

    public LoadingViewHolder(View itemView) { 
     super(itemView); 
     progressBar = (ProgressBar) itemView.findViewById(R.id.progressBar1); 
    } 
} 

public static class DealAppViewHolder extends RecyclerView.ViewHolder { 
    public static ImageView s_szAppImage; 
    public static TextView s_szheadingText, s_szSubHeader; 
    public static Button s_szGetDealBtn; 

    public DealAppViewHolder(View itemLayoutView) { 
     super(itemLayoutView); 
     s_szheadingText = (TextView) itemLayoutView.findViewById(R.id.headingText);// finding id of headerText... 
     s_szSubHeader = (TextView) itemLayoutView.findViewById(R.id.subHeaderText);// finding id of subHeader..... 
     s_szAppImage = (ImageView) itemLayoutView.findViewById(R.id.appImage);//finding Id of Imgae in CardView 
     s_szGetDealBtn = (Button) itemLayoutView.findViewById(R.id.getDealBtn);// finding id of getdeal Btn 

     Random rnd = new Random();//creating object of Random class 
     int color = Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256));//genrating random color 
     s_szGetDealBtn.setBackgroundColor(color);//backgraound color of getDeal Btn 
     s_szGetDealBtn.setOnClickListener(new View.OnClickListener() {// onclick getDeal Btn 
      @Override 
      public void onClick(View v) {//send to deal detail page onclick getDeal Btn 
       Intent i = new Intent(v.getContext(), CDealAppListingDetails.class); 
       i.putExtra("DealCode", s_oDataset.get(getPosition()).getM_szsubHeaderText()); 
       i.putExtra("headerText", s_oDataset.get(getPosition()).getM_szHeaderText()); 
       v.getContext().startActivity(i); 
      } 
     }); 

     itemLayoutView.setOnClickListener(new View.OnClickListener() {// onclick cardview 
      @Override 
      public void onClick(View v) {// onclick cardview send to deal app listing details page ..... 
       Intent i = new Intent(v.getContext(), CDealAppListingDetails.class); 
       i.putExtra("DealCode", list.getM_szsubHeaderText()); 
       i.putExtra("headerText", list.getM_szHeaderText()); 
       v.getContext().startActivity(i); 
      } 
     }); 

    } 

} 

}

+0

Es wäre besser, wenn Sie Ihren 'RecyclerView.Adapter' teilen, würde die Logik, die Sie anfordern, im Allgemeinen in dieses Objekt gehen. – vguzzi

+0

ok warten Ich teile – Nitin

Antwort

0

Entweder speichern zwei Listen in den Adapter, der aktuell angezeigten Liste und die vollständige Liste, oder erhalten nur die Inhalte, die Sie benötigen, wenn Sie Ihre API erlaubt es .

Sie können dann Ihre Adaptergröße in getItemCount als Ihre angezeigte Listengröße + 1 (für die Ansicht mehr Elemente) einstellen. Sie müssen einen separaten Ansichtstyp hinzufügen, um in getItemViewType für Ihre Ansicht mehr Zelle zurückzugeben (die Logik zur Anzeige wäre es, wenn die Position aktuell als Listengröße angezeigt wird). Sie müssen außerdem eine neue Ansicht und einen neuen Ansichtshalter für die Zelle load more hinzufügen.

Nachdem Sie Ihre neue Ansicht mehr Zelle eingerichtet haben, können Sie einfach einen Klick-Listener hinzufügen. Wenn Sie darauf klicken, fügen Sie 5 Einträge aus Ihrer vollständigen Liste in Ihre aktuell angezeigte Liste ein (achten Sie dabei auf die aktuell angezeigte Liste). 1 Index der vollständigen Liste, und rufen notifyDataSetChanged oder notifyItemAdded x 5.

Es tut mir leid ich momentan keine Zeit haben, einen entsprechenden Adapter für Sie zu schreiben, aber ich hoffe, dass die obige Erklärung genügt.

+0

any Referenzen geben mir dann ... Schatz – Nitin

Verwandte Themen