2016-06-30 88 views
1

我有一個recyclerview適配器與3 textviews。我使用模型類來設置文本。現在,我想使用具有不同佈局的相同適配器,並在不同的類中只有一個textview。當我嘗試時,我得到了NullPointerException(可能是其他2 textview是空白的)。有什麼方法可以在不同的佈局和不同的類中使用相同的適配器?使用相同的recyclerview適配器與不同的佈局

// second class - I used 1 textview 
 

 
public class Customers extends AppCompatActivity{ 
 

 
    private CShowProgress cShowProgress; 
 
    private RecyclerView mRecyclerView; 
 
    private TimeLineAdapter mTimeLineAdapter; 
 
    private List<TimeLineModel> mDataList = new ArrayList<>(); 
 
    private static final String CUSTOMERS = "http://192.168.200.3/ubooktoday/android/showspacustomerlist"; 
 

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

 
     getSupportActionBar().setDisplayHomeAsUpEnabled(true); 
 

 
     cShowProgress = CShowProgress.getInstance(); 
 

 
     mRecyclerView = (RecyclerView) findViewById(R.id.recyclerView); 
 
     mRecyclerView.setLayoutManager(getLinearLayoutManager()); 
 
     mRecyclerView.setHasFixedSize(true); 
 

 
     showCustomers(); 
 
    } 
 

 
    private void showCustomers() { 
 

 
     if(mDataList!=null)mDataList.clear(); 
 

 
     cShowProgress.showProgress(Customers.this); 
 

 
     StringRequest stringRequest = new StringRequest(Request.Method.POST, CUSTOMERS, 
 
       new Response.Listener<String>() { 
 
        @Override 
 
        public void onResponse(String response) { 
 

 
         cShowProgress.hideProgress(); 
 

 
         try { 
 

 
          JSONArray jsonArray = new JSONArray(response); 
 

 
          for(int i=0; i<jsonArray.length(); i++){ 
 
           JSONObject obj = jsonArray.getJSONObject(i); 
 

 
           TimeLineModel model = new TimeLineModel(); 
 

 
           model.setCustname(obj.getString("customername")); 
 

 
           mDataList.add(model); 
 
           mTimeLineAdapter = new TimeLineAdapter(getApplicationContext(), R.layout.item_row_customer, mDataList); 
 
           mRecyclerView.setAdapter(mTimeLineAdapter); 
 
          } 
 

 

 
          mTimeLineAdapter.notifyDataSetChanged(); 
 

 

 

 

 

 
         } catch (JSONException e) { 
 
          // JSON error 
 
          e.printStackTrace(); 
 
          Toast.makeText(getApplicationContext(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show(); 
 
         } 
 
        } 
 
       }, new Response.ErrorListener() { 
 
      @Override 
 
      public void onErrorResponse(VolleyError error) { 
 
       Toast.makeText(getApplicationContext(), "VolleyError" + error.toString(), Toast.LENGTH_LONG).show(); 
 
      } 
 
     }) { 
 
      @Override 
 
      protected Map<String, String> getParams() { 
 
       Map<String, String> params = new HashMap<String, String>(); 
 

 
       params.put("spaid", "145"); 
 
       return params; 
 
      } 
 

 
     }; 
 

 
     RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext()); 
 
     requestQueue.add(stringRequest); 
 
    } 
 

 

 
    private LinearLayoutManager getLinearLayoutManager() { 
 

 
     LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getApplicationContext()); 
 
     return linearLayoutManager; 
 

 
    } 
 

 
    @Override 
 
    public boolean onOptionsItemSelected(MenuItem item) { 
 
     switch (item.getItemId()) { 
 
      case android.R.id.home: 
 
       onBackPressed(); 
 
       break; 
 
     } 
 
     return true; 
 
    } 
 
}

// first class - I used all 3 textviews 

public class Walkin extends Fragment{ 

    private RecyclerView mRecyclerView; 
    private TimeLineAdapter mTimeLineAdapter; 
    private List<TimeLineModel> mDataList = new ArrayList<>(); 
    private static final String DASHBOARD = "My API"; 

    @Nullable 
    @Override 
    @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { 
     return inflater.inflate(R.layout.walkin, container, false); 
    } 

    @Override 
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { 
     super.onViewCreated(view, savedInstanceState); 


     mRecyclerView = (RecyclerView) view.findViewById(R.id.recyclerView); 
     mRecyclerView.setLayoutManager(getLinearLayoutManager()); 
     mRecyclerView.setHasFixedSize(true); 

     showDashboard(); 
    } 

