0

所以更具体我有含有tablayout一个活动的每个选项卡应基本上加载包含一个再循环器视图的独立片段的i想要的使用改型的API检索到的数据中的用户动作的recyclerView碱基被加载
所以这是该活动:应用崩溃试图到JSON使用改型加载到recyclerView在一个片段中一个tablayout时

public class RestaurantLogoView extends AppCompatActivity implements LiteFragment.OnFragmentInteractionListener, RegularFragment.OnFragmentInteractionListener, View.OnClickListener { 
    private static final String TAG = "RestaurantLogoView"; 
     public static ProgressDialog progressDialog; 
    //TODO 
    public static View.OnClickListener myOnClickListener; 

    private String chosenArea; 
    TextView locationTv; 

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


     Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); 
     setSupportActionBar(toolbar); 

     ViewPager mViewPager = (ViewPager) findViewById(R.id.container); 
     TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs); 
     tabLayout.setupWithViewPager(mViewPager); 
     SectionsPagerAdapter pagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager(),getApplicationContext()); 
     //remove this if you still didnt get data in the fragment 
     mViewPager.setAdapter(pagerAdapter); 

     FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); 
     fab.setOnClickListener(view -> Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG) 
       .setAction("Action", null).show()); 

     locationTv = (TextView) findViewById(R.id.location_tv); 
     chosenArea = (String) getIntent().getSerializableExtra("Object"); 
     locationTv.setText(chosenArea); 
     locationTv.setOnClickListener(this); 
    } 

    @Override 
    public void onFragmentInteraction(Uri uri) { 
     //TODO i added this lately not sure what its supposed to do but consider removing it 
    } 

    /** 
    * Called when a view has been clicked. 
    * 
    * @param v The view that was clicked. 
    */ 

