如何从Firebase检索数据并将其表示在recyclerview?

时间:2019-02-07 13:40:32

标签: android firebase-realtime-database android-recyclerview get

我无法从Firebase检索数据并在recyclerView上查看它

这是我在Firebase上的数据库enter image description here

没有问题出现,但是在我的跑步中没有显示这是我的跑步enter image description here

这是我的代码,我尝试了所有不知道是什么问题对我有帮助

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>

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

要解决此问题,请在构造函数中添加以下代码行:

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