    private void showDashboard() { 

     if(mDataList!=null)mDataList.clear(); 

     cShowProgress.showProgress(getActivity()); 

     StringRequest stringRequest = new StringRequest(Request.Method.POST, DASHBOARD, 
       new Response.Listener<String>() { 
        @Override 
        public void onResponse(String response) { 


         try { 
          JSONObject jsonObject = new JSONObject(response); 

          JSONArray jsonArray = jsonObject.getJSONArray("walkinlist"); 

          for(int i=0; i<jsonArray.length(); i++){ 
           JSONObject obj = jsonArray.getJSONObject(i); 

           TimeLineModel model = new TimeLineModel(); 

           model.setCustname(obj.getString("customername")); 
           model.setTime(obj.getString("serviceDuration")); 
           model.setServname(obj.getString("service")); 

           mDataList.add(model); 
           mTimeLineAdapter = new TimeLineAdapter(getActivity(), R.layout.item_row_dashboard, mDataList); 
           mRecyclerView.setAdapter(mTimeLineAdapter); 
          } 


          mTimeLineAdapter.notifyDataSetChanged(); 





         } catch (JSONException e) { 
          // JSON error 
          e.printStackTrace(); 
          Toast.makeText(getActivity(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show(); 
         } 
        } 
       }, new Response.ErrorListener() { 
      @Override 
      public void onErrorResponse(VolleyError error) { 
       Toast.makeText(getActivity(), "VolleyError" + error.toString(), Toast.LENGTH_LONG).show(); 
      } 
     }) { 
      @Override 
      protected Map<String, String> getParams() { 
       Map<String, String> params = new HashMap<String, String>(); 

       params.put("spaid", "145"); 
       return params; 
      } 

     }; 

     RequestQueue requestQueue = Volley.newRequestQueue(getActivity()); 
     requestQueue.add(stringRequest); 
    } 


    private LinearLayoutManager getLinearLayoutManager() { 

     LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity()); 
     return linearLayoutManager; 

    } 
} 
// Adapter class 

public class TimeLineAdapter extends RecyclerView.Adapter<TimeLineViewHolder> { 

    private List<TimeLineModel> mFeedList; 
    int resource; 
    private Context mContext; 

    public TimeLineAdapter(Context mContext, int resource, List<TimeLineModel> feedList) { 

     this.resource = resource; 
     this.mContext = mContext; 
     mFeedList = feedList; 
    } 


    @Override 
    public TimeLineViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { 

     View view = View.inflate(parent.getContext(), resource, null); 
     return new TimeLineViewHolder(view, viewType); 
    } 

    @Override 
    public void onBindViewHolder(TimeLineViewHolder holder, int position) { 

     TimeLineModel timeLineModel = mFeedList.get(position); 

     holder.servicename.setText(timeLineModel.getServname()); 
     holder.custname.setText(timeLineModel.getCustname()); 
     holder.time.setText(timeLineModel.getTime()); 

    } 

    @Override 
    public int getItemCount() { 
     return (mFeedList!=null? mFeedList.size():0); 
    } 


} 
// ViewHolder class 

public class TimeLineViewHolder extends RecyclerView.ViewHolder { 
    public TextView servicename, custname, time; 

    public TimeLineViewHolder(View itemView, int viewType) { 
     super(itemView); 
     servicename = (TextView) itemView.findViewById(R.id.tv_service); 
     custname = (TextView) itemView.findViewById(R.id.tv_cust); 
     time = (TextView) itemView.findViewById(R.id.tv_time); 
    } 
} 
+0

檢查空指針異常一樣,如果(時間!= NULL)其中u得到此錯誤 –

+0

嘗試適配器中的getItemType() – naiyu

回答

4

可以使用getItemViewType()

  1. 使您的適配器(此處的TimeLineAdapter)僅限於RecyclerView.Adapter
  2. 可以更改適配器的建築工,以收到的ItemType,並在您的適配器getItemViewType
  3. Overrideint getItemViewType (int position)方法使用它。
  4. 在onCreateViewHolder中,您可以通過使用viewType參數來區分要膨脹的佈局。
  5. onBindViewHolder使用instanceof檢查哪個ViewHolder創建並調用相關的綁定功能

一個示例代碼 -

// Adapter class 
public class TimeLineAdapter extends RecyclerView.Adapter{ 
..... 
int type; 

    public TimeLineAdapter(Context mContext, int resource, List<TimeLineModel> feedList,int layoutType) { 
    ..... 
    ..... 
    type=layoutType; 
    } 

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


    @Override 
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { 
     if(viewType==1){ 
       View view = View.inflate(parent.getContext(), resource, null); 
       return new TimeLineViewHolder(view, viewType); 
     }else{ 
      View view = View.inflate(parent.getContext(), resource, null); 
      return new TimeLineViewHolder2(view, viewType); 
     } 
    } 

    @Override 
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { 

     if(holder instanceof TimeLineViewHolder){ 

       TimeLineModel timeLineModel = mFeedList.get(position); 

       ((TimeLineViewHolder) holder).servicename.setText(timeLineModel.getServname()); 
      ...... 
     } 
     else if(holder instanceof TimeLineViewHolder2){ 
      .... 
      .... 
     } 

    } 

    @Override 
    public int getItemCount() { 
     return (mFeedList!=null? mFeedList.size():0); 
    } 


} 
+0

它可以用於在不同的類中有不同的佈局嗎? @Harshit – Sammy

+0

是的。您可以將所需的佈局值傳遞給此適配器的構造函數。 – Harshit

+0

非常感謝。我會試試看。現在我接受你的答案。 :) – Sammy

相關問題