正确的代码位置检查Firebase是否已创建用户? [英] Correct code location to check Firebase if a user has been created already?

查看:140
本文介绍了正确的代码位置检查Firebase是否已创建用户?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个方法,在用户登录后获取用户的Facebook数据,并在我的firebase数据库上为他们创建一个用户。这个方法addUser()也为所述用户创建和设置变量。但是我不得不离开这个方法,登录,所以它创建了我的变量,然后将这个方法注释掉以备将来测试,否则它会重置所有的值。
那么我可以在哪里添加addUser()来第一次创建这个用户,并且确保它再也不会再调用它,只要用户已经存在了?

MainActivity(开始和登录)
$ b

  import android.app.AlertDialog; 
导入android.app.Dialog;
导入android.content.Intent;
导入android.support.v7.app.AppCompatActivity;
导入android.os.Bundle;
导入android.text.Html;
导入android.view.View;
导入android.widget.TextView;
导入android.widget.Toast;

import com.facebook.AccessToken;
import com.facebook.AccessTokenTracker;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.GraphRequest;
import com.facebook.GraphResponse;
import com.facebook.appevents.AppEventsLogger;
导入com.facebook.login.LoginManager;
导入com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;
import com.facebook.login.widget.ProfilePictureView;
import com.facebook.share.widget.ShareDialog;
import com.firebase.client.AuthData;
import com.firebase.client.DataSnapshot;
import com.firebase.client.Firebase;
import com.firebase.client.FirebaseError;
import com.firebase.client.ValueEventListener;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Map;


公共类MainActivity扩展AppCompatActivity {
CallbackManager callbackManager;
ShareDialog shareDialog;
LoginButton登录;
ProfilePictureView个人资料;
Dialog details_dialog;
TextView details_txt;
JSONObject响应;

/ *用于追踪用户登录/离开Facebook * /
私人AccessTokenTracker mFacebookAccessTokenTracker;

/ *引用Firebase * /
私有Firebase mFirebaseRef;

/ *引用Firebase * /
私有Firebase userRef;

/ *来自认证用户的数据* /
public static AuthData mAuthData;

/ * Firebase会话更改的监听器* /
私有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 =新的Firebase(https://< url> .firebaseio.com /);

callbackManager = CallbackManager.Factory.create();
login =(LoginButton)findViewById(R.id.login_button);
$ b $ 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);
// details.setOnClickListener(new View.OnClickListener(){
// @Override
// public void onClick(View view){
// details_dialog.show() ;
//}
//});
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);
}
}; (b)b