// 
// 
// @Override 
// public boolean onCreateOptionsMenu(Menu menu) { 
//  getMenuInflater().inflate(R.menu.menu_restaurant_main_view, menu); 
//  return true; 
// } 
    @Override 
    public void onClick(View v) { 
     if (v == locationTv) { 
      Intent o = new Intent(getApplicationContext(), AreaList.class); 
      startActivity(o); 
      finish(); 
     } else { 
      Toast.makeText(getApplicationContext(), "What do you want to eat today?", Toast.LENGTH_LONG).show(); 
     } 
    } 

    private class SectionsPagerAdapter extends FragmentStatePagerAdapter { 

     String tabTitles[] = {getString(R.string.regular), getString(R.string.lite)}; 
     Context context; 


     SectionsPagerAdapter(FragmentManager fm, Context context) { 
      super(fm); 
      this.context = context; 
     } 


     @Override 
     public Fragment getItem(int position) { 
      switch (position) { 
       case 0: 
        new RegularFragment(); 
        return RegularFragment.newInstance(TAG, position); 
       case 1: 
        new LiteFragment(); 
        return LiteFragment.newInstance(TAG, position); 

       default: 
        return null; 
      } 
     } 

     @Override 
     public int getCount() { 
      return tabTitles.length; 
     } 

     @Override 
     public CharSequence getPageTitle(int position) { 
      // Generate title based on item position 
      return tabTitles[position]; 
     } 

    } 

} 
` 

这是应该在我的第一标签中所示的第一片段

public class RegularFragment extends Fragment { 

    OnFragmentInteractionListener mListener; 

    // TODO: Rename parameter arguments, choose names that match 
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER 
    public static final String REGULAR_PARAM1 = "lite"; 
    View RootView; 
    List<RestaurantModel> regularRestaurants; 
    private RecyclerView recyclerView; 
    RecyclerViewAdapter adapter; 
    private Call<RestaurantElKbeer> callbackCall; 
    private String TAG = "RegularFragment"; 
    //new 
    public static final String ARG_PAGE = "ARG_PAGE"; 

    private int mPage; 

    public RegularFragment() { 
    } 

    // TODO: Rename and change types and number of parameters 
    public static Fragment newInstance(String param, int position) { 

     //TODO it might be important i didnt know why i created it 
     Fragment fragment = new RegularFragment(); 
     Bundle args = new Bundle(); 
     args.putInt(param, position); 
     fragment.setArguments(args); 
     return fragment; 
    } 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     regularRestaurants = requestRegularList(); 
     mPage = getArguments().getInt(ARG_PAGE); 

    } 

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

     //new 
     RootView = inflater.inflate(R.layout.fragment_regular, container, false); 
     recyclerView = (RecyclerView) RootView.findViewById(R.id.recyclerView); 
     recyclerView.setHasFixedSize(true); 
     initializeAdapter(); 
     LinearLayoutManager llm = new LinearLayoutManager(this.getContext()); 
     recyclerView.setLayoutManager(llm); 
     return RootView; 
    } 

    private void initializeAdapter() { 
     adapter = new RecyclerViewAdapter(getActivity(), regularRestaurants); 
     recyclerView.setAdapter(adapter); 
    } 

    // TODO: Rename method, update argument and hook method into UI event 
    public void onButtonPressed(Uri uri) { 
     if (mListener != null) { 
      mListener.onFragmentInteraction(uri); 
     } 
    } 

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


    private List<RestaurantModel> requestRegularList() { 
     List<RestaurantModel> myRestaurantsList = new ArrayList<>(); 
     RestAdapter restAdapter = new RestAdapter(); 
     API api = restAdapter.getApi(); 
     // URL: https://betaweb.jeebley.com/services_new/services.php?action=search&langId=1&countryId=21&cuisineType=1&cuisineId=all&areaId=1&delvType=1 

     Call<RestaurantElKbeer> call = api.getRestaurants("search", "1", "21", "all", "1", "1"); 
     call.enqueue(new Callback<RestaurantElKbeer>() { 
      @Override 
      public void onResponse(@NonNull Call<RestaurantElKbeer> call, @NonNull Response<RestaurantElKbeer> response) { 
       if (response.isSuccessful()) { 
        ArrayList<String> names = new ArrayList<String>(); 
        RestaurantElKbeer restaurantResponse = response.body(); 
        List<RestaurantModel> list = restaurantResponse.getRestaurantModel(); 
       if(list != null && !list.isEmpty()){ 
        for (int i = 0; i < list.size(); i++) { 
         String name; 
         name = list.get(i).getRName(); 
         names.add(name); 
         Log.i(TAG, "onResponse: " + names.get(i)); 
        } 

       } 
       else 
        { 
         Log.i(TAG, "onResponse(regular): RestaurantModelList is null"); 
        } 
        RecyclerViewAdapter adapter = new RecyclerViewAdapter(getContext(), list); 
        recyclerView.setAdapter(adapter); 
        recyclerView.setOnClickListener(v -> { 
         Intent i = new Intent(getContext(), ChooseYourLanguage.class); 
         i.putExtra("Object", getId()); 
         startActivityForResult(i, 0); 
        }); 
       } 
      } 

      @Override 
      public void onFailure(@NonNull Call<RestaurantElKbeer> call, Throwable t) { 
       Log.i(TAG, "onFailure: failed RegularFragmentCall"); 
      } 
     }); 
     return myRestaurantsList; 
    } 


    interface OnFragmentInteractionListener { 
     // TODO: Update argument type and name 
     void onFragmentInteraction(Uri uri); 
    } 

    /** 
    * Initialize the contents of the Fragment host's standard options menu. You 
    * should place your menu items in to <var>menu</var>. For this method 
    * to be called, you must have first called {@link #setHasOptionsMenu}. See 
    * {@link RestaurantLogoView#onCreateOptionsMenu(Menu) Activity.onCreateOptionsMenu} 
    * for more information. 
    * 
    * @param menu  The options menu in which you place your items. 
    * @param inflater 
    * @see #setHasOptionsMenu 
    * @see #onPrepareOptionsMenu 
    * @see #onOptionsItemSelected 
    */ 
    @Override 
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { 
     super.onCreateOptionsMenu(menu, inflater); 
    } 

    @Override 
    public void setHasOptionsMenu(boolean hasMenu) { 
     super.setHasOptionsMenu(hasMenu); 
    } 
} 

这是我RecyclerViewAdapter

public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> { 
    private List<RestaurantModel> items; 
    private Context ctx; 

    public RecyclerViewAdapter(Context context, List<RestaurantModel> items) { 
     this.ctx = context; 
     this.items=items; 
    } 


    private OnItemClickListener mOnItemClickListener; 
    private SharedPref sharedPref; 

    public interface OnItemClickListener { 
     void onItemClick(View view, RestaurantModel obj, int position); 
    } 

    public void setOnItemClickListener(final OnItemClickListener mItemClickListener) { 
     this.mOnItemClickListener = mItemClickListener; 
    } 

    public static class ViewHolder extends RecyclerView.ViewHolder { 

     CardView cv; 
     TextView title; 
     TextView description; 
     ImageView imageView; 

     ViewHolder(View itemView) { 
      super(itemView); 
      cv = (CardView) itemView.findViewById(R.id.restaurant_card_view); 
      title = (TextView) itemView.findViewById(R.id.restaurantName_section_label); 
      description = (TextView) itemView.findViewById(R.id.section_label2); 
      imageView = (ImageView) itemView.findViewById(R.id.restaurantImageView); 
     } 
    } 


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

     View v = LayoutInflater.from(parent.getContext()) 
       .inflate(R.layout.restaurant_card_layout, parent, false); 
     return new ViewHolder(v); 
    } 

    @Override 
    public void onBindViewHolder(ViewHolder holder, int position, List<Object> payloads) { 
     super.onBindViewHolder(holder, position, payloads); 
     RestaurantModel p = (RestaurantModel) payloads.get(position); 
     holder.title.setText(p.getRName()); 
     if (!p.getDelvType().equals("1")) { 
      holder.description.setText(p.getJDeliveryTime() + " " + p.getRMinOrderAmt() + " " + p.getJDeliveryCharge()); 
     } else { 
      holder.description.setText(p.getRDeliveryTime() + " " + p.getRMinOrderAmt() + " " + p.getRDeliveryCharge()); 
      holder.imageView.setImageResource(R.mipmap.ic_launcher); 
     } 
     holder.cv.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 
       Log.i("RecyclerViewAdapter", "onClick: replace with intent to send Restaurant data"); 
      } 
     }); 
    } 

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

     final RestaurantModel p = items.get(position); 
     holder.title.setText(p.getRName()); 
     if (!p.getDelvType().equals("1")) { 
      holder.description.setText(p.getJDeliveryTime() + " " + p.getRMinOrderAmt() + " " + p.getJDeliveryCharge()); 
     } else { 
      holder.description.setText(p.getRDeliveryTime() + " " + p.getRMinOrderAmt() + " " + p.getRDeliveryCharge()); 

     } 
     holder.cv.setOnClickListener(view -> { 
       mOnItemClickListener.onItemClick(view, p, position); 

     }); 
    } 


    @Override 
    public int getItemCount() { 
     return items.size(); 
    } 

    public interface OnLoadMoreListener { 
     void onLoadMore(int current_page); 
    } 
} 

这是我得到

**

06-06 00例外:11:05.215 10571-10571/com.jeebley。 jeebley E/AndroidRuntime:致命异常:主 工艺:com.jeebley.jeebley,PID:10571 显示java.lang.NullPointerException:尝试调用接口方法 '诠释java.util.List.size()' 上的空对象引用 com.jeebley.jeebley.adapters.RecyclerViewAdapter.getItemCount(RecyclerViewAdapter.java:109) at android.support.v7.widget.RecyclerView.dispatchLayoutStep1(RecyclerView.java:3493) at android.support.v7.widget.RecyclerView .dispatchLayout(RecyclerView.java:3310) at android.support.v7.widget.RecyclerView.onLayout(RecyclerView.java:3844) at android.view.View.layout(View.java:17687) at android.view .ViewGroup.layout(ViewGroup.java:5631) at android.widget.RelativeLayout.onLayout(RelativeLayout.java:1079) at android.view.View.layout(View.java:17687) at android.view.ViewGroup .layout(六ewGroup.java:5631) at android.support.v4.view.ViewPager.onLayout(ViewPager.java:1795) at android.view.View.layout(View.java:17687) at android.view.ViewGroup。 layout(ViewGroup.java:5631) at android.support.design.widget.HeaderScrollingViewBehavior.layoutChild(HeaderScrollingViewBehavior.java:131) at android.support.design.widget.ViewOffsetBehavior.onLayoutChild(ViewOffsetBehavior.java:42) at android.support.design.widget.CoordinatorLayout.onLayout(CoordinatorLayout.java:870) 在android.view上的android.support.design.widget.AppBarLayout $ ScrollingViewBehavior.onLayoutChild(AppBarLayout.java:1391) 。在android.widget.FrameLayout上的android.widget.FrameLayout.layoutChildren(FrameLayout.java:325) 上的android.view.ViewGroup.layout(ViewGroup.java:5631) View.layout(View.java:17687) 。 onLayout(FrameLayout.java:261) 在android.view.View.layout(View.java:17687) 在android.view.ViewGroup.layout(ViewGroup.java:5631) 在android.widget.LinearLayout.setChildFrame( LinearLayout.java:1762) 在android.widget.LinearLayout.layoutVertical(LinearLayout.java:1606) 在android.widget.LinearLayout.onLayout(LinearLayout.java:1515) 在android.view.View.layout(查看。的java:17687) 在android.view.ViewGroup.layout(ViewGroup.java:5631) 在android.widget.FrameLayout.layoutChildren(FrameLayout.java:325) 在android.widget.FrameLayout.onLayout(FrameLayout.java: 261) 在android.view.View.layout(View.java:17687) 在android.view.ViewGroup.layout(ViewGroup.java:5631) 在android.widget.LinearLayout.setChildFrame(LinearLayout.java:1762)在Android.widget.LinearLayout.layoutVertical(LinearLayout.java:1606) at android.widget.LinearLayout.onLayout(LinearLayout.java:1515) at android.view.View.layout(View.java:17687)在android.widget.FrameLayout.onLayout(FrameLayout.java:261) at android.widget.FrameLayout.layoutChildren(FrameLayout.java:325) at android.view.ViewGroup.layout(ViewGroup.java:5631) at com.android.internal.policy.DecorView.onLayout(DecorView.java:774) at android.view.View.layout(View.java:17687) at android.view.ViewGroup.layout(ViewGroup.java:5631) 在android.view.ViewRootImpl.performLayout(ViewRootImpl.java:2511) 在android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2226) 在android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1364)(Choreographer.java:at android.view.ViewRootImpl $ TraversalRunnable.run(ViewRootImpl.java:6763) at android.view.Choreographer $ CallbackRecord.run(Choreographer.java:923) at android.view.Choreographer.doCallbacks(Choreographer.java: 735) at android.view.Choreographer.doFrame(Choreographer.java:667) at android.view.Choreographer $ FrameDisplayEventReceiver.run(Choreographer.java:909) at android.os.Handler.handleCallback(Handler.java: 761) at android.os.Handler.dispatchMessage(Handler.java:98) at android.os.Looper.loop(Looper.java:156) at android.app.ActivityThread.main(Activit yThread.java:6524) 在java.lang.reflect.Method.invoke(本机方法) 在com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:941) 在com.android.internal .os.ZygoteInit.main(ZygoteInit.java:831) 06-06 00:11:05.238 10571-10571/com.jeebley.jeebley I /过程:发送信号。 PID:10571 SIG:9

**

回答

0

这是你在做什么:

List<RestaurantModel> list = restaurantResponse.getRestaurantModel(); 
for (int i = 0; i < list.size(); i++) { 
    String name; 
    name = list.get(i).getRName(); 
    names.add(name); 
    Log.i(TAG, "onResponse: " + names.get(i)); 
} 

至于我可以在错误跟踪看,你的问题是,列表为空当你问的大小,所以你应该问,如果该列表不为空之前:

... 
List<RestaurantModel> list = restaurantResponse.getRestaurantModel(); 
if(list != null && !list.isEmpty()){ 
    for (int i = 0; i < list.size(); i++) { 
     String name; 
     name = list.get(i).getRName(); 
     names.add(name); 
     Log.i(TAG, "onResponse: " + names.get(i)); 
    } 
} 
... 

编辑:

在适配器中,修改此方法:

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

的方法getItemCount()适配器生命周期内的数组初始化之前被调用。这就是为什么你需要检查你的列表是否为空以避免n。。

+0

基本上我只是测试的东西在这里,但我真正想要做的是加载餐馆名称,描述和最小订单金额,我会从API获得,因此,在这两种情况下不显示数据和我不知道为什么或在哪个进程崩溃发生和调试是如此恼人,我不知道大部分的步骤 –

+0

我做了条件检查空状态,我更新了新的异常抛出可以你请看看它 –

0

首先检查restaurantResponse.getRestaurantModel()是否返回null。

List<RestaurantModel> list = restaurantResponse.getRestaurantModel(); 
if(list == null){ 
    enter code here 
} 
+0

是的男人我这样做,并更新了异常被抛出 –

+0

我也更新了上面的代码,你可以看看我的回收视图适配器也许我做错了什么,但我可以'没有得到它 –

相关问题