从firebase获取数据时Recyclerview为空白

Posted

技术标签:

【中文标题】从firebase获取数据时Recyclerview为空白【英文标题】:Recyclerview is blank when getting data from firebase 【发布时间】:2019-11-08 16:06:59 【问题描述】:

我正在从 Firebase 获取数据并将其显示在回收站视图中。当我运行它时,什么都没有出现,我也没有收到任何错误。调试器显示我正在正确检索所有数据,但它显示 arraylist 一直返回零大小。

这是我的数据库结构:


 "Classes" : 
   "-LiGRe3e1YF_HFrHKMgi" : 
  "Students" : 
    "-LiId4URjJ8SWLAP4f4i" : "UhTQgJ4jugMqFtEZK8CsIkTqQl22",
    "-LiIeT5t1T7JpcUee_MJ" : "UhTQgJ4jugMqFtEZK8CsIkTqQl22"
  ,
  "class_info" : 
    "date_clasname" : "mm",
    "room_number" : "jjhh",
    "subject" : "Science",
    "teacher" : "mm",
    "uid" : "-LiGRe3e1YF_HFrHKMgi"
  

  ,
   "Users" : 
    "UhTQgJ4jugMqFtEZK8CsIkTqQl22" : 
    "Classes" : 
    "-LiIeT5slTjC0B3lEqNJ" : "-LiGRe3e1YF_HFrHKMgi"
    "-LiIeT5slTjC0B3lEqNJ" : "-LiGRe3e1YF_HFrHKMgi"
  ,
    "User_info" : 
    "email" : "samuelford48@gmail.com",
    "grade" : "12",
    "name" : "Samuel"
  

这是我的活动的代码:

public class home_fragment extends Fragment implements View.OnClickListener 
private Button button;
//DatabaseReference dref;
//ListView listview2;
//ArrayList<String> list=new ArrayList<>();
private FirebaseDatabase database;
private DatabaseReference myRef;
private List<Listdata> list;
private RecyclerView recyclerview;
public home_fragment() 



@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) 
    View view = inflater.inflate(R.layout.home_fragment, container, false);
    //FirebaseUser fbUser = FirebaseAuth.getInstance().getCurrentUser();
    //if(fbUser == null)  Intent intent = new Intent(getContext(), LoginActivity.class);
    // startActivity(intent);

    button = (Button) view.findViewById(R.id.button);
    button.setOnClickListener(this);
    recyclerview = (RecyclerView) view.findViewById(R.id.rview);
    database = FirebaseDatabase.getInstance();
    myRef = database.getReference("Users")
            .child(FirebaseAuth.getInstance().getCurrentUser().getUid()).child("Classes");
    myRef.addChildEventListener(new ChildEventListener() 
        @Override
        public void onChildAdded(@NonNull DataSnapshot dataSnapshot, String s) 

            list = new ArrayList<>();
                String class_id = dataSnapshot.getValue(String.class);

                myRef = database.getReference("Classes").child(class_id).child("class_info");
            // StringBuffer stringbuffer = new StringBuffer();
            myRef.addListenerForSingleValueEvent(new ValueEventListener() 


                @Override
                public void onDataChange(@NonNull DataSnapshot dataSnapshot) 

                        Class_model new_class = dataSnapshot.getValue(Class_model.class);
                        assert new_class != null;
                        String nameofclass = new_class.getDate_clasname();
                        String teacherofclass = new_class.getTeacher();
                        String roomnumberofclass = new_class.getRoom_number();
                        String class_key = new_class.getUid();
                        Listdata listdata = new Listdata(nameofclass, teacherofclass, roomnumberofclass, class_key);
                        //String name = userdetails.getName();
                        //String email = userdetails.getEmail();
                        //String address = userdetails.getAddress();
                        listdata.setDate_class(nameofclass);
                        listdata.setTeacher(teacherofclass);
                        listdata.setRnumber(roomnumberofclass);
                    list.add(listdata);
                        // Toast.makeText(MainActivity.this,""+name,Toast.LENGTH_LONG).show();
                    


                @Override
                public void onCancelled(DatabaseError error) 
                    AlertDialog alertDialog = new AlertDialog.Builder(getContext()).create();
                    alertDialog.setTitle("Error");
                    alertDialog.setMessage("Check your connection! If, problem persists please email svhsdev@vigoschools.org!");
                    alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
                            new DialogInterface.OnClickListener() 
                                public void onClick(DialogInterface dialog, int which) 
                                    dialog.dismiss();
                                
                            );
                    alertDialog.show();
                

            );

            RecyclerviewAdapter2 recycler = new RecyclerviewAdapter2(list);
            RecyclerView.LayoutManager layoutmanager = new LinearLayoutManager(getContext());
            recyclerview.setLayoutManager(layoutmanager);
            recyclerview.setItemAnimator(new DefaultItemAnimator());
            recyclerview.setAdapter(recycler);

        
        @Override
        public void onChildChanged(@NonNull DataSnapshot dataSnapshot, @Nullable String s) 

        

        @Override
        public void onChildRemoved(@NonNull DataSnapshot dataSnapshot) 

        

        @Override
        public void onChildMoved(@NonNull DataSnapshot dataSnapshot, @Nullable String s) 

        
        @Override
        public void onCancelled(DatabaseError error) 
            AlertDialog alertDialog = new AlertDialog.Builder(getContext()).create();
            alertDialog.setTitle("Error");
            alertDialog.setMessage("Check your connection! If, problem persists please email svhsdev@vigoschools.org!");
            alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
                    new DialogInterface.OnClickListener() 
                        public void onClick(DialogInterface dialog, int which) 
                            dialog.dismiss();
                        
                    );
            alertDialog.show();
        

                                );
    return view;

