Как мне получить данные из firebase и представить их в recyclerview?

Я не могу получить данные из firebase и просмотреть их в recyclerView

это моя база данных в firebaseвведите описание изображения здесь

Проблем нет, но в моем прогоне не отображаются элементы, это мой прогон введите описание изображения здесь

и это мой код, я пробовал все, что я не знаю, в чем проблема, помогите мне, пожалуйста

public class account_preview extends AppCompatActivity {
private ArrayList<outflow>outflows;
private RecyclerView recyclerView;
RecyclerAdapter adapter;
DatabaseReference myRef;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_account_preview);

    FirebaseDatabase database = FirebaseDatabase.getInstance();
    myRef = 
    database.getReference("user_account/(username)/bank_accounts/1");
    adapter = new RecyclerAdapter(outflows, account_preview.this);
    recyclerView = (RecyclerView) findViewById(R.id.RecyclerView);
    recyclerView.setHasFixedSize(true);
    LinearLayoutManager llm = new LinearLayoutManager(this);

    recyclerView.setLayoutManager(llm);
    llm.setOrientation(LinearLayoutManager.VERTICAL);

    onStart();

    new GetDataFromFirebase().
    executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);

    // Read from the database
    recyclerView.setAdapter(adapter);

    }

    @Override
   protected void onStart() {
    super.onStart();
    myRef.child("outflow").child("1").addValueEventListener(new 
    ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            outflows=new ArrayList<outflow>();
            for (DataSnapshot dataSnapshot1: 
       dataSnapshot.getChildren()){
                outflow values =  
     dataSnapshot1.getValue(outflow.class);
                outflows.add(values);}



            adapter.notifyDataSetChanged();


        }

        @Override
        public void onCancelled(DatabaseError error) {
            // Failed to read value
            System.out.println("Failed to read value." + 
        error.toException());
        }
       });

      }

     private class GetDataFromFirebase extends 
     AsyncTask<Void,Void,Boolean>{

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected Boolean doInBackground(Void... voids) {
        return false;
    }

    @Override
    protected void onPostExecute(Boolean aBoolean) {
        super.onPostExecute(aBoolean);
    }
    }
     }






  public class RecyclerAdapter extends 
  RecyclerView.Adapter<RecyclerAdapter.ViewHolder>{
      private Context context;

   private ArrayList<outflow> values;

   public RecyclerAdapter(ArrayList<outflow> values, account_preview 
  context) {
    this.values = values;
    this.context = context;
   }

  @Override
   public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) 
   {
    return new ViewHolder(LayoutInflater.from(parent.getContext())
            .inflate(R.layout.list_outflows, parent, false));


   }

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

    holder.name.setText( values.get(position).getCategory());
    holder.c.setText((int) values.get(position).getAmount());
   }

  @Override
  public int getItemCount() {

    int arr = 0;

    try{
        if (values.size()==0){

            arr = 0;

        }
        else{

            arr=values.size();
        }



    }catch (Exception e){



    }

    return arr;

   }

public class ViewHolder extends RecyclerView.ViewHolder {
    private TextView name,c;
    ViewHolder(View itemView) {
        super(itemView);
        name = (TextView) itemView.findViewById(R.id.totaloutflow);
        c=(TextView)itemView.findViewById(R.id.total);
    }
    }
  }

отток публичного класса {

private double amount;
private String date;
private String time;
private String attachment;
private String category;
private String location;
private String vendor;
private int rate;


public outflow(double amount, String date, String time, String attachment, String category, String location, String vendor) {
    this.amount = amount;
    this.date = date;
    this.time = time;
    this.attachment = attachment;
    this.category = category;
    this.location = location;
    this.vendor = vendor;
}



public double getAmount() {
    return amount;
}

public void setAmount(double amount) {
    this.amount = amount;
}

public String getDate() {
    return date;
}

public void setDate(String date) {
    this.date = date;
}

public String getTime() {
    return time;
}

public void setTime(String time) {
    this.time = time;
}

public String getAttachment() {
    return attachment;
}

public void setAttachment(String attachment) {
    this.attachment = attachment;
}

public String getCategory() {
    return category;
}

public void setCategory(String category) {
    this.category = category;
}

public String getLocation() {
    return location;
}

public void setLocation(String location) {
    this.location = location;
}

public String getVendor() {
    return vendor;
}

public void setVendor(String vendor) {
    this.vendor = vendor;
}

public int getRate() {
    return rate;
}

public void setRate(int rate) {
    this.rate = rate;
}

}

