1

My Database in firebase is in this format

I need that if a user login then for that particular UID I need his associated department name. So How to take the department name as a String.I use this code to fetch department name

 String u_id=auth.getCurrentUser().getUid();
 mdatabase=FirebaseDatabase.getInstance().getReference().child("Users").child(u_id).child("department");
                         user=mdatabase.getKey();

By this i don't get the result.Please provide solution

public class LoginPage extends AppCompatActivity {
private Button btnLogin;
private TextView ForgetText;
private EditText userText,PassText;
private String UserEmail,UserPassword;
private FirebaseAuth auth;
private FirebaseAuth.AuthStateListener mAuthlistener;
private ProgressBar progressBar;
private DatabaseReference mdatabase;
public String departmental;
//private Spinner dropdown;
Variables v=new Variables();
private String username,user;
private Intent i;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login_page);


    auth=FirebaseAuth.getInstance();
    btnLogin=(Button)findViewById(R.id.btn_login);
    ForgetText=(TextView)findViewById(R.id.textView3);
    userText=(EditText)findViewById(R.id.email2);
    PassText=(EditText)findViewById(R.id.password2);
    progressBar=(ProgressBar)findViewById(R.id.progressBar2);

    btnLogin.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            SignIn();
        }
    });

    ForgetText.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            startActivity(new Intent(LoginPage.this,ForgotPassword.class));
        }
    });
}

public void SignIn(){

   UserEmail=userText.getText().toString().trim();
    UserPassword=PassText.getText().toString().trim();
if (UserEmail.isEmpty()){
Toast.makeText(LoginPage.this,"Please Enter the Email 
Id",Toast.LENGTH_LONG).show();
}
else if (UserPassword.isEmpty())
{
Toast.makeText(LoginPage.this,"Please enter Valid 
Password",Toast.LENGTH_LONG).show();
}
else {
auth.signInWithEmailAndPassword(UserEmail, UserPassword)
        .addOnCompleteListener(LoginPage.this, new 
OnCompleteListener<AuthResult>() {
            @Override
            public void onComplete(@NonNull Task<AuthResult> task) {
                // If sign in fails, display a message to the user. If 
sign in succeeds
                // the auth state listener will be notified and logic 
to handle the
                // signed in user can be handled in the listener.
                if (!task.isSuccessful()) {
                    // there was an error

                    Toast.makeText(LoginPage.this,"Error in 
 logging!!",Toast.LENGTH_LONG).show();
                } else 

{ if(FirebaseAuth.getInstance().getCurrentUser().getEmail().equals(v.admin)) startActivity(new Intent(LoginPage.this,AdminUser.class)); else { String u_id = auth.getInstance().getCurrentUser().getUid();

                       mdatabase = FirebaseDatabase.getInstance().getReference().child("Users").child(u_id).child("department");
                        ValueEventListener eventListener = new ValueEventListener() {
                            @Override
                            public void onDataChange(DataSnapshot dataSnapshot) {
                                String  department = (String) dataSnapshot.getValue();

                            }

                            @Override
                            public void onCancelled(DatabaseError databaseError) {}
                        };
                        mdatabase.addListenerForSingleValueEvent(eventListener);
                        Toast.makeText(LoginPage.this,u_id,Toast.LENGTH_LONG).show();
                        Toast.makeText(LoginPage.this,departmental,Toast.LENGTH_LONG).show();
                        /*i = new Intent(LoginPage.this, LoggedIn.class);
                        i.putExtra("hello_user",department);
                        startActivity(i);*/
                    }

                    Toast.makeText(LoginPage.this, "Logged In", Toast.LENGTH_LONG).show();
                   }
            }
        });

}

}
@Override
public void onBackPressed() {
    super.onBackPressed();
}

}

1 Answers1

1

Please use this code:

String u_id = auth.getCurrentUser().getUid();
mdatabase = FirebaseDatabase.getInstance().getReference().child("Users").child(u_id).child("department");
ValueEventListener eventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        String department = (String) dataSnapshot.getValue();
        Log.d("TAG", department);
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {}
};
mdatabase.addListenerForSingleValueEvent(eventListener);

Hope it helps.

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
  • Gives error:-Can't pass null for argument 'pathString' in child() –  Jun 09 '17 at 14:49
  • This means that in your `mdatabase`, one of the arguments of `child()` methods is null. Have you checked the `u_id`? Is it `null`? This the only one which can be `null`. – Alex Mamo Jun 09 '17 at 14:53
  • its not null.I've checked it.Actually I have to pass this department string in another activity there it shows null –  Jun 09 '17 at 15:04
  • Now i CHecked the string department is null.It does not fetch the value of that particular user –  Jun 09 '17 at 15:07
  • If the `u_id` in `not null` and as you say `department` is null, check the spelling in both places, your database and your code. The code must work for sure. – Alex Mamo Jun 09 '17 at 15:09
  • And check also is that the `u_id` is correct for the coresponding user with which you are testing. – Alex Mamo Jun 09 '17 at 15:10
  • mdatabase = FirebaseDatabase.getInstance().getReference().child("Users").child(u_id).child("department"); –  Jun 09 '17 at 15:13
  • This code is correct. Can you Log the `u_id` to asure that is not null? – Alex Mamo Jun 09 '17 at 15:15
  • Ya i toasted the U_id.ITS not null –  Jun 09 '17 at 15:22
  • Now are you logging the `department` names in the logcat? – Alex Mamo Jun 09 '17 at 15:24
  • Sir 1st time it is taking null then when i used it again it gives me the department of previously loggedin user –  Jun 09 '17 at 15:27
  • I declared the string department globally because i have to pass this as parameter. –  Jun 09 '17 at 15:30
  • It is wrong to declare it globally because `onDataChange()` is called asynchronously. So you need to use this string only in that method. – Alex Mamo Jun 09 '17 at 15:32
  • If i have to use that particular string in other method then what can i do? –  Jun 09 '17 at 15:33
  • Please check my answer from this [post](https://stackoverflow.com/questions/43612171/arraylist-gets-empty-after-first-snapshot). – Alex Mamo Jun 09 '17 at 15:34
  • Don't get the point.I am adding my whole code of that class Please check –  Jun 09 '17 at 15:42
  • You cannot simply call that particular string in another method.You are using `Toast` outside that method. Try to use this code: `Toast.makeText(LoginPage.this,departmental,Toast.LENGTH_LONG).show();` inside the `onDataChange()`. – Alex Mamo Jun 09 '17 at 15:51
  • You didn't get my point.See i have to pass this Department String to another activity.So please tell what i have to do? –  Jun 09 '17 at 15:55
  • You need to move this lines: `i = new Intent(LoginPage.this, LoggedIn.class); i.putExtra("hello_user",department); startActivity(i);` inside `onDataChange()` method – Alex Mamo Jun 09 '17 at 16:00