如何将 Firebase 数据提取到数组中以进行 recyclerview?

Posted

技术标签:

【中文标题】如何将 Firebase 数据提取到数组中以进行 recyclerview?【英文标题】:How to fetch Firebase data into arrays for recyclerview? 【发布时间】:2018-09-17 04:46:06 【问题描述】:

这是我的 HomeActivity

package my.unimas.a50200siswa.studentattendancemonitoringsystem;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View; 
import android.widget.Button;
import android.widget.TextView;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser; 
import com.google.firebase.database.DataSnapshot; 
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.List;

public class HomeActivity extends AppCompatActivity 

String userID;
List<CourseModel> mlist;
TextView btnSignOut, UserName;
RecyclerView courseRecycler;

String CourseCode, CourseName;

/*---- Firebase Database stuff ----*/
FirebaseDatabase mFirebaseDatabase;
FirebaseAuth mAuth;
FirebaseUser user;
FirebaseAuth.AuthStateListener mAuthListener;
DatabaseReference myRef;




@Override
protected void onStart() 

    super.onStart();
    mAuth.addAuthStateListener(mAuthListener);



@Override
public void onStop() 
    super.onStop();
    if (mAuthListener != null) 
        mAuth.removeAuthStateListener(mAuthListener);
    


@Override
protected void onCreate(Bundle savedInstanceState) 
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_home);

    /*-------Finding View---------*/
    Button btnShow = findViewById(R.id.show);
    btnSignOut = (TextView) findViewById(R.id.btnsignout_home);
    UserName = findViewById(R.id.username);
    courseRecycler = findViewById(R.id.recyclerviewcourse);

    btnSignOut.setOnClickListener(new View.OnClickListener() 
        @Override
        public void onClick(View v) 
            mAuth.signOut();
        

    );


    mAuthListener = new FirebaseAuth.AuthStateListener() 

        @Override
        public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) 
            if (firebaseAuth.getCurrentUser() == null) 
                startActivity(new Intent(HomeActivity.this, SignInActivity.class));
            
        
    ;


    /* ----------------- Firebase Elements -----------------*/
    mAuth = FirebaseAuth.getInstance();
    user = mAuth.getCurrentUser();
    userID = user.getUid();
    mFirebaseDatabase = FirebaseDatabase.getInstance();
    myRef = mFirebaseDatabase.getInstance().getReference();


    UserName.setText(user.getDisplayName());

    /*------------------------------------------------------------------*/


    myRef.addValueEventListener(new ValueEventListener() 
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) 
            // This method is called once with the initial value and again
            // whenever data at this location is updated.
            mlist = new ArrayList<CourseModel>();
            for (DataSnapshot dataSnapshot1 : dataSnapshot.child("Users").child(userID).child("Courses").getChildren()) 

                CourseModel value = dataSnapshot1.getValue(CourseModel.class);
                CourseModel course = new CourseModel();
                String userID = value.getUserId();
                course.setUserId(userID);
                String courseCode = value.getCourseCode();
                course.setCourseCode(courseCode);

                for (DataSnapshot dataSnapshot2 : dataSnapshot1.child("CourseName").getChildren()) 
                    CourseModel value2 = dataSnapshot2.getValue(CourseModel.class);
                    String courseName = value2.getCourseName();
                    course.setCourseName(courseName);
                    mlist.add(course);

                

            

        

        @Override
        public void onCancelled(DatabaseError error) 
            // Failed to read value
            Log.w("Hello", "Failed to read value.", error.toException());
        
    );




            RecyclerViewAdapterCourse recyclerAdapter = new RecyclerViewAdapterCourse(mlist, HomeActivity.this);
            RecyclerView.LayoutManager recycler = new GridLayoutManager(HomeActivity.this, 2);
            /// RecyclerView.LayoutManager recyce = new LinearLayoutManager(MainActivity.this);
            // recycle.addItemDecoration(new GridSpacingItemDecoration(2, dpToPx(10), true));
            courseRecycler.setLayoutManager(recycler);
            courseRecycler.setItemAnimator(new DefaultItemAnimator());
            courseRecycler.setAdapter(recyclerAdapter);


  

这是我的 RecyclerViewCourse.class

 package my.unimas.a50200siswa.studentattendancemonitoringsystem;

 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.List;

 class RecyclerViewAdapterCourse extends RecyclerView.Adapter<RecyclerViewAdapterCourse.CourseViewHolder> 

 private Context mContext ;
 private List<CourseModel> mlist ;


public RecyclerViewAdapterCourse(List<CourseModel> mData, Context mContext) 
    this.mContext = mContext;
    this.mlist = mData;


@Override
public CourseViewHolder onCreateViewHolder(ViewGroup parent, int viewType) 

    View view =LayoutInflater.from(mContext).inflate(R.layout.item_course,parent,false);
    CourseViewHolder courseViewHolder = new CourseViewHolder(view);

    return courseViewHolder;


@Override
public void onBindViewHolder(CourseViewHolder holder, int position) 
    CourseModel courselist = mlist.get(position);
    holder.userID.setText(courselist.getUserId());
    holder.courseCode.setText(courselist.getCourseCode());
    holder.courseName.setText(courselist.getCourseName());


@Override
public int getItemCount() 

    int arr = 0;

    try
        if(mlist.size()==0)
            arr = 0;
        
        else
            arr=mlist.size();
        

    catch (Exception e)
    
    return arr;