activity_account_preview.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:id = "@+id/container"
  android:layout_width = "match_parent"
  android:layout_height = "match_parent"
  >

    <android.support.v7.widget.RecyclerView
    android:id = "@+id/RecyclerView"
    android:layout_width = "match_parent"
    android:layout_height = "match_parent">


   </android.support.v7.widget.RecyclerView>
   </android.support.constraint.ConstraintLayout>




 list_outflows.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:id = "@+id/container"
android:layout_width = "match_parent"
android:layout_height = "match_parent"
tools:context = ".account_preview">

  <android.support.design.widget.BottomNavigationView
    android:id = "@+id/navigation"
    android:layout_width = "0dp"
    android:layout_height = "wrap_content"
    android:background = "#27233A"
    app:layout_constraintBottom_toBottomOf = "parent"
    app:layout_constraintLeft_toLeftOf = "parent"
    app:layout_constraintRight_toRightOf = "parent"
    app:menu = "@menu/navigation" />

   <TextView
    android:id = "@+id/textView"
    android:layout_width = "84dp"
    android:layout_height = "44dp"
    android:layout_marginEnd = "36dp"
    android:layout_marginStart = "8dp"
    android:padding = "5dp"
    android:text = "(التاريخ)"
    android:textColor = "#000000"
    android:textSize = "20dp"
    app:layout_constraintEnd_toEndOf = "parent"
    app:layout_constraintHorizontal_bias = "1.0"
    app:layout_constraintStart_toStartOf = "parent"
    tools:layout_editor_absoluteY = "64dp"
    tools:ignore = "MissingConstraints" />

  <Button
    android:id = "@+id/button"
    android:layout_width = "251dp"
    android:layout_height = "61dp"
    android:layout_marginBottom = "24dp"
    android:layout_marginEnd = "8dp"
    android:layout_marginLeft = "8dp"
    android:layout_marginRight = "8dp"
    android:layout_marginStart = "8dp"
    android:layout_marginTop = "8dp"
    android:background = "#9FB4C7"
    android:text = "حذف الحساب"
    android:textColor = "#ffffff"
    android:textSize = "30dp"
    app:layout_constraintBottom_toTopOf = "@+id/navigation"
    app:layout_constraintEnd_toEndOf = "parent"
    app:layout_constraintHorizontal_bias = "0.437"
    app:layout_constraintStart_toStartOf = "parent"
    app:layout_constraintTop_toBottomOf = "@+id/textView" />

  <android.support.design.widget.FloatingActionButton
    android:id = "@+id/floatingActionButton"
    android:layout_width = "wrap_content"
    android:layout_height = "wrap_content"
    android:layout_marginBottom = "12dp"
    android:layout_marginEnd = "8dp"
    android:layout_marginLeft = "8dp"
    android:layout_marginRight = "8dp"
    android:layout_marginStart = "8dp"
    android:background = "#D6C9C9"
    android:clickable = "true"
    app:backgroundTint = "#D6C9C9"
    app:layout_constraintBottom_toTopOf = "@+id/navigation"
    app:layout_constraintEnd_toEndOf = "parent"
    app:layout_constraintHorizontal_bias = "0.976"
    app:layout_constraintStart_toStartOf = "parent"
    app:srcCompat = "@android:drawable/ic_input_add" />

  <android.support.v7.widget.CardView
    android:id = "@+id/card_view"
    android:layout_width = "392dp"
    android:layout_height = "64dp"
    android:layout_margin = "2.5dp"
    android:layout_marginBottom = "8dp"
    android:layout_marginEnd = "8dp"
    android:layout_marginStart = "8dp"
    android:layout_marginTop = "184dp"
    app:cardBackgroundColor = "@color/lightgrey"
    app:cardCornerRadius = "4dp"
    app:layout_constraintBottom_toTopOf = "@+id/button"
    app:layout_constraintEnd_toEndOf = "parent"
    app:layout_constraintHorizontal_bias = "1.0"
    app:layout_constraintStart_toStartOf = "parent"
    app:layout_constraintTop_toBottomOf = "@+id/textView"
    app:layout_constraintVertical_bias = "1.0"
    tools:ignore = "MissingConstraints">


    <LinearLayout
        android:layout_width = "wrap_content"
        android:layout_height = "wrap_content"
        android:layout_marginLeft = "5dp"
        android:layout_weight = "0.30"
        android:orientation = "vertical">

        <TextView
            android:id = "@+id/totaloutflow"
            android:layout_width = "match_parent"
            android:layout_height = "wrap_content"
            android:layout_marginLeft = "4dp"
            android:text = "الفواتير"
            android:textColor = "@color/colorPrimaryDark"
            android:textSize = "25sp" />

        <TextView
            android:id = "@+id/total"
            android:layout_width = "388dp"
            android:layout_height = "wrap_content"
            android:layout_marginLeft = "4dp"
            android:layout_marginStart = "4dp"
            android:text = "ريال سعودي"
            android:textSize = "15sp"
            android:textStyle = "bold" />

    </LinearLayout>
    </android.support.v7.widget.CardView>

