简体   繁体   中英

UID for same user is different in Firebase database and authentication

I need to retrieve the data that i have stored in the Firebase database. But it shows that the UIDs are different in authentication part and database part.

UPDATE : Now i am facing problems while trying to fetch data from the firebase. I want to display it in a ListView. When i go from the Login Activity(after successful login) to the General Activity (where i put the ListView), it does not show up and the Activity switches from General to the Login one. I am attaching the code segments at the bottom under "UPDATE CODE" . Help would be highly appreciated. Thanks!

UIDS

Here is the code for registration

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_registration);
    setUpUIviews();

    firebaseAuth = FirebaseAuth.getInstance();

    db = FirebaseDatabase.getInstance().getReference().child("users");

    Register.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (validate()){
                String user_email = REmail.getText().toString().trim();
                String user_password = RPass.getText().toString().trim();

                firebaseAuth.createUserWithEmailAndPassword(user_email,user_password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {

                        if(task.isSuccessful()){
                            updateData();
                            Toast.makeText(Registration.this,"Registration Successful! ",Toast.LENGTH_SHORT).show();
                            startActivity(new Intent(Registration.this,MainActivity.class));
                        }else {
                            Toast.makeText(Registration.this,"Registration Unsuccessful ",Toast.LENGTH_SHORT).show();
                        }

                    }
                });
            }
        }
    });

And this is the update data part:

private void updateData(){

    String uName = RName.getText().toString().trim();
    String uEmail = REmail.getText().toString().trim();

   String id = db.push().getKey();

   ProfileUpdate profileUpdate = new ProfileUpdate(uName,uEmail);

   db.child(id).setValue(profileUpdate);

   Toast.makeText(this,"Added info",Toast.LENGTH_SHORT).show();

}

UPDATE CODE

Login Activity

    public class LoginPage extends AppCompatActivity {

    private TextView userRegistration;
    private TextView Info;
    private EditText LName;
    private EditText LPass;
    private Button LSignIn;
    private int counter = 3;
    private FirebaseAuth firebaseAuth;
    private ProgressDialog progressDialog;

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

        userRegistration = (TextView)findViewById(R.id.tvRegister);
        LName = (EditText)findViewById(R.id.btnName);
        LPass = (EditText)findViewById(R.id.btnPass);
        LSignIn = (Button) findViewById(R.id.btnSignIn);
        Info = (TextView) findViewById(R.id.tvInfo);

         Info.setText( " No of attempts remaining: 3 " );

        firebaseAuth = FirebaseAuth.getInstance();
        progressDialog = new ProgressDialog(this);

        FirebaseUser user= null;

        if(user!=null){
           finish();
            startActivity(new Intent(LoginPage.this,General.class));
        }

         user = firebaseAuth.getCurrentUser();

        LSignIn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                validate(LName.getText().toString(),LPass.getText().toString());
            }
        });

        userRegistration.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(LoginPage.this,Registration.class));
            }
        });


    }

    private void validate(String username, String password){

        progressDialog.setMessage("Processing your request.... ");
        progressDialog.show();

        firebaseAuth.signInWithEmailAndPassword(username,password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
            @Override
            public void onComplete(@NonNull Task<AuthResult> task) {
                if(task.isSuccessful()){
                    progressDialog.dismiss();
                    Toast.makeText(LoginPage.this,"Login successful!",Toast.LENGTH_SHORT).show();
                    startActivity(new Intent(LoginPage.this,General.class));
                }else {
                    Info.setText("No of attempts remaining: " + String.valueOf(counter-1));
                    Toast.makeText(LoginPage.this,"Please enter corrent credentials",Toast.LENGTH_SHORT).show();
                    counter --;
                    progressDialog.dismiss();
                    if(counter<=0){
                        LSignIn.setEnabled(false);
                    }
                }
            }
        });


    }


}


General Activity

    public class General extends AppCompatActivity {

    private FirebaseAuth firebaseAuth;
    private Button Logout;

    ListView l1;
    ArrayAdapter<String> adapter;
    DatabaseReference databaseReference;
    FirebaseUser user;
    List<String> itemlist;
    String uid;




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


        firebaseAuth = FirebaseAuth.getInstance();
        Logout = (Button) findViewById(R.id.btnLogout);

        l1 = (ListView)findViewById(R.id.listView);
        user = FirebaseAuth.getInstance().getCurrentUser();
        uid = user.getUid();
        itemlist = new ArrayList<>();

        databaseReference = FirebaseDatabase.getInstance().getReference();

        databaseReference.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                itemlist.clear();;
                String user_name = dataSnapshot.child(uid).child("usrName").getValue(String.class);
                String user_email = dataSnapshot.child(uid).child("ursEmail").getValue(String.class);

                itemlist.add(user_name);
                itemlist.add(user_email);

                adapter = new ArrayAdapter<>(General.this,android.R.layout.simple_list_item_1,itemlist);
                l1.setAdapter(adapter);
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }
        });


        Logout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                firebaseAuth.signOut();
                finish();
                startActivity(new Intent(General.this, MainActivity.class));
            }
        });


    }


}


activity_general.xml file

    <?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/myApp"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".General">

    <Button
        android:id="@+id/btnLogout"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginBottom="8dp"
        android:text="LOGOUT"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.467"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/listView" />

    <ListView
        android:id="@+id/listView"
        android:layout_width="368dp"
        android:layout_height="270dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="8dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>

The Design

enter image description here

This is the code of how you store the user data into the datbase:

String id = db.push().getKey();

ProfileUpdate profileUpdate = new ProfileUpdate(uName,uEmail);

db.child(id).setValue(profileUpdate);

In the first line you call push().getKey() to get a new unique ID from the database SDK. This ID is not related to the user profile.

If you want to store the users in the database under their UID, you will need to get the UID from the AuthResult just after you created the user. Something like:

String uid = task.getResult().getUser().getUid();

When you pass this uid to your updateData method, you then create the child node the database with:

db.child(uid).setValue(profileUpdate);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM