如何在Firebase数据库中检索数据

时间:2017-12-15 02:41:48

标签: android firebase firebase-realtime-database

我正在尝试创建一个从用户获取信息的应用,然后将数据放在Firebase实时数据库中。我可以毫无问题地存储数据,但是当我尝试检索数据时,它不会出现在TextView中。

这是我的代码

public class UserProfileActivity extends AppCompatActivity {

// Creating button.
Button logout;

// Creating TextView.
TextView userEmailShow, text, text2, text3, text4, text5, text6, text7;

// Creating FirebaseAuth.
FirebaseAuth firebaseAuth;
TextView ShowDataTextView;
String NameHolder, NumberHolder;
// Creating FirebaseAuth.
FirebaseUser firebaseUser;
Firebase firebase;
public static final String Firebase_Server_URL = "https://gakusei-
go.firebaseio.com/";

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

    // Assigning ID's to button and TextView.
    logout = (Button) findViewById(R.id.logout);
    userEmailShow = (TextView) findViewById(R.id.user_email);
    text = (TextView)findViewById(R.id.textView);
    text2 = (TextView)findViewById(R.id.textView2);
    text3 = (TextView)findViewById(R.id.textView3);
    text4 = (TextView)findViewById(R.id.textView4);
    text5 = (TextView)findViewById(R.id.textView5);
    text6 = (TextView)findViewById(R.id.textView6);
    text7 = (TextView)findViewById(R.id.textView7);



    // Adding FirebaseAuth instance to FirebaseAuth object.
    firebaseAuth = FirebaseAuth.getInstance();

    // On activity start check whether there is user previously logged in or not.
    if (firebaseAuth.getCurrentUser() == null) {

        // Finishing current Profile activity.
        finish();

        // If user already not log in then Redirect to LoginActivity .
        Intent intent = new Intent(UserProfileActivity.this, LoginActivity.class);
        startActivity(intent);

        // Showing toast message.
        Toast.makeText(UserProfileActivity.this, "Please log in to continue", Toast.LENGTH_LONG).show();

    }

    // Adding firebaseAuth current user info into firebaseUser object.
    firebaseUser = firebaseAuth.getCurrentUser();

    // Getting logged in user email from firebaseUser.getEmail() method and set into TextView.
    userEmailShow.setText("Welcome " + firebaseUser.getEmail());
    firebase.child("Student").addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot MainSnapshot) {

                Student student = MainSnapshot.getValue(Student.class);

                // Adding name and phone number of student into string that is coming from server.

                    String pname = student.getPname();
                    String pnum =  student.getPhonenumber();
                    String sname = student.getStudentname();
                    String email = student.getEmail();
                    String dorm =  student.getDorm();
                    String password = student.getPassword();
                    String clas = student.getStudentclass();

                    text.setText(pname);
                    text2.setText(pnum);
                    text3.setText(sname);
                    text4.setText(email);
                    text5.setText(dorm);
                    text6.setText(password);
                    text7.setText(clas);
        }

        @Override
        public void onCancelled(FirebaseError firebaseError) {
            System.out.println("Data Access Failed" + firebaseError.getMessage());
        }
    });

当我构建apk时,它崩溃了说

  

的NullPointerException。

我搜索了如何解决它,但没有奏效。 以下是我的数据库。

enter image description here

2 个答案:

答案 0 :(得分:3)

您必须更改这些行

@Override
    public void onDataChange(DataSnapshot MainSnapshot) {

            Student student = MainSnapshot.getValue(Student.class);

            // Adding name and phone number of student into string that is coming from server.

                String pname = student.getPname();
                String pnum =  student.getPhonenumber();
                String sname = student.getStudentname();
                String email = student.getEmail();
                String dorm =  student.getDorm();
                String password = student.getPassword();
                String clas = student.getStudentclass();

                text.setText(pname);
                text2.setText(pnum);
                text3.setText(sname);
                text4.setText(email);
                text5.setText(dorm);
                text6.setText(password);
                text7.setText(clas);
    }

由此

@Override
    public void onDataChange(DataSnapshot MainSnapshot) {

         for(DataSnapshot datasnapShot:MainSnapshot.getChildren()){
            Student student = datasnapShot.getValue(Student.class);

            // Use yore logic here... Use ArrayList<Student> or anything to  Store  the details

                String pname = student.getPname();
                String pnum =  student.getPhonenumber();
                String sname = student.getStudentname();
                String email = student.getEmail();
                String dorm =  student.getDorm();
                String password = student.getPassword();
                String clas = student.getStudentclass();

                text.setText(pname);
                text2.setText(pnum);
                text3.setText(sname);
                text4.setText(email);
                text5.setText(dorm);
                text6.setText(password);
                text7.setText(clas);
               }            
    }

答案 1 :(得分:0)

如果您要显示与特定用户相关的详细信息,请先使用唯一密钥(用户的uid)而不是pushId将详细信息保存在数据库中。 你可以这样做......

//Get user object
  FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
  if(user != null) {
    //Save data in database
    Student mStudent = new Student(......)  //Your Student Object
     FirebaseDatabase.getInstance().getReference().child("Student").child(user.getUid()).setValue(mStudent);
  }

现在您可以获得像这样的特定用户的数据......

FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if(user != null) {
FirebaseDatabse.getInstance().getReference().child("Student").child(user.getUid()).addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot mainSnapshot) {

            Student student = mainSnapshot.getValue(Student.class);

            // Adding name and phone number of student into string that is coming from server.

                String pname = student.getPname();
                String pnum =  student.getPhonenumber();
                String sname = student.getStudentname();
                String email = student.getEmail();
                String dorm =  student.getDorm();
                String password = student.getPassword();
                String clas = student.getStudentclass();

                text.setText(pname);
                text2.setText(pnum);
                text3.setText(sname);
                text4.setText(email);
                text5.setText(dorm);
                text6.setText(password);
                text7.setText(clas);
    }

    @Override
    public void onCancelled(FirebaseError firebaseError) {
        System.out.println("Data Access Failed" + firebaseError.getMessage());
    }
});
}

在你的代码中,你正在为'firebase'添加一个子事件监听器,你没有在任何地方初始化,这就是抛出NullPointerException的原因......