</android.support.constraint.ConstraintLayout>

Пожалуйста, добавьте содержимое вашего класса outflow.

Alex Mamo 07.02.2019 15:26

спасибо, что заставили меня не забыть добавить класс оттока, который я добавляю.

nora Khaled 08.02.2019 23:01
0
2
363
2

Ответы 2

У Firebase есть собственный адаптер для RecyclerView, поэтому лучше используйте его.

public FirebaseRecyclerAdapter<taskdata, ShowDataViewHolder> getmFirebaseAdapter() {
    return mFirebaseAdapter;
}

public void setmFirebaseAdapter(FirebaseRecyclerAdapter<taskdata, ShowDataViewHolder> mFirebaseAdapter) {
    this.mFirebaseAdapter = mFirebaseAdapter;
}


//View Holder For Recycler View
public static class ShowDataViewHolder extends RecyclerView.ViewHolder {
    private final TextView image_title  ;


    public ShowDataViewHolder(final View itemView)
    {
        super(itemView);

        image_title = itemView.findViewById(R.id.taskname);


    }

    private void Image_Title(String title)
    {
        image_title.setText(title);
    }


}


@Override
public void onStart() {
    super.onStart();

    FirebaseAuth mauth = FirebaseAuth.getInstance();
    String userod = mauth.getCurrentUser().getUid();
    myref = FirebaseDatabase.getInstance().getReference("Yourself").child(userod).child("task");

    setmFirebaseAdapter(new FirebaseRecyclerAdapter<taskdata, ShowDataViewHolder>(
            taskdata.class, R.layout.taskitem, ShowDataViewHolder.class, myref.orderByValue()) {
        public void populateViewHolder(final ShowDataViewHolder viewHolder, taskdata model, final int position) {

            viewHolder.Image_Title(model.getTaskname());


        }

    });


    recyclerView.setAdapter(getmFirebaseAdapter());


    myref.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            if (dataSnapshot.getValue() == null){
                Toast.makeText(getContext(),"No Bookmarks added yet!",Toast.LENGTH_SHORT).show();
                }else {
                mFirebaseAdapter.notifyItemChanged(0);
                mFirebaseAdapter.notifyDataSetChanged();
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });
    mFirebaseAdapter.notifyItemInserted(taskdata2.size()-1);
}

Если вам нужна дополнительная помощь по коду, перейдите на мой github — https://github.com/afreakyelf/Yourself/blob/master/app/src/main/java/com/example/rajat/yourself/taskadapterhome.java

Чтобы решить эту проблему, просто добавьте следующие строки кода в конструктор:

public RecyclerAdapter(List<outflow> list, account_preview context) {
    this.list = list
    this.context = context
}

Элементы теперь отображаются в вашем RecyclerView? Для этой ошибки см. этот Почта.

Alex Mamo 09.02.2019 12:30

Спасибо, но предметы не отображаются

nora Khaled 09.02.2019 13:01

В вашем методе onBindViewHolder()list.get(position) возвращает объект типа outflow?

Alex Mamo 09.02.2019 13:08

это мой onBindViewHolder(), и да, он возвращает объект исходящего потока @Override public void onBindViewHolder (держатель ViewHolder, позиция int) {holder.name.setText (values.get (position).getCategory()); держатель.c.setText((int) values.get(position).getAmount()); }

nora Khaled 09.02.2019 13:25

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

nora Khaled 09.02.2019 13:31

Если вы только пытаетесь зарегистрировать эти данные, печатает ли он что-то в логарифме?

Alex Mamo 10.02.2019 09:38

он успешно извлекает объект, но он не добавлен в список, я не знаю, почему

nora Khaled 10.02.2019 19:33

Вы пробовали комментировать эту строку recyclerView.setHasFixedSize(true);? Это работает?

Alex Mamo 11.02.2019 08:50

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