当前位置: 首页 > 面试题库 >

正确的代码位置以检查Firebase是否已创建用户?

佴涵蓄
2023-03-14
问题内容

我创建了一种方法,可以在用户登录后获取用户的Facebook数据,并在我的Firebase数据库上为他们创建一个“用户”。此方法addUser()也为该用户创建并设置变量。但是我必须保留该方法登录,以便它创建我的变量,然后注释掉该方法以进行将来的测试,否则它将重置所有值。因此,我可以在哪里添加“
addUser()”来首次创建该用户,并确保只要该用户已经存在,就永远不要再次调用它?

MainActivity(启动和登录)

public class MainActivity extends AppCompatActivity {
    CallbackManager callbackManager;
    ShareDialog shareDialog;
    LoginButton login;
    ProfilePictureView profile;
    Dialog details_dialog;
    TextView details_txt;
    JSONObject response;

    /* Used to track user logging in/out off Facebook */
    private AccessTokenTracker mFacebookAccessTokenTracker;

    /* A reference to the Firebase */
    private Firebase mFirebaseRef;

    /* A reference to the Firebase */
    private Firebase userRef;

    /* Data from the authenticated user */
    public static AuthData mAuthData;

    /* Listener for Firebase session changes */
    private Firebase.AuthStateListener mAuthStateListener;

    public static String uName = null;

    public static String uEmail = null;

    public static String uUrl = null;

    public static int mTokens = 50;

    public static String uID = null;

    public static int getLiveTokens() {
        return liveTokens;
    }

    public static void setLiveTokens(int liveTokens) {
        MainActivity.liveTokens = liveTokens;
    }

    public static int liveTokens = 0;

    public static int getLiveSpins() {
        return liveSpins;
    }

    public static void setLiveSpins(int liveSpins) {
        MainActivity.liveSpins = liveSpins;
    }

    public static int liveSpins = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        mFirebaseRef = new Firebase("https://<url>.firebaseio.com/");

        callbackManager = CallbackManager.Factory.create();
        login = (LoginButton) findViewById(R.id.login_button);

        profile = (ProfilePictureView) findViewById(R.id.picture);
        shareDialog = new ShareDialog(this);
        login.setReadPermissions("public_profile email");

        details_dialog = new Dialog(this);
        details_dialog.setContentView(R.layout.dialog_details);
        details_dialog.setTitle("Details");
        details_txt = (TextView) details_dialog.findViewById(R.id.details);

        getLoginDetails(login);

        mFacebookAccessTokenTracker = new AccessTokenTracker() {
            @Override
            protected void onCurrentAccessTokenChanged(AccessToken oldAccessToken, AccessToken currentAccessToken) {
                //Log.i(Tag, "Facebook.AccessTokenTracker.OnCurrentAccessTokenChanged");
              //  Toast.makeText(getApplicationContext(), "FBAccessTokenChange", Toast.LENGTH_LONG).show();

                MainActivity.this.onFacebookAccessTokenChange(currentAccessToken);
            }
        };

        if (AccessToken.getCurrentAccessToken() != null) {
            RequestData();
            getLoginDetails(login);
            getUserInfo();

            Toast.makeText(getApplicationContext(), "Already Logged In", Toast.LENGTH_LONG).show();
        }

