当前位置: 首页 > 知识库问答 >
问题:

应用程序在尝试使用tablayout中的片段中的RecolyerView的改型加载Json时崩溃

颛孙森
2023-03-14

更具体地说,我有一个活动,它包含一个tablayout,每个选项卡基本上都应该加载一个独立的片段,其中包含一个Recolyer视图,我希望使用RecolyerView根据用户操作加载从api检索的数据
,所以这就是活动:

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);
    }
}
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);
    }
}

**

共有1个答案

贺宝
2023-03-14

首先,检查RestaurantResponse.getRestaurantModel()是否返回NULL。

List<RestaurantModel> list = restaurantResponse.getRestaurantModel();
if(list == null){
    enter code here
}
 类似资料:
  • 主要活动 碎片 这是一个简单对话框的代码。 这里有一个我从中学习的链接。如果我只需通过调用按钮创建对话框,它就可以完全正常工作。

  • 我在片段中有一个listview。listview的每一行都有imageview,我正在加载位图图像。我将位图设置为imageview的标记。下次遇到带有非空标记的图像视图时,我会在标记中回收位图并将图像重新加载到其中。这导致崩溃“画布:试图使用回收的位图android.graphics.bitmap”在活动方向更改时崩溃。我不明白为什么会这样。请帮忙。 堆栈跟踪:java.lang.Runtim

  • 当我尝试连接Android Studio调试器时,我的一些应用程序崩溃,然后我收到以下错误: 我试着重启Windows 我正在使用最新版本的Android SDK,构建工具,。。。 此崩溃后的部分日志:

  • 我正在开发一个Android应用程序,它必须从文件中解析文本。 我的解析器中有以下方法。java类: 每当调用缓冲区时,我都会遇到问题。while循环中的readLine()方法。 我传递以下路径信息File对象是: 现在我已经看了堆栈和在线上的许多帖子,以便尝试解决这个问题,并尝试使用一些解决方案,但没有运气。这是我从错误堆栈跟踪中获得的一个片段。 我确信文件的路径是正确的,因为我在调试时检查了

  • 当我运行应用程序时,它工作得很好,但是当我想调试一个变量值时,应用程序就崩溃了。下面是完整的调试日志。我不知道是什么错误来纠正它。你们能帮帮我吗?我读到了一些关于并且我禁用和启用了ADB集成,但没有帮助我。我试图清洁,重建和运行的项目再次和没有帮助我。每次我尝试开始调试时,应用程序都会崩溃。 提前谢谢!!