【问题标题】:How to retrieve data in Firebase Database如何在 Firebase 数据库中检索数据
【发布时间】:2017-12-15 13:58:47
【问题描述】:

我正在尝试创建一个应用程序,该应用程序从用户那里获取信息,然后将数据放在 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。

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

【问题讨论】:

  • 你能更新错误日志吗?和你的模型班学生
  • NullPointerException 通常应该清楚地指出代码中的哪一行导致它。从那里开始,就是追踪为什么是null 并修复它。见stackoverflow.com/questions/218384/…

标签: android firebase firebase-realtime-database


【解决方案1】:

你必须改变这些行

@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);
               }            
    }

【讨论】:

    【解决方案2】:

    如果您尝试显示与特定用户相关的详细信息,请首先使用唯一键(用户的 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 的原因...

    【讨论】:

      猜你喜欢
      • 2016-11-27
      • 1970-01-01
      • 2016-11-22
      • 2021-08-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多