        login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (AccessToken.getCurrentAccessToken() != null) {
                    profile.setProfileId(null);
                }
            }
        });

        mAuthStateListener = new Firebase.AuthStateListener() {
            @Override
            public void onAuthStateChanged(AuthData authData) {
               // mAuthProgressDialog.hide();
                setAuthenticatedUser(authData);
            }
        };
        /* Check if the user is authenticated with Firebase already. If this is the case we can set the authenticated
         * user and hide hide any login buttons */
        mFirebaseRef.addAuthStateListener(mAuthStateListener);
    }

    public void addUser() {

        this.uID = mAuthData.getUid();

        Toast.makeText(getApplicationContext(), "Setting Up User Account", Toast.LENGTH_LONG).show();

        Firebase rootRef = new Firebase("https://<url>.firebaseio.com/users/");
        Firebase userRef = rootRef.child(mAuthData.getUid() + "/");
        userRef.child("name").setValue(mAuthData.getProviderData().get("displayName"));
        userRef.child("provider").setValue(mAuthData.getProvider());
        userRef.child("email").setValue(mAuthData.getProviderData().get("email"));
        userRef.child("tokens").setValue("100");
        userRef.child("spins").setValue("100");
        userRef.child("totalspins").setValue("0");
        userRef.child("topwin").setValue("0");
    }

    protected void getLoginDetails(LoginButton login){

        login.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {

            @Override
            public void onSuccess(LoginResult login_Result) {
                getUserInfo();
            }

            @Override
            public void onCancel() {
            }

            @Override
            public void onError(FacebookException exception) {
            }
        });
    }

    // LoginResult login_result
    protected void getUserInfo() {

        // LoginResult login_result.getAccessToken()

        GraphRequest data_request = GraphRequest.newMeRequest(AccessToken.getCurrentAccessToken(), new GraphRequest.GraphJSONObjectCallback() {

            @Override
            public void onCompleted(JSONObject json_object, GraphResponse response) {

                Intent intent = new Intent(MainActivity.this, HomeActivity.class);
                intent.putExtra("jsondata", json_object.toString());
                intent.putExtra("Uid", uID);
                startActivity(intent);
            }
        });

        Bundle permission_param = new Bundle();
        permission_param.putString("fields", "id,name,email,picture.width(120).height(120)");
        data_request.setParameters(permission_param);
        data_request.executeAsync();
    }

    public void RequestData() {
        GraphRequest request = GraphRequest.newMeRequest(AccessToken.getCurrentAccessToken(), new GraphRequest.GraphJSONObjectCallback() {
            @Override
            public void onCompleted(JSONObject object, GraphResponse response) {

                JSONObject json = response.getJSONObject();
                try {
                    if (json != null) {
                        String text = "<b>Name :</b> " + json.getString("name") + "<br><br><b>Email :</b> " + json.getString("email") + "<br><br><b>Profile link :</b> " + json.getString("link");
                        details_txt.setText(Html.fromHtml(text));
                        profile.setProfileId(json.getString("id"));
                        uName = json.getString("name");
                        uEmail = json.getString("email");

                        uUrl = json.getString("id");
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });

        Bundle parameters = new Bundle();
        parameters.putString("fields", "id,name,link,email,picture");
        request.setParameters(parameters);
        request.executeAsync();
    }

    /**
     * This method will attempt to authenticate a user to firebase given an oauth_token (and other
     * necessary parameters depending on the provider)
     */
    private void authWithFirebase(final String provider, Map<String, String> options) {
        if (options.containsKey("error")) {
           showErrorDialog(options.get("error"));
        } else {
            //mAuthProgressDialog.show();

                // if the provider is not twitter, we just need to pass in the oauth_token
                mFirebaseRef.authWithOAuthToken(provider, options.get("oauth_token"), new AuthResultHandler(provider));
            }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        callbackManager.onActivityResult(requestCode, resultCode, data);
    }

    private void setAuthenticatedUser(AuthData authData) {
        if (authData != null) {

            /* show a provider specific status text */
            String name = null;
            if (authData.getProvider().equals("facebook")) {
                name = (String) authData.getProviderData().get("displayName");
            } else if (authData.getProvider().equals("anonymous")
                    || authData.getProvider().equals("password")) {
                name = authData.getUid();
            } else {
                Toast.makeText(getApplicationContext(), "invalid provider", Toast.LENGTH_LONG).show();
            }
            if (name != null) {

                //success
              //  Toast.makeText(getApplicationContext(), "Log " + name + " (" + authData.getProvider() + ")", Toast.LENGTH_LONG).show();

            }

        } else {

        }

        // Firebase Authenticated

        this.mAuthData = authData;

        MainActivity.uID = mAuthData.getUid();

       //addUser();
        /* invalidate options menu to hide/show the logout button */
        supportInvalidateOptionsMenu();
    }


    /**
     * Show errors to users
     */
    private void showErrorDialog(String message) {
        new AlertDialog.Builder(this)
                .setTitle("Error")
                .setMessage(message)
                .setPositiveButton(android.R.string.ok, null)
                .setIcon(android.R.drawable.ic_dialog_alert)
                .show();
    }

    private class AuthResultHandler implements Firebase.AuthResultHandler {

        private final String provider;

        public AuthResultHandler(String provider) {
            this.provider = provider;
        }

        @Override
        public void onAuthenticated(AuthData authData) {
          //  mAuthProgressDialog.hide();
         //   Toast.makeText(getApplicationContext(), "Auth Success", Toast.LENGTH_LONG).show();
           // Toast.makeText(getApplicationContext(), authData.getUid(), Toast.LENGTH_LONG).show();

           // createUser();

            setAuthenticatedUser(authData);

           String mEmail = authData.getUid();

           // uID = authData.getUid();

            String mProvide = mAuthData.getProvider();

        }

        @Override
        public void onAuthenticationError(FirebaseError firebaseError) {
            //mAuthProgressDialog.hide();
            showErrorDialog(firebaseError.toString());
        }
    }

    public void createUser(){

        Firebase rootRef = new Firebase("https://<url>.firebaseio.com/");
       Firebase userRef = rootRef.child("users").child(mAuthData.getUid());

        userRef.child("provider").setValue(mAuthData.getProvider());
        userRef.child("provider").setValue(mAuthData.getProviderData().get("displayName)"));


        rootRef.createUser(mAuthData.getProviderData().get("email").toString(), mAuthData.getProviderData().get("id").toString(), new Firebase.ValueResultHandler<Map<String, Object>>() {

            @Override
            public void onSuccess(Map<String, Object> result){
                Toast.makeText(getApplicationContext(), "Yes-UID=" + result.get("Uid") , Toast.LENGTH_LONG).show();

            }

            @Override
            public void onError(FirebaseError firebaseError){
                Toast.makeText(getApplicationContext(), "Not Created", Toast.LENGTH_LONG).show();


            }


        });

    }


    private void logout() {
        if (this.mAuthData != null) {
            /* logout of Firebase */
            mFirebaseRef.unauth();
            /* Logout of any of the Frameworks. This step is optional, but ensures the user is not logged into
             * Facebook/Google+ after logging out of Firebase. */
            if (this.mAuthData.getProvider().equals("facebook")) {
                /* Logout from Facebook */
                LoginManager.getInstance().logOut();
            }
            /* Update authenticated user and show login buttons */
            setAuthenticatedUser(null);
        }
    }


    @Override
    protected void onResume() {

        super.onResume();
        AppEventsLogger.activateApp(this);

    }

    @Override
    protected void onPause() {

        super.onPause();
        AppEventsLogger.deactivateApp(this);

    }


    /* ************************************
     *             FACEBOOK               *
     **************************************
     */
    private void onFacebookAccessTokenChange(AccessToken token) {
        if (token != null) {
            //mAuthProgressDialog.show();
            mFirebaseRef.authWithOAuthToken("facebook", token.getToken(), new AuthResultHandler("facebook"));
        } else {
            // Logged out of Facebook and currently authenticated with Firebase using Facebook, so do a logout
            if (this.mAuthData != null && this.mAuthData.getProvider().equals("facebook")) {
                mFirebaseRef.unauth();
                setAuthenticatedUser(null);
            }
        }
    }


    public static int getmTokens() {

       return getLiveTokens();

    }

    public static void setmTokens(int mTokens) {
        MainActivity.mTokens = mTokens;
    }

    public static void takemTokens(int mTokens) {
        MainActivity.mTokens -= mTokens;
    }

    public static void givemTokens(final int ttokens) {
        //MainActivity.mTokens += tokens;

        // TODO
       // if (ttokens > MainActivity.getmTopWin()){
        //    MainActivity.setmTopWin(ttokens);
        //}

        Firebase ref = new Firebase("https://<url>.firebaseio.com/users/" +  MainActivity.uID + "/");
        final Firebase tokensRef = ref.child("tokens");
        tokensRef.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                int iii = new Integer(dataSnapshot.getValue().toString());

                iii += ttokens;

                tokensRef.setValue(iii);

                setLiveTokens(iii);

                checkmTopWin(ttokens);

            }

            @Override
            public void onCancelled(FirebaseError firebaseError) {
            }

        });
        //tokensRef.removeEventListener(MainActivity);

    }


    public static int mSpins = 30;

    public static int getmSpins() {
        return getLiveSpins();
    }

    public static void setmSpins(int mspins) {
        MainActivity.mSpins = mspins;
    }

    public static void takemSpins(final int mspins) {

        Firebase ref = new Firebase("https://<url>.firebaseio.com/users/" +  MainActivity.uID + "/");
        final Firebase tokensRef = ref.child("spins");
        tokensRef.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                int i = Integer.valueOf(dataSnapshot.getValue().toString());

                i -= mspins;

                tokensRef.setValue(i);
                setLiveSpins(i);

            }
            @Override
            public void onCancelled(FirebaseError firebaseError) {}
        });

    }

    public static void givemSpins(final int mspins){

        Firebase ref = new Firebase("https://<url>.firebaseio.com/users/" +  MainActivity.uID + "/");
        final Firebase tokensRef = ref.child("spins");
        tokensRef.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                int i = Integer.valueOf(dataSnapshot.getValue().toString());

                i += mspins;

                tokensRef.setValue(i);
            }
            @Override
            public void onCancelled(FirebaseError firebaseError) {}
        });


    }

    public static int slotVari = 0;

    public static int getSlotVari() {
        return slotVari;
    }

    public static void setSlotVari(int slotVari) {
        MainActivity.slotVari = slotVari;
    }


    public static int mTotalSpins;

    public static int getmTotalSpins() {
        return mTotalSpins;
    }

    public static void setmTotalSpins(int mTotalSpins) {
        MainActivity.mTotalSpins = mTotalSpins;
    }

    public static void incmTotalSpins(){

        Firebase ref = new Firebase("https://<url>.firebaseio.com/users/" +  MainActivity.uID + "/");
        final Firebase tokensRef = ref.child("totalspins");
        tokensRef.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                int i = Integer.valueOf(dataSnapshot.getValue().toString());

                i++;

                tokensRef.setValue(i);
            }
            @Override
            public void onCancelled(FirebaseError firebaseError) {}
        });

        MainActivity.mTotalSpins++;
    }


    public static int mTopWin;

    public static int getmTopWin() {
        return mTopWin;
    }

    public static void setmTopWin(int mTopWin) {

        Firebase ref = new Firebase("https://<url>.firebaseio.com/users/" +  MainActivity.uID + "/");
        Firebase tokensRef = ref.child("topwin");

        tokensRef.setValue(mTopWin);

        MainActivity.mTopWin = mTopWin;
    }

    public static void checkmTopWin(final int mTokensWon) {

        Firebase ref = new Firebase("https://<url>.firebaseio.com/users/" +  MainActivity.uID + "/");
        final Firebase tokensRef = ref.child("topwin");
        tokensRef.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                int i = Integer.valueOf(dataSnapshot.getValue().toString());

                if (i < mTokensWon){

                    tokensRef.setValue(mTokensWon);

                }

            }
            @Override
            public void onCancelled(FirebaseError firebaseError) {}
        });
    }
}

