Белый экран при выводе информации из json в cardview, затем в RecyclerView

Совсем недавно начал изучать разработку в android studio. Посмотрел видео на ютубе, как вывести данные в cardview. Не думал, что будет затуп на такой, вроде бы, простой вещи. Спасибо!

home_fragment

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    tools:context=".MainActivity"
    android:orientation="vertical">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recycler_view_menu"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</RelativeLayout>

Сама карточка

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.motion.widget.MotionLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/clMain"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:layoutDescription="@xml/item_menu_kitchen_scene">

    <androidx.cardview.widget.CardView
        android:id="@+id/cardView"
        android:layout_width="match_parent"
        android:layout_height="150dp"
        android:layout_marginStart="100dp"
        android:layout_marginLeft="100dp"
        android:layout_marginTop="16dp"
        android:layout_marginEnd="16dp"
        android:layout_marginRight="16dp"
        android:layout_marginBottom="16dp"
        app:cardCornerRadius="20dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <androidx.constraintlayout.widget.ConstraintLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <TextView
                android:id="@+id/kitchen_title"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_marginStart="100dp"
                android:layout_marginTop="24dp"
                android:layout_marginEnd="8dp"
                android:textSize="18sp"
                android:textStyle="bold"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toTopOf="parent"
                tools:text="" />

            <TextView
                android:id="@+id/kitchen_description"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_marginStart="100dp"
                android:ellipsize="end"
                android:maxLines="3"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/kitchen_title"
                tools:text="" />

        </androidx.constraintlayout.widget.ConstraintLayout>
    </androidx.cardview.widget.CardView>

</androidx.constraintlayout.motion.widget.MotionLayout>

menu_kitchen(адаптер)

public class menu_kitchen extends RecyclerView.Adapter<menu_kitchen.MyViewClass> {
    ArrayList<String> title;
    ArrayList<String> des;
    HomeFragment context;

    public menu_kitchen(ArrayList<String> title, ArrayList<String> des, HomeFragment context) {
        this.title = title;
        this.des = des;
        this.context = context;
    }

    @NonNull
    @Override
    public MyViewClass onCreateViewHolder(@NonNull ViewGroup parent, int viewType){
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_menu_kitchen,parent,false);
        MyViewClass myViewClass = new MyViewClass(view);
        return  myViewClass;
    }

    @Override
    public void onBindViewHolder(@NonNull @NotNull MyViewClass holder, int position) {
        holder.title.setText(title.get(position));
        holder.des.setText(des.get(position));
        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });
    }

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

    public void setData(List<String> data){
        title = (ArrayList<String>) data;
    }

    public class MyViewClass extends RecyclerView.ViewHolder{
        TextView title;
        TextView des;
        public MyViewClass(@NonNull View itemView) {
            super(itemView);
            title = itemView.findViewById(R.id.kitchen_title);
            des = itemView.findViewById(R.id.kitchen_description);
        }
    }

}
menu_kitchen(адаптер)

home_fragment

public class HomeFragment extends Fragment {

    private HomeViewModel homeViewModel;
    private FragmentHomeBinding binding;
    RecyclerView recyclerView;
    ArrayList<String> title=new ArrayList<>();
    ArrayList<String> des = new ArrayList<>();

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        homeViewModel =
                new ViewModelProvider(this).get(HomeViewModel.class);

        binding = FragmentHomeBinding.inflate(inflater, container, false);
        View root = binding.getRoot();

        View view = inflater.inflate(R.layout.fragment_home, container, false);

        recyclerView = view.findViewById(R.id.recycler_view_menu);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity().getApplicationContext());
        recyclerView.setLayoutManager(linearLayoutManager);

        try{
            JSONObject jsonObject = new JSONObject(JsonDataFromAsset("kitchen.json"));
            JSONArray jsonArray = jsonObject.getJSONArray("menu");
            for(int i = 0; i<jsonArray.length();i++){
                JSONObject kitchenData=jsonArray.getJSONObject(i);
                Log.w("123", kitchenData.getString("title"));
                title.add(kitchenData.getString("title"));
                des.add(kitchenData.getString("des"));
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        menu_kitchen menukitchen = new menu_kitchen(title,des,HomeFragment.this);
        recyclerView.setAdapter(menukitchen);




//        final TextView textView = binding.textHome;
//        homeViewModel.getText().observe(getViewLifecycleOwner(), new Observer<String>() {
//            @Override
//            public void onChanged(@Nullable String s) {
//                textView.setText(s);
//            }
//        });
        return root;
    }

    private String JsonDataFromAsset(String FileName){
        String json = null;
        try{
            InputStream inputStream = getActivity().getAssets().open(FileName);
            int sizeOfFile = inputStream.available();
            byte [] bufferData = new byte[sizeOfFile];
            inputStream.read(bufferData);
            inputStream.close();
            json = new String(bufferData, "UTF-8");

        }catch (IOException e){
            e.printStackTrace();
            return null;
        }
        return json;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }
}

В логах выводятся данные из массива. json файл находится в папке assets

UPD JSON файл

{"menu": [
  {
    "id": "1",
    "title": "Стейк Миньон",
    "des": "Миньон из говяжьей вырезки с гарниром из маринованного яблока и ягод"
  },
  {
    "id": "2",
    "title": "Стейк Рибай",
    "des": "Рибай из мраморной говядины зернового откорма с тыквенным муссом"
  },
  {
    "id": "3",
    "title": "Люля-Кебаб из баранины",
    "des": "Люля-кебаб из баранины и говядины со сливовым соусом"
  }
]

}

Logcat

2022-07-28 01:00:52.565 20616-20616/com.example.test2 I/HwViewRootImpl: removeInvalidNode all the node in jank list is out of time
2022-07-28 01:00:55.359 20616-20616/com.example.test2 V/AudioManager: querySoundEffectsEnabled...
2022-07-28 01:00:55.414 20616-20616/com.example.test2 W/123: Стейк Миньон
2022-07-28 01:00:55.414 20616-20616/com.example.test2 W/123: Стейк Рибай
2022-07-28 01:00:55.414 20616-20616/com.example.test2 W/123: Люля-Кебаб из баранины
2022-07-28 01:00:55.441 20616-20616/com.example.test2 E/RecyclerView: No adapter attached; skipping layout

Ответы (1 шт):

Автор решения: Andrew

Не очень понимаю в чем смысл строки:

private FragmentHomeBinding binding;

при том что у вас нет биндинга в фрагменте, и тут тоже:

binding = FragmentHomeBinding.inflate(inflater, container, false);

и дальше вы из onCreateView возврат этого:

View root = binding.getRoot();

и не очень понятно что в итоге вам вернется. С виду загрузка данных в адаптер выглядит корректно. Попробуйте ориентацию установить дополнительно как в доках описано:

LinearLayoutManager(Context context, @RecyclerView.Orientation int orientation,
            boolean reverseLayout)

типа такого:

LinearLayoutManager(getActivity(), LinearLayoutManager.HORIZONTAL, false)

и делайте возврат из onCreateView:

return view;
→ Ссылка