0

I want to retrieve data such as 'username' from firebase specific directory. Here is process i've tried but it's not working for some reason. Below is the part of code that i have written.I don't know whether it is correct or not.

 FirebaseDatabase database = FirebaseDatabase.getInstance();
 DatabaseReference currentu=database.getReference("Users");
enter code here
  currentu.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            User user = dataSnapshot.getValue(User.class);
            loggedinuser.setText(user.getUsername());
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

User Helper Class:

public class User {

    private String email;
    private String username;
    private String password;

    public User(){

    }

    public User(String email, String username,String password ) {

        this.email = email;
        this.username=username;
        this.password = password;
    }



    public String getEmail() {
        return email;
    }

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


    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
}

Here's the picture of my Firebase database. The red marked field(username) actually who's Currently logged in his name i want to show in a text field(loggedinuser) which i've set the getValue. firebase data

Now this process is not working.How can i retrieve the specific username who is currently logged in ?

Sign Up Class.

public class SignUp extends AppCompatActivity {

FirebaseDatabase database;
DatabaseReference users;
EditText edtUsername,edtPassword,edtMail;
Button btnSignUp,back_login;
private static final String REQUIRED = "Required";


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

    database = FirebaseDatabase.getInstance();
    users=database.getReference("Users");

    edtUsername=(EditText)findViewById(R.id.edtUsername);
    edtPassword=(EditText)findViewById(R.id.edtPassword);
    edtMail=(EditText)findViewById(R.id.edtMail);
    btnSignUp=(Button)findViewById(R.id.btnSignUp);
    back_login=(Button)findViewById(R.id.back_login);



    btnSignUp.setOnClickListener(new View.OnClickListener() {
                                     @Override
                                     public void onClick(View view) {
                                         submit();

                                     }
    }


    );
    back_login.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent i = new Intent (getApplicationContext(),Login.class);
            startActivity(i);
        }
    });


  confirm();

}

private void submit(){

    final String em = edtMail.getText().toString();
    final String en=edtUsername.getText().toString();
    final String ep= edtPassword.getText().toString();
    if(android.util.Patterns.EMAIL_ADDRESS.matcher(em).matches());

    if  (TextUtils.isEmpty(em)){
        edtMail.setError(REQUIRED);
        return;
    }

    if (TextUtils.isEmpty(en)){

        edtUsername.setError(REQUIRED);
        return;
    }
    if (TextUtils.isEmpty(ep)){
        edtPassword.setError(REQUIRED);
        return;
    }

    Toast.makeText(this, "Processing...", Toast.LENGTH_SHORT).show();

    final User user = new User(
            edtMail.getText().toString(),
            edtUsername.getText().toString(),
            edtPassword.getText().toString());


    users.addListenerForSingleValueEvent(new ValueEventListener() {

                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {

                    if (dataSnapshot.child(user.getUsername()).exists()) {
                        Toast.makeText(SignUp.this, "The username is Already Exist", Toast.LENGTH_SHORT).show();
                        setEditingEnabled(true);
                    }


                    else {
                        users.child(user.getUsername()).setValue(user);
                        Toast.makeText(SignUp.this, "Registration Successful", Toast.LENGTH_SHORT).show();
                       lukano();
                       confirmv();


                    }
                }


                @Override
                public void onCancelled(DatabaseError databaseError) {

                }
            });

}

and Here is the login.class

public class Login extends AppCompatActivity {

FirebaseDatabase database;
DatabaseReference users;
ProgressBar pbar;

EditText edtUsername,edtPassword;
Button btnSignIn;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);
    database = FirebaseDatabase.getInstance();
    users=database.getReference("Users");

    edtUsername=(EditText)findViewById(R.id.edtUsername);
    edtPassword=(EditText)findViewById(R.id.edtPassword);
    btnSignIn=(Button)findViewById(R.id.btnSignIn);
     pbar = (ProgressBar) findViewById(R.id.pb1);
      pbar.setVisibility(View.INVISIBLE);


    btnSignIn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            signIn(edtUsername.getText().toString(),
                    edtPassword.getText().toString());
            pbar.setVisibility(View.VISIBLE);

        }
    });


}

