简体   繁体   English

如何在我的 RecyclerView 中显示来自 firebase 的子数据?

[英]How do I display child of child's data from firebase in my RecyclerView?

I want to show data of all children inside all the Categories from the database (added the image below of what my database looks).我想显示数据库中所有类别中所有子项的数据(添加了下面我的数据库外观的图像)。 I am adding data to my RecyclerView using the adapter which needs FirebaseRecyclerOptions object to be passed.我正在使用需要传递 FirebaseRecyclerOptions object 的适配器将数据添加到我的 RecyclerView。 I saw one answer where DataSnapshot was used to get child of child data, I tried to get the data using that and it showed me when I logged it in logcat (the commented code is what I tried using), but I do not know how to use that with my Adapter class.我看到一个答案,其中 DataSnapshot 用于获取子数据的子数据,我尝试使用它获取数据,当我将其登录到 logcat 时它显示给我(注释代码是我尝试使用的代码),但我不知道如何与我的适配器 class 一起使用。

This is what my database looks, I want the data inside of the highlighted fields:这是我的数据库的样子,我想要突出显示的字段中的数据:

{
    "Category_wise": {
        "education": {
            "udemy": {     <-Return data of this child
                "companyName": "Udemy",
                ...
            },
            "khanacademy": {     <-Return data of this child
                "companyName": "Khan Academy",
                ...
            }
        },
        "technology": {
            "google": {    <-Return data of this child
                "companyName": "Google",
                ...
            },
            "facebook": {    <-Return data of this child
                "companyName": "Facebook",
                ...
            },
        ....
    }   
}

In the below code, SCard is my Model Class and SCardAdapter is my Adapter Class.在下面的代码中,SCard 是我的 Model Class,SCardAdapter 是我的 Adapter Class。

This is my Fragment (HomeFragment) where I'm adding data into recyclerview:这是我的片段(HomeFragment),我将数据添加到 recyclerview 中:

public class HomeFragment extends Fragment{
    private RecyclerView recyclerView;
    private Query query;
    private SCardAdapter<SCard, SCardAdapter.ViewHolder> adapter;

    public HomeFragment() {}

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_home, container, false);
        recyclerView = v.findViewById(R.id.search_recyclerview);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
        recyclerView.setLayoutManager(linearLayoutManager);
        recyclerView.setHasFixedSize(true);

        setQueryByOrder("technology", "totalInvestors");
        fetchResult(query);

        return v;
    }

//    protected void fetchAll(){
//        final DatabaseReference reference= FirebaseDatabase.getInstance().getReference("Category_wise");
//        reference.addValueEventListener(new ValueEventListener() {
//            @Override
//            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
//                for (DataSnapshot snapshot : dataSnapshot.getChildren()){
//                    Log.i(TAG, "4321: Name of each company: " + Objects.requireNonNull(snapshot.child("companyName").getValue()).toString()
//                }
//            }
//            @Override
//            public void onCancelled(@NonNull DatabaseError databaseError) {}
//        });
//    }

    protected void setQueryByOrder(String choice, String order){
        query = FirebaseDatabase.getInstance()
                .getReference()
                .child("Category_wise").child(choice).orderByChild(order);
    }

    protected void fetchResult(Query query) {
        FirebaseRecyclerOptions<SCard> options =
                new FirebaseRecyclerOptions.Builder<SCard>()
                        .setQuery(query, new SnapshotParser<SCard>() {
                            @NonNull
                            @Override
                            public SCard parseSnapshot(@NonNull DataSnapshot snapshot) {
                                return new SCard(
                                        Objects.requireNonNull(snapshot.child("companyName").getValue()).toString()...);
                            }
                        })
                        .build();
        adapter = new SCardAdapter<>(options);
        adapter.startListening();
        recyclerView.setAdapter(adapter);
    }

    @Override
    public void onStart() {
        super.onStart();
        adapter.startListening();
    }

    @Override
    public void onStop() {
        super.onStop();
        adapter.stopListening();
    }
}

This is my Adapter Class:这是我的适配器 Class:

public class SCardAdapter<M extends SCard, V extends SCardAdapter.ViewHolder> extends FirebaseRecyclerAdapter<SCard, V> {

    FirebaseRecyclerOptions<SCard> options;
    public SCardAdapter(@Nullable FirebaseRecyclerOptions<SCard> options) {
        super(options);
        this.options = options;
    }

    @Override
    protected void onBindViewHolder(V holder, @SuppressLint("RecyclerView") final int position, SCard model) {
        holder.setName(model.getsName());
      ...
    }

    @Override
    public V onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.startup_search_card, parent, false);
        return (V) new ViewHolder(view);
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        ImageView simg2;
        TextView sname, sdesc, senddate, sperraised, snoin, sminam;
        ProgressBar sraisingprogbar;
        public ViewHolder(View itemView) {
            super(itemView);
            sname = itemView.findViewById(R.id.sname);
          ...
        }

        public void setName(String string) {
            sname.setText(string);
        }
      ...
    }
}

First of all, you need to create 2 loops since your json looks like that and store them inside an arrayList .首先,您需要创建 2 个循环,因为您的 json 看起来像那样,并将它们存储在arrayList中。 You are suppose to get all the data there inside the arrayList.您假设在 arrayList 中获取所有数据。

FirebaseDatabase.getInstance().getReference().child("Category_wise").addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
        if (dataSnapshot.exists()) {
            ArrayList<Scard> sCardList = new ArrayList<Scard>();
            for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
                if (snapshot.exists()){
                    for (DataSnapshot shot : snapshot.getChildren()){
                        if (shot.exists()){
                            final Scard scard = shot.getValue(Scard.class);
                            if (scard != null){
                                sCardList.add(scard);
                            }
                        }
                    }
                }
            }
            final ScardAdapter scardAdapter = new ScardAdapter(sCardList);
            recyclerView.setAdapter(scardAdapter);
        }
    }
    @Override
    public void onCancelled(@NonNull DatabaseError databaseError) {
    }
});

Next you need to create your own adapter.接下来您需要创建自己的适配器。 You can search on Google also for more information.您也可以在 Google 上搜索以获取更多信息。 But you will get the point here.但是你会明白这一点的。

public class ScardAdapter extends RecyclerView.Adapter<ScardViewHolder> {
    private ArrayList<Scard> sCardList;
    public ScardAdapter(final ArrayList<Scard> sCardList) {
        this.sCardList = sCardList;
    }
    @NonNull
    @Override
    public ScardViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.scard_item, parent, false);
        return new ScardViewHolder(view);
    }
    @Override
    public void onBindViewHolder(@NonNull final ScardViewHolder holder, final int position) {
        final Scard model = sCardList.get(position);
        holder.getTvCompanyName.setText(model.getCompanyName);
    }
    @Override
    public int getItemCount() {
        return sCardList.size();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM