简体   繁体   English

如何从android上的firebase获取用户uid?

[英]How to get user uid from firebase on android?

I want to save data to firebase.我想将数据保存到 firebase。 This is my Activity Code :这是我的活动代码:

private Firebase firebaseRef;
Firebase.setAndroidContext(this);

try {
    mUserId = firebaseRef.getAuth().getUid();
} catch (Exception e) {
    //  loginWithMailView();
}
itemsUrl = Constants.FIREBASE_URL + "/Person/" + mUserId +"/Information/";

//Person + null (?) + the other information

and this is for my button code :这是我的按钮代码:

buttonSave = (Button) findViewById(R.id.btnKaydolKayit);
buttonSave.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View v) {
        firebaseRef = new Firebase(Constants.FIREBASE_URL);
        String name = editTextName.getText().toString().trim();
        String surname = editTextSurname.getText().toString().trim();
        String gender = final_result.getText().toString();
        String mail = editTextMail.getText().toString();
        String pass = editTextPass.getText().toString().trim();
        String phone = editTextPhone.getText().toString().trim();
        String trom = final_resultT.getText().toString();
        String bloodGroup = spinnerBlood.getSelectedItem().toString();
        String dateBlood = dateTextViewBlood.getText().toString();
        String dateTrombo = dateTextViewTrom.getText().toString();

        if (pass.isEmpty() || mail.isEmpty()) {
            AlertDialog.Builder builder = new AlertDialog.Builder(KaydolActivity.this);
            builder.setMessage(R.string.signup_error_message)
                    .setTitle(R.string.signup_error_title)
                    .setPositiveButton(android.R.string.ok, null);
            AlertDialog dialog = builder.create();
            dialog.show();
        } else {
            firebaseRef.createUser(mail, pass, new Firebase.ResultHandler(){

                @Override
                public void onSuccess() {
                    firebaseRef = new Firebase(Constants.FIREBASE_URL);
                    //  firebaseRef.setValue();
                    AlertDialog.Builder builder = new AlertDialog.Builder(KaydolActivity.this);
                    builder.setMessage("Hesap başarılı bir şekilde oluşturuldu!").setPositiveButton(R.string.login_button_label, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            Intent intent = new Intent(KaydolActivity.this, loginWithMail.class);
                            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
                            startActivity(intent);
                        }
                    });
                    AlertDialog dialog = builder.create();
                    dialog.show();
                }

                @Override
                public void onError(FirebaseError firebaseError) {
                    AlertDialog.Builder builder = new AlertDialog.Builder(KaydolActivity.this);
                    builder.setMessage(firebaseError.getMessage())
                            .setTitle(R.string.signup_error_title)
                            .setPositiveButton(android.R.string.ok, null);
                    AlertDialog dialog = builder.create();
                    dialog.show();
                }
            });
        }

        new Firebase(itemsUrl).push().child("name").setValue(name);
        new Firebase(itemsUrl).push().child("surname").setValue(surname);
        new Firebase(itemsUrl).push().child("gender").setValue(gender);
        new Firebase(itemsUrl).push().child("mail").setValue(mail);
        new Firebase(itemsUrl).push().child("pass").setValue(pass);
        new Firebase(itemsUrl).push().child("phone").setValue(phone);
        new Firebase(itemsUrl).push().child("trom").setValue(trom);
        new Firebase(itemsUrl).push().child("bloodGroup").setValue(bloodGroup);
        new Firebase(itemsUrl).push().child("trom").setValue(trom);
        new Firebase(itemsUrl).push().child("dateBlood").setValue(dateBlood);
        new Firebase(itemsUrl).push().child("dateTrombo").setValue(dateTrombo);
    }
});

my source code (for help / for example ) : https://www.sitepoint.com/creating-a-cloud-backend-for-your-android-app-using-firebase/我的源代码(寻求帮助/例如): https : //www.sitepoint.com/creating-a-cloud-backend-for-your-android-app-using-firebase/

When I save a data to firebase as the following photo ( Login&Auth )当我将数据作为以下照片保存到 firebase 时(登录和身份验证) 在此处输入图片说明

but mUserId is null.但 mUserId 为空。 so when I look database mUserid is null ( like a photo )所以当我看数据库 mUserid 是空的(就像一张照片) 在此处输入图片说明

You can use these lines of code to get Current User Uid with Android Firebase Framework您可以使用这些代码行通过 Android Firebase 框架获取当前用户 Uid

FirebaseUser currentFirebaseUser = FirebaseAuth.getInstance().getCurrentUser() ;
Toast.makeText(this, "" + currentFirebaseUser.getUid(), Toast.LENGTH_SHORT).show();

要获取当前用户 UID,您只需要这行代码:

String currentuser = FirebaseAuth.getInstance().getCurrentUser().getUid();

the problem is that in firebase when you create a user it doesn't sign in the user.问题是在 firebase 中,当您创建用户时,它不会登录用户。 Here is from the docs:这是来自文档:

Creates a new email / password user with the provided credentials.使用提供的凭据创建新的电子邮件/密码用户。 This method does not authenticate the user.此方法不会对用户进行身份验证。 After the account is created, the user may be authenticated with authWithPassword().创建帐户后,可以使用 authWithPassword() 对用户进行身份验证。 https://www.firebase.com/docs/web/api/firebase/createuser.html https://www.firebase.com/docs/web/api/firebase/createuser.html

Firebase ref = new Firebase("https://<YOUR-FIREBASE-APP>.firebaseio.com");
    ref.authWithPassword(mail, pass, new Firebase.AuthResultHandler() {
        @Override
        public void onAuthenticated(AuthData authData) {
            System.out.println("User ID: " + authData.getUid() + ", Provider: " + authData.getProvider());
        }
        @Override
        public void onAuthenticationError(FirebaseError firebaseError) {
            // there was an error
        }
    });

So once your user is created call the authWithPassword function.因此,一旦您的用户被创建,请调用 authWithPassword 函数。 Hope it helps!希望有帮助!

在您的代码中,您的 firebaseRef 似乎为 null,因此导致 null uid ,从 Firebase 获取用户 ID 的推荐方法是在用户登录后在您的应用程序中的任何位置执行以下操作

String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();

in REACT NATIVE it's just like this.在 REACT NATIVE 中就是这样。

  import firebase as 'firebase';

    HandleGetUserId=()=>{
    let userId = firebase.auth().currentUser.uid;
    return userId;
    }

just call the function HandleGetUserId to get the id like this只需调用函数 HandleGetUserId 即可获取这样的 id

this.HandleGetUserId();

I was also having the same problem with getting the uid.我在获取 uid 时也遇到了同样的问题。 When i had it printed on the log (Log.i), i could see the uid, however when trying to use it as one of the fields in one of my objects being created, the field does not get created.当我将它打印在日志 (Log.i) 上时,我可以看到 uid,但是当尝试将它用作正在创建的对象之一中的字段之一时,该字段没有被创建。

I was doing thing : String currentUId = FirebaseAuth.getInstance().getCurrentUser().getUid();我正在做的事情: String currentUId = FirebaseAuth.getInstance().getCurrentUser().getUid();

This didn't work well for me.这对我来说效果不佳。

SOLUTION I FOUND OUT - (worked for me - try it out)我发现的解决方案 - (对我有用 - 试试看)

Use : FirebaseUser currentU = FirebaseAuth.getInstance().getCurrentUser();使用: FirebaseUser currentU = FirebaseAuth.getInstance().getCurrentUser(); String uId = currentU.getUid(); String uId = currentU.getUid();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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