问题答案:

您需要将首选项设置为,FIRST_LAUNCH并在每次用户登录时检查其是否正确。第一次启动应用程序时,FIRST_LAUNCH找不到首选项。因此,调用您的addUser()函数在FireBase数据库中创建一个新条目。

SharedPreferences pref = getSharedPreferences(Constants.ApplicationTag, Activity.MODE_PRIVATE);

if (!pref.contains(Constants.FIRST_LAUNCH)) {
    addUser();
    pref.edit().putBoolean(Constants.FIRST_LAUNCH, true).commit();
}

因此,您可能会想,如果用户先卸载应用程序然后重新安装,首选项将消失,addUser()功能将被再次调用。没问题,只要child属性的路径相同,就不会获得新的Firebase条目。这些值将被用户当前信息替换为特定路径(如果确实存在)。

现在,如果要检查您的用户在Firebase数据库中是否已经存在,则需要添加这样的侦听器。我附上一个代码示例,以更好地理解。

Firebase rootRef = new Firebase("https://<url>.firebaseio.com/users/");
Firebase userRef = rootRef.child(mAuthData.getUid() + "/");

userRef.addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        if (dataSnapshot.exists()) {

            // User exists. Do nothing

        } else addUser();

    }

    @Override
    public void onCancelled(FirebaseError firebaseError) {}
});


 类似资料:
  • 如何检查字节中的某个位是否被设置?

  • 这是我遇到的一个普遍问题。我想知道是否有人知道任何合适的设计模式或技术。 上面的类从队列中获取外部对象并构造MyBuilderClass对象。 如果所有字段都设置为非null非空值,则成功构建MyBuilderClass对象。 将有许多MyBuilderClass对象无法构建,因为ExternalObject中缺少数据。 我的问题是,检测对象是否已正确构建的最佳方法是什么? 我可以检查set方法中

  • 这是我明天为期中考试做的一些练习。我似乎找不到我的代码的问题,这就是问题所在: 当我们的许多信息存储在网上时,拥有一个安全的密码是非常重要的。按照以下规则编写一个验证新密码的程序: •密码长度必须至少为8个字符。 密码必须至少有一个大写字母和一个小写字母 • 密码必须至少有一位数字。 编写一个要求输入密码的程序,然后再次要求确认密码。如果密码不匹配或未满足规则,请再次提示。您的程序应包含一种检查密

  • 问题内容: 将Apache Derby与Java结合使用(J2ME,但我认为这没有什么不同),是否有任何方法可以检查数据库是否已经存在并包含表? 问题答案: 除了MySQL之外,我什么都不知道,只有很少的解决方法,这与MySQL具有IF EXIST的功能不同。 您要做的是,尝试连接数据库,如果不可能的话。在成功建立连接之后,您可以执行简单的选择,例如SELECT count(*)FROM TABL

  • 问题内容: 我正在尝试检查用户名是否存在。当我打电话时,快照值始终可用,但是它将打印我的整个数据库,而不仅仅是我请求的数据。当我打电话时,它总是返回null。我尝试了很多方法来解决。 这是我的代码: 这是我的json树: 这是安全规则: 问题答案: 修改 JSON 树以包含一个单独的节点,即在您创建新用户时添加每个用户的用户名,在用户修改其用户名时进行修改… 要检查您的用户名是否已经存在: 通过操

  • 问题内容: 我正在看这个网站,但似乎无法弄清楚该怎么做,因为它不起作用。我需要检查当前站点用户是否已登录(已验证),并且正在尝试: 尽管确定用户已登录,但它仅返回: 我可以执行其他请求(来自上面url的第一部分),例如: 这将返回成功的响应。 问题答案: Django 1.10+更新:现在是Django 1.10中的属性。为了向后兼容,该方法仍然存在,但在Django 2.0中将被删除。 对于Dj