RecyclerView не будет отображать данные

Итак, я новичок в использовании RecyclerView, и я пытаюсь его использовать. Я проверил, данные поступают, но теперь отображается строка, и я пытался отладить ее в течение дня, но безуспешно. Поэтому, пожалуйста, направьте меня в правильном направлении.

Активность :

package com.example.adelina_pc.testscanner3;
    public class PopularHourActivity extends AppCompatActivity {
        int length;
        RepoProducts repo;
        RecyclerAdapter  adapter;
        Product p;
        List<Product> array;
        RecyclerView list;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_popular_hour);


            TextView popularHour = findViewById(R.id.hour);
            popularHour.setText(String.valueOf(0));
            list = findViewById(R.id.list);

            Calendar rightNow = Calendar.getInstance();
            DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd/HH");
            String formattedDate = dateFormat.format(rightNow.getTime());

            DatabaseReference fireRef3 = FirebaseDatabase.getInstance().getReference().child("Info").child(formattedDate);
            fireRef3.addListenerForSingleValueEvent(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    length = (int) dataSnapshot.getChildrenCount();
                    repo = new RepoProducts(length);

                    for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
                        Product o = snapshot.getValue(Product.class);

                        repo.addObject(o);

                    }
                    if (repo.length==length){
                        restOfCode();
                        return;
                    }

                }
                @Override
                public void onCancelled(DatabaseError databaseError) {

                }
            });
        }
        public void restOfCode(){
            if (length>3){
                length=3;
            }

            array = new ArrayList<>();
            for (int i=0;i<length;i++){
               array.add(i,repo.v[i]);
            }
            list.setLayoutManager(new LinearLayoutManager(this));
            list.setHasFixedSize(true);
            adapter = new RecyclerAdapter(this, array);

            list.setAdapter(adapter);
            adapter.notifyDataSetChanged();

        }
    }

Я исключил импорт.

Мой RecyclerAdapter:

package com.example.adelina_pc.testscanner3;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.ViewHolder> {

    private List<Product> mData;
    private LayoutInflater mInflater;

    // data is passed into the constructor
    RecyclerAdapter(Context context, List<Product> data) {
        this.mInflater = LayoutInflater.from(context);
        this.mData = data;
    }

    // inflates the row layout from xml when needed
    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = mInflater.inflate(R.layout.custom_row_products, parent, false);
        return new ViewHolder(view);
    }

    // binds the data to the TextView in each row
    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
       Product p= new Product(mData.get(position));
        holder.name.setText(p.get_name());
        holder.barcode.setText(String.valueOf(p.get_barCode()));
        holder.code.setText(String.valueOf(p.get_code()));
        holder.price.setText(String.valueOf(p.get_price()));
        holder.stock.setText(String.valueOf(p.get_sold()));

    }



    // total number of rows
    @Override
    public int getItemCount() {
        return mData.size()
    }


    // stores and recycles views as they are scrolled off screen
    public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
        TextView name;
        TextView price;
        TextView code;
        TextView barcode;
        TextView stock;

        ViewHolder(View view) {
             super(view);
             name = view.findViewById(R.id.name);
             price = view.findViewById(R.id.price);
             code = view.findViewById(R.id.code);
             barcode = view.findViewById(R.id.barcode);
             stock = view.findViewById(R.id.stock);
        }

        @Override
        public void onClick(View view) {

        }
    }

}

И мой файл макета:

