如何使用数据快照跨多个子节点检索数据?

时间:2018-03-13 09:32:50

标签: android firebase firebase-realtime-database

我想检索每个userID节点中找到的eventName和eventSport值。

我还是Android Studio新手。

我的firebase数据库按以下方式组织:

throw new BadRequestHttpException('Message', null, 418);

因为每次不同的用户将数据上传到数据库时,数据都会从Firebase身份验证中存储在其firebase用户ID节点中。有没有办法让我仍然从每个用户生成的节点检索数据,同时仍然允许用户通过自己的UserID存储他们的数据? 我使用他们的userID来设置FirabaseDatabase中的读写规则。

Host_Activity.java:

fir-login-31***
 event
  userID(retrieved from firebase authentication)
    Unique EventID(randomly generated by me)
      eventID: "Unique EventID
      eventName: "Test1
      eventSport: "TestSport12

Event.java:

package com.example.songkwongwee.myapplication;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.Toast;

import com.google.firebase.auth.FirebaseAuth;
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 HostActivity extends AppCompatActivity {

    EditText editTextName;
    Button buttonAdd;
    Spinner spinnerSports;

    DatabaseReference databaseEvent;
    FirebaseAuth mAuth;

    ListView listViewEvents;

    List<Event> eventList;

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

        databaseEvent = FirebaseDatabase.getInstance().getReference("event");

        mAuth = FirebaseAuth.getInstance();

        editTextName = findViewById(R.id.editTextName);
        buttonAdd = findViewById(R.id.buttonHostGame);
        spinnerSports = findViewById(R.id.spinnerSports);

        listViewEvents = findViewById(R.id.listViewEvents);

        eventList = new ArrayList<>();

        buttonAdd.setOnClickListener(new View.OnClickListener() {   //click button method for adding event
            @Override
            public void onClick(View v) {
                addEvent();
            }
        });

    }

    @Override
    protected void onStart() {
        super.onStart();

        databaseEvent.addValueEventListener(new ValueEventListener() { //executed every time we change anything in database
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {   //contains all data in snapshot data object

                eventList.clear(); //clear artist list

                for(DataSnapshot eventSnapshot: dataSnapshot.getChildren()){
                    Event event = eventSnapshot.getValue(Event.class);

                    eventList.add(event); //every time new data entered, this method executes,fetch all artist from database
                }

                EventList adapter = new EventList(HostActivity.this, eventList);
                listViewEvents.setAdapter(adapter);

            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });
    }


    private void addEvent(){   //method for user to create event
        String name = editTextName.getText().toString().trim();
        String sport = spinnerSports.getSelectedItem().toString();

        if(!TextUtils.isEmpty(name)){   //if name is not empty

            String uid = mAuth.getUid(); //call uid method to get user id

            String id = databaseEvent.push().getKey();  //call id method to get random string key

            Event event = new Event(id, name, sport); //call event method to

            databaseEvent.child(uid).child(id).setValue(event);  //method to store node in organise form (Event>UserID>Event.UKey>Details)

            Toast.makeText(this,"Event added",Toast.LENGTH_LONG).show();    //Show UI
        }
        else{   //if name is empty
            Toast.makeText(this,"You should enter a name", Toast.LENGTH_LONG).show();   //Show error UI
        }

    }
}

1 个答案:

答案 0 :(得分:1)

要检索eventname和eventsport,请尝试以下操作:

FirebaseUser user=FirebaseAuth.getInstance().getCurrentUser();
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("event").child(user.getUid());;

reference.addListenerForSingleValueEvent(new ValueEventListener() {
 @Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot datas: dataSnapshot.getChildren()){
   String eventname=datas.child("eventName").getValue().toString();
   String eventsport=datas.child("eventSport").getValue().toString();
    }
 }
 @Override
public void onCancelled(DatabaseError databaseError) {
  }
 });

你有这个数据库:

event
userID(retrieved from firebase authentication)
 Unique EventID(randomly generated by me)
    eventID: "Unique EventID
    eventName: "Test1
    eventSport: "TestSport12

每个userid对于该用户都是唯一的,并且由于您希望用户检索他的数据,因此您可以使用user.getUid()来检索用户ID,然后在其中进行迭代以获取eventname和eventsport。