@Override
public void onClick(View view) 
    signout();



    //startActivity(new Intent(home_fragment.this, LoginActivity.class));


public void signout()
    FirebaseAuth.getInstance().signOut();
    Intent intent = new Intent(getContext(), LoginActivity.class);
    startActivity(intent);


   
 

首先,Activity 获取类的 id,这些 id 存储在用户的类下,然后它获取类信息并将其显示在 recyclerview 中。 这是我的适配器的代码(这里应该没有问题):

public class RecyclerviewAdapter2 extends RecyclerView.Adapter<RecyclerviewAdapter2.MyHolder>

List<Listdata> listdata;

public RecyclerviewAdapter2(List<Listdata> listdata) 
    this.listdata = listdata;


@Override
public RecyclerviewAdapter2.MyHolder onCreateViewHolder(ViewGroup parent, int viewType) 
    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.cardview_class_model,parent,false);

    RecyclerviewAdapter2.MyHolder myHolder = new RecyclerviewAdapter2.MyHolder(view);
    return myHolder;



public void onBindViewHolder(RecyclerviewAdapter2.MyHolder holder, final int position) 
    final Listdata data = listdata.get(position);
    holder.vdate_class.setText(data.getDate_class());
    holder.vteacher.setText(data.getTeacher());
    holder.vrnumber.setText(data.getRnumber());
    //System.out.println(data.getDate_class2());
    holder.itemView.setOnClickListener(new View.OnClickListener()
    
        @Override
        public void onClick( final View view) 
            Context context = view.getContext();
            Intent intent = new Intent(context, Add_class_to_user.class);
            intent.putExtra("date_class", listdata.get(position).getDate_class());
            intent.putExtra("teacher", listdata.get(position).getTeacher());
            intent.putExtra("room_number", listdata.get(position).getRnumber());
            intent.putExtra("post_key", listdata.get(position).getUid());
            context.startActivity(intent);
        
    );



@Override
public int getItemCount() 
    return listdata.size();



class MyHolder extends RecyclerView.ViewHolder
    TextView vdate_class , vteacher,vrnumber;

    public MyHolder(View itemView) 
        super(itemView);
        vdate_class = (TextView) itemView.findViewById(R.id.date_class_name);
        vteacher = (TextView) itemView.findViewById(R.id.teacher);
        vrnumber = (TextView) itemView.findViewById(R.id.room_number);

    
   


谢谢您,如果您有任何问题,请告诉我!

【问题讨论】:

【参考方案1】:

您需要在数据添加到列表后调用ADAPTER_NAME.notifyDataSetChanged() 以反映RecyclerView 中的更改。不要忘记将ADAPTER_NAME 替换为实际的适配器名称。

【讨论】:

您应该在将项目添加到列表后执行adapter.notifyDataSetChanged()【参考方案2】:

