当我在应用中使用Google帐户/ facebook帐户登录时,我想将帐户数据记录到firebase realltime-database中,但是我没想到我的目标,因为我开始登录应用程序并进行存储处理,该应用程序被强制关闭。
这是我尝试过的代码
LoginActivity.java
package id.co.dolansemarang.loginfirebaseds;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.facebook.AccessToken;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;
import com.google.android.gms.auth.api.Auth;
import com.google.android.gms.auth.api.signin.GoogleSignIn;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInClient;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.ApiException;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthCredential;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FacebookAuthProvider;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.auth.GoogleAuthProvider;
import com.google.firebase.database.DatabaseReference;
import id.co.dolansemarang.loginfirebaseds.model.User;
import id.co.dolansemarang.loginfirebaseds.model.UsersProvider;
public class LoginActivity extends BaseActivity implements View.OnClickListener, GoogleApiClient.OnConnectionFailedListener {
private static final String TAG = "Login User";
private static final int RC_SIGN_IN = 1234;
CallbackManager callbackManager;
GoogleSignInClient googleSignInClient;
GoogleApiClient mGoogleApiClient;
LoginButton loginButton;
Button btnLogin;
LinearLayout btnGoogleSignIn, btnFacebookSignIn;
EditText edtEmailLogin, edtPasswordLogin;
TextView tvResetPass, tvRegisterLink;
FirebaseAuth firebaseAuthLogin;
FirebaseAuth.AuthStateListener authStateListener;
// DatabaseReference userRefLogin;
FirebaseUser curUser;
DatabaseReference providerLoginRef;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
btnLogin = findViewById(R.id.btn_login);
edtEmailLogin = findViewById(R.id.edt_email_login);
edtPasswordLogin = findViewById(R.id.edt_password_login);
tvResetPass = findViewById(R.id.tv_reset_pass);
tvRegisterLink = findViewById(R.id.tv_register_link);
btnGoogleSignIn = findViewById(R.id.btn_sign_in_with_google);
btnFacebookSignIn = findViewById(R.id.btn_sign_in_with_facebook);
loginButton = findViewById(R.id.login_button);
firebaseAuthLogin = FirebaseAuth.getInstance();
// authStateListener = new FirebaseAuth.AuthStateListener() {
// @Override
// public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
// if (curUser != null) {
// Log.d(TAG, "onAuthStateChanged: Sign In");
// } else {
// Log.d(TAG, "onAuthStateChanged:signed_out");
// }
// }
// };
//Google Sign In
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build();
mGoogleApiClient = new GoogleApiClient.Builder(LoginActivity.this)
.enableAutoManage(LoginActivity.this, this)
.addApi(Auth.GOOGLE_SIGN_IN_API, gso)
.build();
googleSignInClient = GoogleSignIn.getClient(this, gso);
//facebook Sign In
callbackManager = CallbackManager.Factory.create();
loginButton.setReadPermissions("email", "public_profile");
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
@Override
public void onSuccess(LoginResult loginResult) {
Log.d(TAG, "facebook: onSuccess Login" + loginResult);
handleFacebookAccessToken(loginResult.getAccessToken());
}
@Override
public void onCancel() {
Log.d(TAG, "facebook: onCancel");
}
@Override
public void onError(FacebookException error) {
Log.d(TAG, "facebook: onError", error);
}
});
btnFacebookSignIn.setOnClickListener(this);
btnLogin.setOnClickListener(this);
tvResetPass.setOnClickListener(this);
btnGoogleSignIn.setOnClickListener(this);
tvRegisterLink.setOnClickListener(this);
}
private void handleFacebookAccessToken(AccessToken accessToken) {
Log.d(TAG, "handleFacebookAccessToken : " + accessToken);
showProgressDialog();
AuthCredential credential = FacebookAuthProvider.getCredential(accessToken.getToken());
firebaseAuthLogin.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
Log.d(TAG, "your account has been success to register");
FirebaseUser user = firebaseAuthLogin.getCurrentUser();
// updateUI(user);
startActivity(new Intent(getApplicationContext(), MainActivity.class));
Toast.makeText(LoginActivity.this, "Welcome " + user.getEmail() + "", Toast.LENGTH_LONG).show();
finish();
} else {
Log.w(TAG, "please, try again", task.getException());
Toast.makeText(LoginActivity.this, "Gagal Login, silakan coba lagi", Toast.LENGTH_LONG).show();
// updateUI(null);
}
hideProgressDialog();
}
});
}
@Override
protected void onStart() {
super.onStart();
// cek apakah pengguna sudah pernah masuk sehingga ada update UI disini
if(authStateListener!= null){
FirebaseUser currentUser = firebaseAuthLogin.getCurrentUser();
updateUI(currentUser);
authStateListener.onAuthStateChanged(firebaseAuthLogin);
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
if (requestCode == RC_SIGN_IN) {
// GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
// handleSignInResult(result);
Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
try {
GoogleSignInAccount account = task.getResult(ApiException.class);
loginWithGoogle(account);
} catch (ApiException e) {
Log.w(TAG, "Google Sign I Failed", e);
updateUI(curUser);
}
}
}
private void loginWithGoogle(GoogleSignInAccount account) {
showProgressDialog();
AuthCredential credential = GoogleAuthProvider.getCredential(account.getIdToken(), null);
firebaseAuthLogin.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
String nama =FirebaseAuth.getInstance().getCurrentUser().getDisplayName();
String email = FirebaseAuth.getInstance().getCurrentUser().getEmail();
String providerID =FirebaseAuth.getInstance().getCurrentUser().getProviderId();
UsersProvider users = new UsersProvider (uid,nama,email,providerID);
providerLoginRef.child("UsersProviders").child(uid).setValue(users).addOnCompleteListener(LoginActivity.this, new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
updateUI(curUser);
}
});
} else {
Log.w(TAG, "please, try again", task.getException());
Toast.makeText(LoginActivity.this, "Gagal Login, silakan coba lagi", Toast.LENGTH_LONG).show();
}
hideProgressDialog();
}
});
}
private void loginUserWithEmail(String email, String password) {
Log.d(TAG, "signIn:" + email);
if (!validateForm()) {
return;
}
showProgressDialog();
firebaseAuthLogin.signInWithEmailAndPassword(email, password).addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
Log.d(TAG, "your account has been success to register");
FirebaseUser user = firebaseAuthLogin.getCurrentUser();
if (user.isEmailVerified()) {
updateUI(user);
} else {
Toast.makeText(LoginActivity.this, "Silakan cek inbox untuk verifikasi", Toast.LENGTH_LONG).show();
}
} else {
Log.w(TAG, "please, try again", task.getException());
Toast.makeText(LoginActivity.this, "Gagal Login, silakan coba lagi", Toast.LENGTH_LONG).show();
// updateUI(null);
}
hideProgressDialog();
}
});
}
private void updateUI(FirebaseUser user) {
hideProgressDialog();
if (user != null) {
user.getDisplayName();
startActivity(new Intent(LoginActivity.this, MainActivity.class));
Toast.makeText(this, "Welcome " + user.getEmail() + "", Toast.LENGTH_LONG).show();
finish();
}
}
private boolean validateForm() {
boolean valid = true;
String email = edtEmailLogin.getText().toString();
String password = edtPasswordLogin.getText().toString();
if (TextUtils.isEmpty(email)) {
Toast.makeText(getApplicationContext(), "Harap isi email kembali", Toast.LENGTH_LONG).show();
valid = false;
} else {
if (TextUtils.isEmpty(password)) {
Toast.makeText(getApplicationContext(), "Harap isi password kembali", Toast.LENGTH_LONG).show();
valid = false;
} else {
if (password.length() <= 6) {
Toast.makeText(getApplicationContext(), "password contained minimum 6 character", Toast.LENGTH_LONG).show();
valid = false;
}
}
}
return valid;
}
@Override
public void onClick(View v) {
int i = v.getId();
if (i == R.id.btn_login) {
loginUserWithEmail(edtEmailLogin.getText().toString(), edtPasswordLogin.getText().toString());
} else if (i == R.id.tv_reset_pass) {
startActivity(new Intent(LoginActivity.this, ResetPasswordActivity.class));
finish();
} else if (i == R.id.btn_sign_in_with_google) {
signInGoogle();
} else if (i == R.id.tv_register_link) {
gotoRegister();
} else if (i == R.id.btn_sign_in_with_facebook) {
loginButton.performClick();
}
}
private void gotoRegister() {
startActivity(new Intent(this, RegisterActivity.class));
finish();
}
private void signInGoogle() {
Intent signIntent = googleSignInClient.getSignInIntent();
startActivityForResult(signIntent, RC_SIGN_IN);
}
@Override
protected void onStop() {
super.onStop();
if (authStateListener != null) {
firebaseAuthLogin.removeAuthStateListener(authStateListener);
}
}
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
}
}
我希望我可以存储,但是相反,因为logcat显示这样的错误
2019-05-04 20:55:13.471 16495-16495/id.co.dolansemarang.loginfirebaseds E/AndroidRuntime: FATAL EXCEPTION: main
Process: id.co.dolansemarang.loginfirebaseds, PID: 16495
java.lang.NullPointerException: Attempt to invoke virtual method 'com.google.firebase.database.DatabaseReference com.google.firebase.database.DatabaseReference.child(java.lang.String)' on a null object reference
at id.co.dolansemarang.loginfirebaseds.LoginActivity$3.onComplete(LoginActivity.java:203)
at com.google.android.gms.tasks.zzj.run(Unknown Source)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6776)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1518)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1408)
我希望您能帮助我。之前谢谢
答案 0 :(得分:1)
要解决此问题,请更改以下代码行:
DatabaseReference providerLoginRef;
到
DatabaseReference providerLoginRef = FirebaseDatabase.getInstance().getReference();
由于您的providerLoginRef
对象从未初始化,所以出现了该错误。