if(AccessToken.getCurrentAccessToken()!= null){

//在这里队长\ / 1
// addUser() ;
// createUser();

RequestData();

getLoginDetails(login);

getUserInfo();

Toast.makeText(getApplicationContext(),已登录,Toast.LENGTH_LONG).show();


// share.setVisibility(View.VISIBLE);
// details.setVisibility(View.VISIBLE);

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

$ b mAuthStateListener = new Firebase.AuthStateListener(){
@Override
public void onAuthStateChanged(AuthData authData){
// mAuthProgressDialog.hide() ;
setAuthenticatedUser(authData);
}
};
/ *检查用户是否已经使用Firebase进行身份验证。如果是这种情况,我们可以设置已验证的
*用户并隐藏任何登录按钮* /
mFirebaseRef.addAuthStateListener(mAuthStateListener);



$ public void addUser(){

this.uID = mAuthData.getUid();

Toast.makeText(getApplicationContext(),设置用户帐户,Toast.LENGTH_LONG).show();

Firebase rootRef =新的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);


$ b protected void getLoginDetails(LoginButton login){

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

@Override
public void onSuccess(LoginResult login_Result){

$ b // login_result
getUserInfo();

}

@Override
public void onCancel(){


$ b @Override $ b $ public void onError(FaceException exception ){
}
});


$ b // LoginResult login_result

protected void getUserInfo(){

// LoginResult login_result.getAccessToken )

GraphRequest data_request = GraphRequest.newMeRequest(AccessToken.getCurrentAccessToken(),new GraphRequest.GraphJSONObjectCallback(){
$ b @Override $ b $ public void onCompleted(JSONObject json_object, GraphResponse响应){

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();


$ b public void RequestData(){


$ b GraphRequest请求= GraphRequest.newMeRequest(AccessToken.getCurrentAccessToken ),new GraphRequest.GraphJSONObjectCallback(){
@Override $ b $ public void onCompleted(JSONObject object,GraphResponse response){

JSONObject json = response.getJSONObject();
试试{
if(json!= null){
String text =< b>名称:< / b>+ json.getString(name)+< br> < b>电子邮件:< / b>+ json.getString(email)+< br>< br>< b>个人资料链接:< / b> .getString(link);
details_txt.setText(Html.fromHtml(text));
profile.setProfileId(json.getString(id));
uName = json。 getString(name);
uEmail = json.getString(email);

uUrl = json.getS特林( ID);



$ catch(JSONException e){
e.printStackTrace();
}
}
});
Bundle parameters = new Bundle();
parameters.putString(fields,id,name,link,email,picture);
request.setParameters(parameters);
request.executeAsync();

$ b / **
*这个方法将尝试认证一个用户给firebase给定一个oauth_token(和其他
*必要的参数取决于提供者)
* /
private void authWithFirebase(final String提供者,Map< String,String> options){
if(options.containsKey(error)){
showErrorDialog(options。得到( 错误));
} else {
//mAuthProgressDialog.show();

//如果提供者不是twitter,我们只需要传入oauth_token
mFirebaseRef.authWithOAuthToken(provider,options.get(oauth_token),new AuthResultHandler(provider)) ;


$ b $覆盖$ b $保护void onActivityResult(int requestCode,int resultCode,Intent data){
super.onActivityResult(requestCode,resultCode,数据);
callbackManager.onActivityResult(requestCode,resultCode,data);


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

/ *显示提供程序的特定状态文本* /
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(); ($!


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

}

}其他{b
$ b}

//已验证Firebase

此.mAuthData = authData;

MainActivity.uID = mAuthData.getUid();

// addUser();
/ *无效选项菜单隐藏/显示注销按钮* /
supportInvalidateOptionsMenu();


$ b / **
*向用户显示错误
* /
private void showErrorDialog(String message){
新的AlertDialog.Builder(this)
.setTitle(Error)
.setMessage(消息)
.setPositiveButton(android.R.string.ok,null)
。 setIcon(android.R.drawable.ic_dialog_alert)
.show();


private class AuthResultHandler实现了Firebase.AuthResultHandler {

private final String provider;

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

$ b @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();


$ b @Override
public void onAuthenticationError(FirebaseError firebaseError){
//mAuthProgressDialog.hide();
showErrorDialog(firebaseError.toString()); 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)));

$ b 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();


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


}


});



$ b private void logout(){
if(this.mAuthData!= null){
/ * Firebase的注销* /
mFirebaseRef.unauth();
/ *注销任何框架。此步骤是可选的,但确保用户在注销Firebase后未登录到
* Facebook / Google +。 * /
if(this.mAuthData.getProvider()。equals(facebook)){
/ *从Facebook注销* /
LoginManager.getInstance()。logOut
}
/ *更新认证用户并显示登录按钮* /
setAuthenticatedUser(null);



$ b @Override
protected void onResume(){

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


$ b @Override
protected void onPause(){

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

}


/ * *************************** *********
* FACEBOOK *
****************************** ********
* /
private voidFacebookAccessTokenChange(AccessToken token){
if(token!= null){
//mAuthProgressDialog.show();
mFirebaseRef.authWithOAuthToken(facebook,token.getToken(),new AuthResultHandler(facebook));
} else {
//从Facebook登出,并使用Facebook使用Firebase进行身份验证,因此,注销
if(this.mAuthData!= null&& this.mAuthData.getProvider ().equals(facebook)){
mFirebaseRef.unauth();
setAuthenticatedUser(null);




$ b 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;
$ b $ // TODO
// if(ttokens> MainActivity.getmTopWin()){
// MainActivity.setmTopWin(ttokens);
//

Firebase ref = new Firebase(https://< url> .firebaseio.com / users /+ MainActivity.uID +/);
最终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 +/);
最终Firebase tokensRef = ref.child(spins);
tokensRef.addListenerForSingleValueEvent(new ValueEventListener(){
@Override $ b $ 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){}
});


$ b public static void givemSpins(final int mspins){

Firebase ref = new Firebase(https://< url> .firebaseio.com / users /+ MainActivity.uID +/);
最终Firebase tokensRef = ref.child(spins);
tokensRef.addListenerForSingleValueEvent(new ValueEventListener(){
@Override $ b $ 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 +/);
最终Firebase tokensRef = ref.child(totalspins);
tokensRef.addListenerForSingleValueEvent(new ValueEventListener(){
@Override $ b $ 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; FireBase ref = new Firebase(https://< url> .firebaseio.com /)/ / Firebase ref = new Firebase(


public static void setmTopWin(int mTopWin){

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 +/);
最终Firebase tokensRef = ref.child(topwin);
tokensRef.addListenerForSingleValueEvent(new ValueEventListener(){
@Override $ b $ public void onDataChange(DataSnapshot dataSnapshot){
int i = Integer.valueOf(dataSnapshot.getValue()。toString( ));

if(i
tokensRef.setValue(mTokensWon);

}

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


$ b $ / code $ / pre

解决方案

您需要设置一个首选项,如 FIRST_LAUNCH ,并检查每次用户登录时是否为true。首次启动应用程序时, 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();





$ b

所以你可能会考虑用户是否卸载你的应用程序然后重新安装,首选项将消失, addUser()函数将被再次调用。没问题,只要指向子属性的路径相同,您就不会获得新的Firebase条目。这些值将被替换为特定的路径(如果它存在的话)和用户的当前信息。



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

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

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

// User exists。Do nothing

} else addUser();

}

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


I've created a method to take a users facebook data, after they login, and create a "user" for them on my firebase database. this method, addUser(), also creates and sets the variables for said user. But I have to leave the method in, login, so it creates my variables, then comment the method out for future testing, or it will reset all the values. So where can I add "addUser()" to create said user the first time, and make sure it never call it again, as long as the user already exists?

MainActivity (start and login)

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Html;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.facebook.AccessToken;
import com.facebook.AccessTokenTracker;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.GraphRequest;
import com.facebook.GraphResponse;
import com.facebook.appevents.AppEventsLogger;
import com.facebook.login.LoginManager;
import com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;
import com.facebook.login.widget.ProfilePictureView;
import com.facebook.share.widget.ShareDialog;
import com.firebase.client.AuthData;
import com.firebase.client.DataSnapshot;
import com.firebase.client.Firebase;
import com.firebase.client.FirebaseError;
import com.firebase.client.ValueEventListener;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Map;


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);
 //   details.setOnClickListener(new View.OnClickListener() {
 //       @Override
 //       public void onClick(View view) {
 //           details_dialog.show();
 //      }
 //   });
    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) {

        //right here captain \/1
      //  addUser();
        //createUser();

        RequestData();

        getLoginDetails(login);

        getUserInfo();

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


        // share.setVisibility(View.VISIBLE);
       // details.setVisibility(View.VISIBLE);
    }
    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) {


            //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) {}
    });

}
}

解决方案

You need to set a preference like FIRST_LAUNCH and check if its true each time your user logs in. First time the application launches, the FIRST_LAUNCH preference won't be found. So call your addUser() function to create a new entry in your FireBase database.

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

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

So you might be thinking of if an user uninstalls your application and then reinstalls it, the preferences will be gone and the addUser() function will be called again. No problem, you won't get a new Firebase entry as long as the path to the child attribute is the same. The values will be replaced to the specific path (if it does exist), with current information of user.

Now if you want to check if your user already exists in Firebase database you need to add a listener like this. I'm attaching a code sample for better understanding.

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) {}
});

这篇关于正确的代码位置检查Firebase是否已创建用户?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