class CourseViewHolder extends RecyclerView.ViewHolder
    TextView userID,courseCode,courseName;


    public CourseViewHolder(View itemView) 
        super(itemView);
        userID = (TextView) itemView.findViewById(R.id.userid);
        courseCode= (TextView) itemView.findViewById(R.id.coursecode);
        courseName= (TextView) itemView.findViewById(R.id.coursename);
    




这是我的 CourseModel.class

package my.unimas.a50200siswa.studentattendancemonitoringsystem;


public class CourseModel 

public String UserId, CourseCode, CourseName;

public String getUserId() 
    return UserId;


public String getCourseCode() 
    return CourseCode;


public String getCourseName() 
    return CourseName;



public void setUserId(String userid) 
    this.UserId = userid;


public void setCourseCode(String coursecode) 
    this.CourseCode = coursecode;


public void setCourseName(String coursename) 
    this.CourseCode = coursename;




我想要这样的数组列表:

"***", "TMI4013", "System Programming"
"***", "TMI4033", "LogicProgramming"

我对数组中的 Firebase 数据检索并不是很熟悉。我尝试了许多发布在堆栈中的答案。没有工作。在某些答案中,有时它会在一段时间后显示数据,然后在实时数据库中数据被删除,我什至不明白为什么。

我没有提供 XML 文件,因为我尝试使用本地文件并在 HomeActivity 中生成数组并且效果很好。

    mlist = new ArrayList<>();
    mlist.add(new CourseModel("012223","TMN4013","System Programming"));
    mlist.add(new CourseModel("34566","TMN4013","System Programming"));
    RecyclerView myrv = (RecyclerView) findViewById(R.id.recyclerview_id);
    RecyclerViewAdapter myAdapter = new RecyclerViewAdapter(this,mlist);
    myrv.setLayoutManager(new GridLayoutManager(this,3));
    myrv.setAdapter(myAdapter);

【问题讨论】:

请添加您的 Firebase 数据库的屏幕截图 @Nuwan94 我已经添加了。请点击链接说“我想要像 ........这样的数组列表” 您需要从 firebase 获取数据并显示在 recyclerView 上吗?我说的对吗? @SarasaGunawardhana 是的.. RecyclerViewAdapterCourse recyclerAdapter = new RecyclerViewAdapterCourse(mlist, HomeActivity.this); RecyclerView.LayoutManager recycler = new GridLayoutManager(HomeActivity.this, 2); courseRecycler.setLayoutManager(recycler); courseRecycler.setItemAnimator(new DefaultItemAnimator()); courseRecycler.setAdapter(recyclerAdapter); 如果您有兴趣,this 是您可以从 Firebase 实时数据库中检索数据并使用 FirebaseRecyclerAdapter 将其显示在 RecyclerView 中的方法。 【参考方案1】:

从 firebase 中检索数据并将列表转换为这样的数组

for (DataSnapshot dataSnapshot1 : dataSnapshot.child("Users").child(userID).child("Courses").getChildren())  
    CourseModel value = dataSnapshot1.getValue(CourseModel.class); 
    CourseModel course = new CourseModel(); 
    String userID = value.getUserId(); course.setUserId(userID); 
    String courseCode = value.getCourseCode();
    course.setCourseCode(courseCode);
    for (DataSnapshot dataSnapshot2 : dataSnapshot1.child("CourseName").getChildren())  
        CourseModel value2 = dataSnapshot2.getValue(CourseModel.class); 
        String courseName = value2.getCourseName(); 
        course.setCourseName(courseName);
        mlist.add(course);

     



  CourseModel[] array = mlist.toArray(new CourseModel[mlist.size()]);

编辑:

像这样改变你的适配器

RecyclerViewAdapter myAdapter = new RecyclerViewAdapter(this, array);

将recyclerView的构造函数改为CourseModel数组

public RecyclerViewAdapterCourse(CourseModel[] mData, Context mContext) 
     this.mContext = mContext; 
     this.mArray = mData; 
   


@Override 
public void onBindViewHolder(CourseViewHolder holder, int position)  
    CourseModel courselist = marray[position];
    holder.userID.setText(courselist.getUserId());
    holder.courseCode.setText(courselist.getCourseCode());
    holder.courseName.setText(courselist.getCourseName());
 

【讨论】:

感谢您的回复。它显示在应该找到 CourseModel[] 的位置查找 odject 时出错。然后我怎样才能将它传递给我在 recyclerview 中的上下文? 侯赛因谢谢你再次显示同样的错误,即使根据你的建议更正后。 错误:不兼容的类型:Object[] 无法转换为 CourseModel[] 错误:不兼容的类型:HomeActivity 无法转换为 CourseModel[] 检查编辑的答案。这将解决您的问题

以上是关于如何将 Firebase 数据提取到数组中以进行 recyclerview?的主要内容,如果未能解决你的问题,请参考以下文章

如何加入从我的数组的每个元素的数据库中提取的结果并在 Laravel 8 中以 json 形式返回

如何将我在 EditText 框中键入的数据添加到数组中以在另一个活动中列出?

如何从 MySQL 中提取 JSON 数组

如何按选择的顺序将多个文件上传到 Firebase 存储?

如何在不实际创建数据库的情况下将在线可用数据库 API 中的数据提取到 firebase 数据库中? [关闭]

如何将 firebase 函数提取到 Swift 中的对象?