private void signIn(final String username,final String password) {
    users.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            if(dataSnapshot.child(username).exists()){

                if(!username.isEmpty()){
                    User login = dataSnapshot.child(username).getValue(User.class);
                    if(login.getPassword().equals(password)){
                        Toast.makeText(Login.this,"Log in Successful",Toast.LENGTH_SHORT).show();
                        Intent s = new Intent(getApplicationContext(),Interface.class);
                        startActivity(s);
                        finish();
                    }
                    else {
                        Toast.makeText(Login.this, "Username or Password is Incorrect", Toast.LENGTH_SHORT).show();
                    }
                }

            else
                    Toast.makeText(Login.this, "Username is not Registered", Toast.LENGTH_SHORT).show();
                }

        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });
}
Batman
  • 47
  • 1
  • 6
Rudro
  • 25
  • 1
  • 6
  • 1
    I'm confused. You ask "how can i retrieve the specific user name who's currently logged in ?", but in the title say that you're not using Firebase Authentication. In that, case: how is the user logged in? – Frank van Puffelen Feb 15 '19 at 02:09
  • 1
    Your database reference is Users, so the EventListener will return list of users not a single user. If you need only 1 user then you have to change the reference to database.getReference("Users/ab"); or if you need to loop through all users then you can try for(DataSnapshot child: dataSnapshot.getChildren()){ } – Avinash_ks Feb 15 '19 at 03:21
  • I think you need to add addChildEventListener. Because users have multiple users as a list. – Ishan Fernando Feb 15 '19 at 04:16
  • So what is the real question? Please responde with @. – Alex Mamo Feb 15 '19 at 11:20
  • Please check the updated question. @FrankvanPuffelen here i've added the signup process and login process without firebase Auth. – Rudro Feb 15 '19 at 14:40
  • Sorry Rudro, but now there is simply too much code. Also "it's not working for somereason" is not really clear. What isn't working? E.g. if you run the code in a debugger, what specific piece of the code doesn't do what you expect it to do? I highly recommend reading [how to create a minimal, complete, verifiable example](http://stackoverflow.com/help/mcve) to improve the chances someone can help. – Frank van Puffelen Feb 15 '19 at 15:11
  • i just want to show a username via which i logged in.simple @FrankvanPuffelen and the reason i've put too much code in there that is i don't use FirebaseAuth it's shown over there. – Rudro Feb 15 '19 at 15:39
  • If you're not using Firebase Authentication then you are using no authentication. So it then appears you are asking how to read a node in Firebase. Is that the question? The node you want to read is `/Users/ab/username` and that is covered in the getting started guide. Where are you getting stuck? – Jay Feb 18 '19 at 19:09

1 Answers1

0

In your firebase database, "users" child node name is same as username inside. Then how can firebase know that whether ab is trying to login or bb is trying to login and so on. Hence first using this code in the signup activity will not work.

users.child(user.getUsername()).setValue(user); //won't help later

In the firebase console, open your project and you can see Authentication tab where firebase has associated Identifier (user login email id) with a unique User UID. This helps firebase to determine who is login in (using FirebaseAuth of course later).

In your case, those child node names under "users" node are not associated with your login unless you do so first some way.

But since you said you don't want to use Firebase auth. On thing I can think of is in the signup activity use this maybe:

//users.child(user.getUsername()).setValue(user);
users.child(user.getEmail()).setValue(user);

AND pass user login email id between activities after successfully login in. Say in one of your activity you have you have retrieved this login email id and stored in variable (suppose in String loginName). Then finally you can use above first code as:

FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference currentu=database.getReference("Users").child(loginName);

currentu.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        String username = dataSnapshot.child("username").getValue().toString();
        loggedinuser.setText(username);
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {

    }
});

But if you still insist to use username in child node of "users" node. Then associate username and login email id someway first and try to work around. This might be helpful to you. How to provide user login with a username and NOT an email?

But in anyway doing so will expose your user login. Hence it is better to use FirebaseAuth as far as possible. And convenient as well. Hope this gives you some idea.

Ujjwal Jung Thapa
  • 604
  • 2
  • 8
  • 31