你在调用这个逻辑

 database = FirebaseDatabase.getInstance();
    myRef = database.getReference("Users")
            .child(FirebaseAuth.getInstance().getCurrentUser().getUid()).child("Classes");
    myRef.addChildEventListener(new ChildEventListener() 
        @Override
        public void onChildAdded(@NonNull DataSnapshot dataSnapshot, String s) 

            list = new ArrayList<>();
                String class_id = dataSnapshot.getValue(String.class);

                myRef = database.getReference("Classes").child(class_id).child("class_info");
            // StringBuffer stringbuffer = new StringBuffer();
            myRef.addListenerForSingleValueEvent(new ValueEventListener() 


                @Override
                public void onDataChange(@NonNull DataSnapshot dataSnapshot) 

                        Class_model new_class = dataSnapshot.getValue(Class_model.class);
                        assert new_class != null;
                        String nameofclass = new_class.getDate_clasname();
                        String teacherofclass = new_class.getTeacher();
                        String roomnumberofclass = new_class.getRoom_number();
                        String class_key = new_class.getUid();
                        Listdata listdata = new Listdata(nameofclass, teacherofclass, roomnumberofclass, class_key);
                        //String name = userdetails.getName();
                        //String email = userdetails.getEmail();
                        //String address = userdetails.getAddress();
                        listdata.setDate_class(nameofclass);
                        listdata.setTeacher(teacherofclass);
                        listdata.setRnumber(roomnumberofclass);
                    list.add(listdata);
                        // Toast.makeText(MainActivity.this,""+name,Toast.LENGTH_LONG).show();
                    


                @Override
                public void onCancelled(DatabaseError error) 
                    AlertDialog alertDialog = new AlertDialog.Builder(getContext()).create();
                    alertDialog.setTitle("Error");
                    alertDialog.setMessage("Check your connection! If, problem persists please email svhsdev@vigoschools.org!");
                    alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
                            new DialogInterface.OnClickListener() 
                                public void onClick(DialogInterface dialog, int which) 
                                    dialog.dismiss();
                                
                            );
                    alertDialog.show();
                

            );

            RecyclerviewAdapter2 recycler = new RecyclerviewAdapter2(list);
            RecyclerView.LayoutManager layoutmanager = new LinearLayoutManager(getContext());
            recyclerview.setLayoutManager(layoutmanager);
            recyclerview.setItemAnimator(new DefaultItemAnimator());
            recyclerview.setAdapter(recycler);

        
        @Override
        public void onChildChanged(@NonNull DataSnapshot dataSnapshot, @Nullable String s) 

        

        @Override
        public void onChildRemoved(@NonNull DataSnapshot dataSnapshot) 

        

        @Override
        public void onChildMoved(@NonNull DataSnapshot dataSnapshot, @Nullable String s) 

        
        @Override
        public void onCancelled(DatabaseError error) 
            AlertDialog alertDialog = new AlertDialog.Builder(getContext()).create();
            alertDialog.setTitle("Error");
            alertDialog.setMessage("Check your connection! If, problem persists please email svhsdev@vigoschools.org!");
            alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
                    new DialogInterface.OnClickListener() 
                        public void onClick(DialogInterface dialog, int which) 
                            dialog.dismiss();
                        
                    );
            alertDialog.show();
        

                                );

在你的onCreateView()方法中,因为这是一个Fragment,在onCreateView()你应该只有视图初始化,然后在onViewCreated()onActivityCreated()你应该有上面的代码。

我认为问题的出现是因为在实例化视图后,您调用了一个异步过程(从 firebase 获取数据)来填充您的 RecyclerView,但未达到 RecyclerView 视图。

【讨论】:

你能告诉我怎么做吗?我试过了,我不确定我做对了,但它没有用 只需像使用 onCreateView() 一样覆盖 onViewCreated()

以上是关于从firebase获取数据时Recyclerview为空白的主要内容,如果未能解决你的问题,请参考以下文章

从 Firebase RTD 获取数据时获取 null

使用 Firebase 从不同的集合中获取数据,并在数据更改时更新 UI

从firebase数据库获取数据到android应用程序时使用进度条

从 Firebase android kotlin 获取数据时如何显示加载的项目

尝试从Firebase数据库获取时无法获取CarType

从 firebase 数据库获取数据时显示进度对话框