我创建了一种方法,在用户登录后获取用户的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 one rror(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 one rror(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) {}});
总结 以上是内存溢出为你收集整理的java – 如果已经创建了用户,请更正Firebase的代码位置?全部内容,希望文章能够帮你解决java – 如果已经创建了用户,请更正Firebase的代码位置?所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)