Firebase Database returns null every time while reading

烈酒焚心 提交于 2019-12-11 13:23:38

问题


I have a class to read data from my database but it always returns null.

Here's the java file

public class UserActivity extends AppCompatActivity {

    TextView textView;
    private FirebaseDatabase mFirebaseDatabase;
    private FirebaseAuth mAuth;
    private FirebaseAuth.AuthStateListener mAuthListener;
    private DatabaseReference myRef;
    private String userID;


    private String TAG = "hifiwi";

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


        textView = (TextView) findViewById(R.id.textView);

        //////////////////////////////////////////////////////////////
        mAuth = FirebaseAuth.getInstance();
        mFirebaseDatabase = FirebaseDatabase.getInstance();
        myRef = mFirebaseDatabase.getReference();
        FirebaseUser user = mAuth.getCurrentUser();
        userID = user.getUid();
        mAuthListener = new FirebaseAuth.AuthStateListener() {
            @Override
            public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
                FirebaseUser user = mAuth.getCurrentUser();
                if (user != null) {
                    Toast.makeText(UserActivity.this, "Signed in with " + user.getEmail(), Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(UserActivity.this, "Successfully signed out...", Toast.LENGTH_SHORT).show();
                }
            }
        };

        myRef.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                showData(dataSnapshot);
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });


        ///////////////////////////////////////////////////////////////


    }

    private void showData(DataSnapshot dataSnapshot) {
        for (DataSnapshot ds : dataSnapshot.getChildren()) {
            UserInformation uInfo = new UserInformation();
            uInfo.setEmail(ds.child(userID).getValue(UserInformation.class).getEmail());
            uInfo.setName(ds.child(userID).getValue(UserInformation.class).getName());
            uInfo.setPassword(ds.child(userID).getValue(UserInformation.class).getPassword());
            uInfo.setPhoneno(ds.child(userID).getValue(UserInformation.class).getPhoneno());

            Log.i(TAG, " " + uInfo.getEmail());    //Always returning null
            Log.i(TAG, " " + uInfo.getName());    //Always returning null
            Log.i(TAG, " " + uInfo.getPassword());    //Always returning null
            Log.i(TAG, " " + uInfo.getPhoneno());    //Always returning null

        }
    }

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

        mAuth.addAuthStateListener(mAuthListener);
    }

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

        mAuth.removeAuthStateListener(mAuthListener);
    }
}

The log statements always return null.

This is my database structure under t2-login(the project name).

{
  "Users" : {
    "8dQ8unnqQXa69nkxUFKrcgiTM3S2" : {
      "emailuser" : "sam@gmail.com",
      "mobileUser" : "1234567899",
      "nameuser" : "sam",
      "passworduser" : "sammypp"
    },
    "DIMBAk4CHZdWGbxN9kPESwIrw9b2" : {
      "emailuser" : "hsjsjsjjsjsj@mdm.mdmdmdmndn",
      "mobileUser" : "9999999999",
      "nameuser" : "hshs",
      "passworduser" : "ppppppl"
    },
    "YJhf16ZyfWUn1Dou3BPcIkSSmVm1" : {
      "emailuser" : "test2@gmail.com",
      "mobileUser" : "1234567892",
      "nameuser" : "test2",
      "passworduser" : "test2pp"
    },
    "yQEFEe5x06hvSZP18Mmb6OfNqnB2" : {
      "emailuser" : "test1@gmail.com",
      "mobileUser" : "1234567891",
      "nameuser" : "test1",
      "passworduser" : "test1pp"
    }
  }
}

The UserInformation.class

package com.rishav.t2;

/**
 * Created by rishav on 6/27/2017.
 */

public class UserInformation {
    private String email;
    private String name;
    private String phoneno;
    private String password;

    public UserInformation() {
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPhoneno() {
        return phoneno;
    }

    public void setPhoneno(String phoneno) {
        this.phoneno = phoneno;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

回答1:


Set myRef to: myRef = FirebaseDatabase.getInstance().getReference("Users").child(user.getUid());

Also change this:

  private void showData(DataSnapshot dataSnapshot) {

            UserInformation uInfo = ds.getValue(UserInformation.class);
            Log.i(TAG, " " + uInfo.getEmail());    //Always returning null
            Log.i(TAG, " " + uInfo.getName());    //Always returning null
            Log.i(TAG, " " + uInfo.getPassword());    //Always returning null
            Log.i(TAG, " " + uInfo.getPhoneno());    //Always returning null


    }

Have UserInformation class variables match the key names that exist in the firebase database:

public class UserInformation {
public String emailuser;
public String nameuser;
public String mobileUser;
public String passworduser;

public UserInformation() {
}

public String getEmail() {
    return email;
}

public void setEmail(String email) {
    this.email = email;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getPhoneno() {
    return phoneno;
}

public void setPhoneno(String phoneno) {
    this.phoneno = phoneno;
}

public String getPassword() {
    return password;
}

public void setPassword(String password) {
    this.password = password;
}

}




回答2:


try this

  myRef.child("Users").addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                showData(dataSnapshot);
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });



回答3:


Try this way

FirebaseDatabase database = FirebaseDatabase.getInstance();
     DatabaseReference myRef = database.getReference("users");
     myRef.addValueEventListener(new ValueEventListener() { 
            @Override 
            public void onDataChange(DataSnapshot dataSnapshot) {
                userList = new ArrayList<User>();
                dataSnapshot.getChildrenCount();
                //List<User> list= new ArrayList<User>(); 
                for (DataSnapshot childDataSnapshot : dataSnapshot.getChildren()) {
                    User user = childDataSnapshot.getValue(User.class);
                    userList.add(user);
                } 
                Log.e("hello","childDataSnapshot"+ userList.size());

                adapter.update(userList); 

            } 

            @Override 
            public void onCancelled(DatabaseError error) {
                // Failed to read value 
                Log.w("MY", "Failed to read value.", error.toException());
            } 
        }); 



回答4:


Have you checked the rule of your firebase project setting

Firebase rules provides a way to identify user role while performing read and write operations. These rules will acts a security layer on the server before perform any CRUD operation. By default the rules allows user to perform read & write operation only after authentication.

The below rules allow authenticated users only to read or write data.
{
  "rules": {
    ".read": "auth != null",
    ".write": "auth != null"
  }
}

Below rules allows everyone to read & write data without authentication.

{
  "rules": {
    ".read": true,
    ".write": true
  }
}

You can also use these rules to validate data before inserting into database. For example below rules validates the name to be less than 50 chars and email to be valid using email regular expression.

{
    "rules": {
        ".read": true,
        ".write": true,
        "users": {
            "$user": {
                "name": {
                    ".validate": "newData.isString() && newData.val().length < 50"
                },
                "email": {
                    ".validate": "newData.isString() && newData.val().matches(/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,4}$/i)"
                }
            }
        }
    }
}

For detailed tutorial check this link



来源:https://stackoverflow.com/questions/44772906/firebase-database-returns-null-every-time-while-reading

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!