首页 > 解决方案 > 如何从简单的 Cloud Firestore 结构中检索数据

问题描述

我正在尝试从 Cloud firestore 数据库中检索简单数据。使用以下代码,我试图显示集合“prodotti”中的 2 个属性,但 toast 消息没有出现,日志消息也没有出现。请问有人能找到问题吗?(这个项目是他的起点,不要因为公共规则而责备我,但我试图了解基础知识是如何工作的)

这是数据库结构:

数据库结构截图

我尝试读取这些数据的片段:

public class FragmentHome extends Fragment {

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View fragmentHomeView=inflater.inflate(R.layout.fragment_layout_home_vuoto, container, false);
        return fragmentHomeView;
    }

    //debug message
    //Toast.makeText(getContext(), "debug", Toast.LENGTH_LONG).show();

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        DatabaseReference root= FirebaseDatabase.getInstance().getReference();
        final DatabaseReference prodotti= root.child("prodotti");
        final TextView nulla=(TextView) view.findViewById(R.id.textCarrelloVuoto);
        ImageView carr=(ImageView) view.findViewById(R.id.immagineCarrelloVuoto);
        ValueEventListener vel=new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                String line="";
                for(DataSnapshot ds : dataSnapshot.getChildren()){
                    String nome=ds.child("nome").getValue(String.class);
                    String ndisp=ds.child("ndisp").getValue(String.class);
                    line.concat(nome+" "+ndisp);
                    Toast.makeText(getContext(), line, Toast.LENGTH_LONG).show();
                }
                Log.i("TAG", line);
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        };
        prodotti.addListenerForSingleValueEvent(vel);

    }

}

“Prodotti”类:

public class Prodotti {

    public int id;
    public String nome;
    public boolean disponibile;
    public int ndisp;

    public Prodotti(){
        //chiamate da dataSnapshot
    }

    public Prodotti(int fid, String fnome, boolean fdisp, int fndisp){
        this.id=fid;
        this.nome=fnome;
        this.ndisp=fndisp;
        this.disponibile=fdisp;
    }

}

标签: androidfirebasefirebase-realtime-databasegoogle-cloud-firestore

解决方案


此代码未访问 Cloud Firestore。它正在访问实时数据库。屏幕截图显示了 Cloud Firestore,但代码永远不会看到该数据,因为它是一个完全不同的数据库产品。

请使用Cloud Firestore 的文档来了解如何使用它。


推荐阅读