简体   繁体   English

从 Firebase 实时数据库中检索特定数据的最快方法?

[英]Quickest way to retrieve specific data from Firebase realtime database?

I want to retrieve specific data from my database but im not sure of the quickest method to do so.我想从我的数据库中检索特定数据,但我不确定最快的方法。 This is how I have my data in the database:这就是我在数据库中保存数据的方式:

在此处输入图像描述

I want to get the String present in the "profilePic" value for a given name ( users->Aleem->profilePic ).我想获取给定名称( users->Aleem->profilePic )的“profilePic”值中存在的字符串。

This is how Im trying to get the data:这就是我试图获取数据的方式:

String profilePicUri="";
String searchFor="any Name";
String url = "https://as*******.firebaseio.com/users.json";

StringRequest request = new StringRequest(Request.Method.GET, url, new Response.Listener<String>(){
    @Override
    public void onResponse(String s) {
            try {
                JSONObject obj = new JSONObject(s);

                if(obj.getJSONObject(searchFor).getString("users").equals(searchFor)){
                    profilePicUri=obj.getJSONObject(searchFor).getString("profilePic");


                }

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }


    }
},new Response.ErrorListener(){
    @Override
    public void onErrorResponse(VolleyError volleyError) {
        System.out.println("" + volleyError);

    }
});

RequestQueue rQueue = Volley.newRequestQueue(Login.this);
rQueue.add(request);

But the code does not work.但是代码不起作用。 Can someone tell me what way I should be retrieving this specific data and whats the good way to do it.有人可以告诉我应该以什么方式检索这些特定数据以及什么是做它的好方法。 Thanks a lot非常感谢

You dont need to do a get request, firebase already offers its own api.您不需要执行get请求,firebase 已经提供了自己的 api。 To retrieve the data you need to do the following:要检索数据,您需要执行以下操作:

DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("users").child("Aleem");
databaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
           String profilePic = dataSnapshot.child("profilePic").getValue(String.class);
           String password   = dataSnapshot.child("password").getValue(String.class);
    }
    @Override
    public void onCancelled(DatabaseError databaseError) {
        throw databaseError.toException();
    }
});

First add reference to the node Aleem , then attach a listener and you will be able to retrieve the data under Aleem .首先添加对节点Aleem的引用,然后附加一个侦听器,您将能够检索Aleem下的数据。

Check here for more information:在这里查看更多信息:

https://firebase.google.com/docs/database/android/read-and-write https://firebase.google.com/docs/database/android/read-and-write

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

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