<?xml version = "1.0" encoding = "utf-8"?>
<android.support.constraint.ConstraintLayout 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:layout_width = "match_parent"
    android:layout_height = "70dp"
    android:height = "100dp"
    android:minHeight = "20dp">

    <TextView
        android:id = "@+id/code"
        android:layout_width = "0dp"
        android:layout_height = "46dp"
        android:layout_marginLeft = "16dp"
        android:layout_marginStart = "16dp"
        android:gravity = "center"
        android:text = "cod"
        app:layout_constraintHorizontal_chainStyle = "spread"
        app:layout_constraintHorizontal_weight = "3"
        app:layout_constraintBottom_toBottomOf = "parent"
        app:layout_constraintEnd_toStartOf = "@+id/price"
        app:layout_constraintHorizontal_bias = "0.5"
        app:layout_constraintStart_toStartOf = "parent"
        app:layout_constraintTop_toTopOf = "parent" />

    <TextView
        android:id = "@+id/price"
        android:layout_width = "0dp"
        android:layout_height = "46dp"

        android:gravity = "center"
        android:text = "price"
        app:layout_constraintHorizontal_weight = "3"
        app:layout_constraintBottom_toBottomOf = "parent"
        app:layout_constraintEnd_toStartOf = "@+id/name"
        app:layout_constraintHorizontal_bias = "0.5"
        app:layout_constraintStart_toEndOf = "@+id/code"
        app:layout_constraintTop_toTopOf = "parent" />

    <TextView
        android:id = "@+id/name"
        android:layout_width = "0dp"
        android:layout_height = "46dp"
        android:gravity = "center"
        android:text = "nume"
        app:layout_constraintHorizontal_weight = "10"
        app:layout_constraintBottom_toBottomOf = "parent"
        app:layout_constraintEnd_toStartOf = "@+id/barcode"
        app:layout_constraintHorizontal_bias = "0.5"
        app:layout_constraintStart_toEndOf = "@+id/price"
        app:layout_constraintTop_toTopOf = "parent" />

    <TextView
        android:id = "@+id/barcode"
        android:layout_width = "0dp"
        android:layout_height = "46dp"
        android:gravity = "center"
        android:text = "codbare"
        app:layout_constraintHorizontal_weight = "10"
        app:layout_constraintBottom_toBottomOf = "parent"
        app:layout_constraintEnd_toStartOf = "@+id/stock"
        app:layout_constraintHorizontal_bias = "0.5"
        app:layout_constraintStart_toEndOf = "@+id/name"
        app:layout_constraintTop_toTopOf = "parent" />

    <TextView
        android:id = "@+id/stock"
        android:layout_width = "0dp"
        android:layout_height = "46dp"

        android:layout_marginBottom = "8dp"
        android:layout_marginEnd = "16dp"
        android:layout_marginRight = "16dp"
        android:layout_marginTop = "8dp"
        android:gravity = "center"
        app:layout_constraintHorizontal_weight = "3"
        android:text = "stock"
        app:layout_constraintBottom_toBottomOf = "parent"
        app:layout_constraintEnd_toEndOf = "parent"
        app:layout_constraintHorizontal_bias = "0.5"
        app:layout_constraintStart_toEndOf = "@+id/barcode"
        app:layout_constraintTop_toTopOf = "parent" />


</android.support.constraint.ConstraintLayout>

PopularHourLayout.xml:

<?xml version = "1.0" encoding = "utf-8"?>
<android.support.constraint.ConstraintLayout 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:layout_width = "match_parent"
    android:layout_height = "match_parent"
    tools:context = ".PopularHourActivity">

    <TextView
        android:id = "@+id/textView9"
        android:layout_width = "204dp"
        android:layout_height = "48dp"
        android:background = "@drawable/custom_button"
        android:cursorVisible = "true"
        android:gravity = "center"
        android:text = "Populat Hour "
        android:textColor = "#000000"
        app:layout_constraintBottom_toBottomOf = "parent"
        app:layout_constraintEnd_toEndOf = "parent"
        app:layout_constraintStart_toStartOf = "parent"
        app:layout_constraintTop_toTopOf = "parent"
        app:layout_constraintVertical_bias = "0.057" />

    <android.support.v7.widget.RecyclerView
        android:id = "@+id/list"
        android:layout_width = "0dp"
        android:layout_height = "238dp"
        android:layout_marginBottom = "16dp"
        android:layout_marginTop = "8dp"
        app:layout_constraintBottom_toBottomOf = "parent"
        app:layout_constraintEnd_toEndOf = "parent"
        app:layout_constraintHorizontal_bias = "0.0"
        app:layout_constraintStart_toStartOf = "parent"
        app:layout_constraintTop_toTopOf = "parent"
        app:layout_constraintVertical_bias = "0.74" />
</android.support.constraint.ConstraintLayout>

Я что-то пропустил? Я сделал что-то неправильно?

Проблема может быть связана с XML-файлом макета PopularHourActivity. Я думаю, вам нужно добавить это к вашему вопросу.

Rasmusob 06.04.2019 22:48
0
1
53
1
Перейти к ответу Данный вопрос помечен как решенный

Ответы 1

Ответ принят как подходящий

Когда вы объявляете свой RecyclerView таким образом в своей деятельности

RecyclerView.Adapter adapter;

Вместо этого вы должны объявить это так

RecyclerAdapter adapter;

Кроме того, удалите строку, в которой вы вызываете notifyDataSetChanged(); вам это не нужно, используя то, как вы настраиваете адаптер,

А также LayoutInflater, вы должны получить LayoutInflater в onCreateViewHolder() следующим образом:

LayoutInflater.from(parent.getContext())

Проверьте свой список, прежде чем передавать его адаптеру, также обновите свой код с помощью рекомендаций, а также добавьте макет, где находится RecyclerView.

User One 06.04.2019 22:46

Также установите высоту RecyclerView на 0dp, чтобы соответствовать ограничениям, и примените рекомендацию LayoutInflater, которую я тоже вам говорил.

User One 06.04.2019 23:04

Ого, это была проблема. Но я не понимаю логики этого. Опубликуйте это как ответ, чтобы я мог проверить это

Adelina V. 06.04.2019 23:07

А в onBindViewHolder() замените Product p= new Product(mData.get(position)); по продукту p=mData.get(position); я думаю, вам не нужно создавать экземпляр нового продукта?

User One 06.04.2019 23:07

Настройка 0dp в RecyclerView сделала свое дело. Большое вам спасибо за ваше время.

Adelina V. 06.04.2019 23:16

Другие вопросы по теме