I am creating Login with Facebook from Firebase. I am using Facebook Sdk and AccountKit with Firebase Auth. I worked with Firebase Auth on dozens of projects before everything used to run smoothly. This time I am working with AccountKit too.
This is my traditional code to login with facebook and retrieving the access token.
mAuth = FirebaseAuth.getInstance();
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
firebaseAuth.getCurrentUser();
}
};
mCallbackManager = CallbackManager.Factory.create();
facebookLogin.setReadPermissions("email", "public_profile", "user_birthday");
facebookLogin.registerCallback(mCallbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
Log.d(TAG, "facebook:onSuccess:" + loginResult);
handleFacebookAccessToken(loginResult.getAccessToken());
Profile profile = Profile.getCurrentProfile();
if (profile != null) {
userId = profile.getId();
}
}
#Override
public void onCancel() {
updateUI(null);
}
#Override
public void onError(FacebookException error) {
updateUI(null);
}
});
The ActivityResult Code now has both AccountKit Code and Facebook CallbackManager
#Override
protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
super.onActivityResult(requestCode, resultCode, data);
mCallbackManager.onActivityResult(requestCode, resultCode, data);
// confirm that this response matches your request
if (requestCode == APP_REQUEST_CODE) {
AccountKitLoginResult loginResult = data.getParcelableExtra(AccountKitLoginResult.RESULT_KEY);
if (loginResult.getError() != null) {
// display login error
String toastMessage = loginResult.getError().getErrorType().getMessage();
Toast.makeText(this, toastMessage, Toast.LENGTH_LONG).show();
} else if (loginResult.getAccessToken() != null) {
// on successful login, proceed to the account activity
launchAccountActivity();
}
}
}
The problem is here where the App Crashes on this method while handling the AccessToken.
private void handleFacebookAccessToken(final AccessToken token) {
Log.d(TAG, "handleFacebookAccessToken:" + token);
showProgressDialog();
AuthCredential credential = FacebookAuthProvider.getCredential(token.getToken());
mAuth.signInWithCredential(credential).addOnSuccessListener(this, new OnSuccessListener<AuthResult>() {
#Override
public void onSuccess(AuthResult authResult) {
updateUI(authResult.getUser());
}
});
}
private void updateUI(final FirebaseUser firebaseUser){
if (firebaseUser != null) {
Map<String, Object> updateValues = new HashMap<>();
Profile profile = Profile.getCurrentProfile();
if (profile != null) {
userId = profile.getId();
}
updateValues.put("userName", firebaseUser.getDisplayName() != null ? firebaseUser.getDisplayName() : "Anonymous");
updateValues.put("photo", firebaseUser.getPhotoUrl() != null ? firebaseUser.getPhotoUrl() : null);
updateValues.put("userId", firebaseUser.getUid());
updateValues.put("facebookId", userId != null ? userId : null);
FirebaseUtil.getCustomersRef().child(firebaseUser.getUid()).updateChildren(
updateValues,
new DatabaseReference.CompletionListener() {
#Override
public void onComplete(DatabaseError firebaseError, DatabaseReference databaseReference) {
if (firebaseError == null) {
doPhoneLogin();
}
}
});
}
}
Here is my Logcat for the Crash
08-09 14:07:02.571 9962-14870/in.order.craveu D/FA: Connected to remote service
08-09 14:07:02.571 9962-14870/in.order.craveu V/FA: Processing queued up service tasks: 4
08-09 14:07:05.668 9962-10097/in.order.craveu D/FirebaseAuth: Notifying id token listeners about user ( 5mSc7SjIltWWWHWzUJ3AoxkobEW2 ).
08-09 14:07:05.685 9962-9962/in.order.craveu D/FirebaseApp: Notifying auth state listeners.
08-09 14:07:05.685 9962-9962/in.order.craveu D/FirebaseApp: Notified 0 auth state listeners.
08-09 14:07:05.756 9962-9962/in.order.craveu I/DynamiteModule: Considering local module com.google.android.gms.firebase_database:4 and remote module com.google.android.gms.firebase_database:6
08-09 14:07:05.756 9962-9962/in.order.craveu I/DynamiteModule: Selected remote version of com.google.android.gms.firebase_database, version >= 6
08-09 14:07:06.369 9962-9972/in.order.craveu I/art: Background partial concurrent mark sweep GC freed 46716(1878KB) AllocSpace objects, 7(136KB) LOS objects, 39% free, 12MB/20MB, paused 5.432ms total 64.680ms
08-09 14:07:06.435 9962-9962/in.order.craveu D/AndroidRuntime: Shutting down VM
08-09 14:07:06.569 9962-9962/in.order.craveu E/UncaughtException: java.lang.StackOverflowError: stack size 8MB
at com.google.android.gms.internal.zg.zzao(Unknown Source)
at com.google.android.gms.internal.zg.zzar(Unknown Source)
at com.google.android.gms.internal.zh.zzas(Unknown Source)
at com.google.android.gms.internal.zg.zzao(Unknown Source)
at com.google.android.gms.internal.zg.zzar(Unknown Source)
After the crash when I open the application I am logged in with Facebook.
Related
This question has been asked already but it doesn't have an answer and i'm looking for help in this.
I want to integrate stripe to my android firebase app.But I keep getting the error java.lang.IllegalArgumentException: Parameter specified as non-null is null: method kotlin.jvm.internal.Intrinsics.checkParameterIsNotNull. I am not using kotlin in my project but java so I'm not sure where kotlin comes from.
Error
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.myapp.app, PID: 26686
java.lang.IllegalArgumentException: Parameter specified as non-null is null: method kotlin.jvm.internal.Intrinsics.checkParameterIsNotNull, parameter clientSecret
at com.stripe.android.model.ConfirmPaymentIntentParams$Companion.createWithPaymentMethodCreateParams(Unknown Source:29)
at com.stripe.android.model.ConfirmPaymentIntentParams$Companion.createWithPaymentMethodCreateParams$default(ConfirmPaymentIntentParams.kt:420)
at com.stripe.android.model.ConfirmPaymentIntentParams.createWithPaymentMethodCreateParams(Unknown Source:14)
at com.myapp.app.PaymentPageActivity.lambda$startCheckout$0$PaymentPageActivity(PaymentPageActivity.java:84)
at com.myapp.app.-$$Lambda$PaymentPageActivity$lysPf2qYJjjVdPRqihuLblLplpI.onClick(Unknown Source:2)
//My code
// Configure the SDK with your Stripe publishable key so it can make requests to Stripe
stripe = new Stripe(
getApplicationContext(),
Objects.requireNonNull("stripe_key")
);
startCheckout();
}
private void startCheckout() {
// ...
// Hook up the pay button to the card widget and stripe instance
Button payButton = findViewById(R.id.payButton);
payButton.setOnClickListener((View view) -> {
CardInputWidget cardInputWidget = findViewById(R.id.cardInputWidget);
PaymentMethodCreateParams params = cardInputWidget.getPaymentMethodCreateParams();
if (params != null) {
ConfirmPaymentIntentParams confirmParams = ConfirmPaymentIntentParams
.createWithPaymentMethodCreateParams(params, paymentIntentClientSecret);
confirmParams.getPaymentMethodCreateParams();
final Context context = getApplicationContext();
stripe = new Stripe(
context,
PaymentConfiguration.getInstance(context).getPublishableKey()
);
stripe.confirmPayment(this, confirmParams);
}
});
}
// ...
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Handle the result of stripe.confirmPayment
stripe.onPaymentResult(requestCode, data, new PaymentResultCallback(PaymentPageActivity.this));
}
// ...
private final class PaymentResultCallback
implements ApiResultCallback<PaymentIntentResult> {
#NonNull private final WeakReference<PaymentPageActivity> activityRef;
PaymentResultCallback(#NonNull PaymentPageActivity activity) {
activityRef = new WeakReference<>(activity);
}
#Override
public void onSuccess(#NonNull PaymentIntentResult result) {
final PaymentPageActivity activity = activityRef.get();
if (activity == null) {
return;
}
PaymentIntent paymentIntent = result.getIntent();
PaymentIntent.Status status = paymentIntent.getStatus();
if (status == PaymentIntent.Status.Succeeded) {
// Payment completed successfully
Gson gson = new GsonBuilder().setPrettyPrinting().create();
Toast.makeText(PaymentPageActivity.this, "Paymen success", Toast.LENGTH_SHORT).show();
} else if (status == PaymentIntent.Status.RequiresPaymentMethod) {
// Payment failed
Toast.makeText(PaymentPageActivity.this, "Failed", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onError(#NonNull Exception e) {
final PaymentPageActivity activity = activityRef.get();
if (activity == null) {
return;
}
// Payment request failed – allow retrying using the same payment method
Toast.makeText(PaymentPageActivity.this, "Error " +e.toString(), Toast.LENGTH_SHORT).show();
}
}
I'm trying to set up google sign in for my app but it keeps failing, I click on a button, get a popup, select account and a Toast pops up telling me that sign in failed. Any ways I can fix this? The problem lies in onActivityResult() method and the said Toast says "Auth went wrong". I've searched all over the internet but failed to find a solution or even a reason why this is happening. Line 80 is this
Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
public class SignInActivity extends AppCompatActivity {
static final int GOOGLE_SIGN_IN = 2;
FirebaseAuth mAuth;
Button btn_login;
GoogleSignInClient mGoogleSignInClient;
FirebaseAuth.AuthStateListener mAuthListener;
#Override
protected void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_in);
btn_login = findViewById(R.id.login);
mAuth = FirebaseAuth.getInstance();
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
if (firebaseAuth.getCurrentUser() != null) {
Switch();
}
}
};
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build();
mGoogleSignInClient = GoogleSignIn.getClient(this, gso);
btn_login.setOnClickListener(v -> signIn());
}
private void signIn() {
Intent signInIntent = mGoogleSignInClient.getSignInIntent();
startActivityForResult(signInIntent, GOOGLE_SIGN_IN);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
if (requestCode == GOOGLE_SIGN_IN) {
Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
try {
// Google Sign In was successful, authenticate with Firebase
GoogleSignInAccount account = task.getResult(ApiException.class);
firebaseAuthWithGoogle(account);
} catch (ApiException e) {
// Google Sign In failed, update UI appropriately
Log.w("TAG", "Google sign in failed", e);
Toast.makeText(SignInActivity.this, "Auth went wrong :/", Toast.LENGTH_SHORT).show();
// ...
}
}
}
private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
Log.d("TAG", "firebaseAuthWithGoogle:" + acct.getId());
AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, task -> {
if (task.isSuccessful()) {
// Sign in success, update UI with the signed-in user's information
Log.d("TAG", "signInWithCredential:success");
FirebaseUser user = mAuth.getCurrentUser();
Toast.makeText(SignInActivity.this, "Success!", Toast.LENGTH_SHORT).show();
updateUI(user);
Switch();
} else {
// If sign in fails, display a message to the user.
Log.w("TAG", "signInWithCredential:failure", task.getException());
Toast.makeText(SignInActivity.this, "Authentication failed.", Toast.LENGTH_SHORT).show();
updateUI(null);
}
});
}
}
2019-03-23 12:13:35.569 6312-6312/com.charpik.agropomocnik W/TAG: Google sign in failed
com.google.android.gms.common.api.ApiException: 10:
at com.google.android.gms.common.internal.ApiExceptionUtil.fromStatus(Unknown Source:4)
at com.google.android.gms.auth.api.signin.GoogleSignIn.getSignedInAccountFromIntent(Unknown Source:8)
at com.charpik.agropomocnik.SignInActivity.onActivityResult(SignInActivity.java:80)
at android.app.Activity.dispatchActivityResult(Activity.java:7701)
at android.app.ActivityThread.deliverResults(ActivityThread.java:5037)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:5084)
at android.app.ActivityThread.-wrap20(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2053)
at android.os.Handler.dispatchMessage(Handler.java:108)
at android.os.Looper.loop(Looper.java:166)
at android.app.ActivityThread.main(ActivityThread.java:7529)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:245)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:921)
I fixed the similar issue by using the latest version of the appcompat library.
implementation 'androidx.appcompat:appcompat:1.1.0-alpha03'
If it's not the case, try without requestIdToken(getString(R.string.default_web_client_id)). And if the error is not occurred, you should check the credential part again.
Check these:
Is SHA-1 fingerprint correct?
Is SHA-1 fingerprint for debug or release?
Is package name correct?
Did you use the web application type client ID?
Hi I'm using FireStore to store data in remote database. However, I had a problem with using set and update method.
When I want to update some value in some documents and display dialog after update, my android app restarts. The below is logcat which is displayed when I proceed above process.
12-27 12:09:49.838 17014-17014/com.wecobell.www.doggy D/showUnlockDialog: OnSuccess
12-27 12:09:49.875 17014-17014/com.wecobell.www.doggy W/OpenGLRenderer: Points are too far apart 4.000001
12-27 12:09:49.908 17014-17014/com.wecobell.www.doggy D/MainActivity: onPause
12-27 12:09:49.930 17014-17014/com.wecobell.www.doggy D/MainActivity: ---- Network Status Check ----
12-27 12:09:49.932 17014-17014/com.wecobell.www.doggy D/MainActivity: Wifi Connection : true, 4G or 5G : false
12-27 12:09:49.943 17014-17014/com.wecobell.www.doggy D/MainActivity: onCreate
As you can see, MainActivity is reopened, when 'showUnlockDialog' is successfully displayed. How can I solve this problem?
/**
* 메소드명 : unlockProfile
* 설명 : Method that unlocks user's profile
*/
private void unlockProfile(final int position) {
FirebaseFirestore firestore = FirebaseFirestore.getInstance();
FirebaseAuth auth = FirebaseAuth.getInstance();
FirebaseUser user = auth.getCurrentUser();
String currentUid = user.getUid();
FireStore.unlockInterestedUser(firestore, currentUid, interestedUsers.get(position).getUid());
}
/**
* 메소드명 : showUnlockDialog
* 설명 : Method that displays dialog.
*/
private void showUnlockDialog(final int position) {
MaterialDialog.Builder builder = new MaterialDialog.Builder(context);
builder.content("프로필을 보시려면 뼈다귀 포인트 5개가 필요합니다.")
.positiveText("적용")
.onPositive(new MaterialDialog.SingleButtonCallback() {
#Override
public void onClick(#NonNull MaterialDialog dialog, #NonNull DialogAction which) {
FirebaseFirestore firestore = FirebaseFirestore.getInstance();
DocumentReference dc = FireStore.getPointOfUser(firestore, MyUser.getInstance().getUid());
FirebaseAuth fa = FirebaseAuth.getInstance();
FirebaseUser user = fa.getCurrentUser();
final DocumentReference me = FireStore.getUserInfo(firestore, user.getUid());
me.get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
#Override
public void onSuccess(DocumentSnapshot documentSnapshot) {
Log.d("showUnlockDialog", "OnSuccess");
MyUser user = documentSnapshot.toObject(MyUser.class);
int newPoint = user.getPoint() - 5;
user.setPoint(newPoint);
me.set(user).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Log.d("showUnlockDialog", "unlockProfileMethod");
unlockProfile(position);
Toast.makeText(context, "업데이트 완료", Toast.LENGTH_SHORT).show();
}
});
}
});
}
})
.negativeText("취소")
.show();
}
I have been trying to learn how to use the GCM by going over their step by step guild. I get to the point of registering but it never actually does the registration part of the project. I have the configuration file in the project and I am using this website to test for push notification http://www.androidbegin.com/tutorial/gcm.html
So this is what it is giving me in the logcat:
02-18 14:07:42.866 32402-32402/com.example.mmillar.gcmpushnotificationtest D/Main Activity: Started
02-18 14:07:42.867 32402-32402/com.example.mmillar.gcmpushnotificationtest D/Checking PlayService: Started
02-18 14:07:42.868 32402-32402/com.example.mmillar.gcmpushnotificationtest D/Cheking player Service: true
02-18 14:07:42.868 32402-32402/com.example.mmillar.gcmpushnotificationtest D/Starting service:: Intent { cmp=com.example.mmillar.gcmpushnotificationtest/.Registration }
02-18 14:07:42.877 32402-32432/com.example.mmillar.gcmpushnotificationtest D/OpenGLRenderer: Use EGL_SWAP_BEHAVIOR_PRESERVED: true
02-18 14:07:42.949 32402-32432/com.example.mmillar.gcmpushnotificationtest I/OpenGLRenderer: Initialized EGL, version 1.4
02-18 14:07:43.008 32402-32432/com.example.mmillar.gcmpushnotificationtest W/EGL_emulation: eglSurfaceAttrib not implemented
02-18 14:07:43.008 32402-32432/com.example.mmillar.gcmpushnotificationtest W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0xad79f100, error=EGL_SUCCESS
02-18 14:07:45.679 32402-32407/com.example.mmillar.gcmpushnotificationtest W/art: Suspending all threads took: 12.876ms
02-18 14:07:53.143 32402-32429/com.example.mmillar.gcmpushnotificationtest I/GMPM: Tag Manager is not found and thus will not be used
02-18 14:08:33.167 32402-32411/com.example.mmillar.gcmpushnotificationtest W/art: Suspending all threads took: 5.121ms
02-18 14:10:19.493 32402-32407/com.example.mmillar.gcmpushnotificationtest W/art: Suspending all threads took: 6.036ms
02-18 14:11:15.635 32402-32407/com.example.mmillar.gcmpushnotificationtest W/art: Suspending all threads took: 12.898ms
As it shows it get down to the start(intent0 part of the onCreate method. But it never reaches to the Register class at all. I am a bit stumped on what I am doing wrong here. Any help will be appreciated.
here is the main activity code that starts the app
public class GCMMainActivity extends AppCompatActivity{
private static final int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
private static final String TAG = "MainActivity";
private BroadcastReceiver mRegistrationBroadcastReceiver;
private ProgressBar mRegistrationProgressBar;
private TextView mInformationTextView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gcmmain);
Log.d("Main Activity", "Started");
mRegistrationProgressBar = (ProgressBar) findViewById(R.id.registrationProgressBar);
mRegistrationBroadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Log.d("Main Activity: ", "onReceive Method");
mRegistrationProgressBar.setVisibility(ProgressBar.GONE);
SharedPreferences sharedPreferences =
PreferenceManager.getDefaultSharedPreferences(context);
boolean sentToken = sharedPreferences.getBoolean(Preferences.SENT_TOKEN_TO_SERVER, false);
if (sentToken) {
mInformationTextView.setText("Token retrieved and sent to server! You can now use gcmsender to\n" +
" send downstream messages to this app");
} else {
mInformationTextView.setText("An error occurred while either fetching the InstanceID token,\n" +
"sending the fetched token to the server or subscribing to the PubSub topic. ");
}
}
};
mInformationTextView = (TextView) findViewById(R.id.informationTextView);
if (checkPlayServices()) {
Log.d("Checking PlayService", "Started");
Boolean check = checkPlayServices();
Log.d("Cheking player Service ", check.toString());
// Start IntentService to register this application with GCM.
Intent intent = new Intent(this, Registration.class);
//this should call the registration code
Log.d("Starting service: ", intent.toString());
startService(intent);
}
}
#Override
protected void onResume() {
super.onResume();
LocalBroadcastManager.getInstance(this).registerReceiver(mRegistrationBroadcastReceiver,
new IntentFilter(Preferences.REGISTRATION_COMPLETE));
}
#Override
protected void onPause() {
LocalBroadcastManager.getInstance(this).unregisterReceiver(mRegistrationBroadcastReceiver);
super.onPause();
}
//deos the device support google play?
private boolean checkPlayServices() {
GoogleApiAvailability apiAvailability = GoogleApiAvailability.getInstance();
int resultCode = apiAvailability.isGooglePlayServicesAvailable(this);
if (resultCode != ConnectionResult.SUCCESS) {
if (apiAvailability.isUserResolvableError(resultCode)) {
apiAvailability.getErrorDialog(this, resultCode, PLAY_SERVICES_RESOLUTION_REQUEST)
.show();
} else {
Log.d(TAG, "This device is not supported.");
finish();
}
return false;
}
return true;
}
}
And this is the registration class
public class Registration extends IntentService {
private static final String TAG = "RegIntentService";
private static final String[] TOPICS = {"global"};
private final String SENDERID = "630172590481";
public Registration() {
super(TAG);
}
#Override
protected void onHandleIntent(Intent intent) {
Log.d("Registration Class: ", "onHandleIntent mehtod");
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
//Register for the gcm
try {
// Initially this call goes out to the network to retrieve the token, subsequent calls
// are local.
InstanceID instanceID = InstanceID.getInstance(this);
//this is using the google configuration file crated at their website
//https://developers.google.com/cloud-messaging/android/start
String token = instanceID.getToken(getString(R.string.gcm_defaultSenderId),
GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);
/*used to hardcode the Sender ID
String token = instanceID.getToken(SENDERID),
GoogleCloudMessaging.INSTANCE_ID_SCOPE, null);
*/
Log.d(TAG, "GCM Registration Token: " + token);
sendRegistrationToServer(token);
// Subscribe to topic channels
subscribeTopics(token);
// You should store a boolean that indicates whether the generated token has been
// sent to your server. If the boolean is false, send the token to your server,
// otherwise your server should have already received the token.
sharedPreferences.edit().putBoolean(Preferences.SENT_TOKEN_TO_SERVER, true).apply();
} catch (Exception e) {
Log.d(TAG, "Failed to complete token refresh", e);
// If an exception happens while fetching the new token or updating our registration data
// update at a later time.
sharedPreferences.edit().putBoolean(Preferences.SENT_TOKEN_TO_SERVER, false).apply();
}
// Notify UI that registration has completed, so the progress indicator can be hidden.
Intent registrationComplete = new Intent(Preferences.REGISTRATION_COMPLETE);
LocalBroadcastManager.getInstance(this).sendBroadcast(registrationComplete);
}
/**
* Persist registration to third-party servers.
*
* Modify this method to associate the user's GCM registration token with any server-side account
* maintained by your application.
*
* #param token The new token.
*/
private void sendRegistrationToServer(String token) {
// Add custom implementation, as needed.
}
//Subscribe to any GCM topics of interest, as defined by the TOPICS constant.
private void subscribeTopics(String token) throws IOException {
GcmPubSub pubSub = GcmPubSub.getInstance(this);
for (String topic : TOPICS) {
pubSub.subscribe(token, "/topics/" + topic, null);
}
}
}
When the app starts for the first time and the user grants permission, the app crashes. If the app is restarted the user is already logged in and the app works perfectly.
To recreate the error I have to delete the app from the phone and disassociate the app from my Facebook account. ( if this helps )
Also to clarify, I understand what a null pointer exception is, just don't quite understand why it is happening on only the first run. Do I need to add some kind of statement for the first time run?
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getApplicationContext());
Parse.enableLocalDatastore(this);
Parse.initialize(this);
//parse test
ParseObject testObject = new ParseObject("TestObject");
testObject.put("foo", "bar");
testObject.saveInBackground();
callbackManager = CallbackManager.Factory.create();
setContentView(R.layout.activity_main_page);
info = (TextView) findViewById(R.id.info);
loginButton = (LoginButton) findViewById(R.id.login_button);
Bundle logout_req = getIntent().getExtras();
if (logout_req != null) {
String logout = logout_req.getString("user_logout");
if (logout == "logout") {
LoginManager.getInstance().logOut();
}
}
Toolbar myToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(myToolbar);
if (Profile.getCurrentProfile() != null) {
Profile profile1 = Profile.getCurrentProfile();
Intent myIntent = new Intent(getBaseContext(), Home.class);
myIntent.putExtra("user_id", profile1.getId());
myIntent.putExtra("user_name", profile1.getName());
MainPage.this.startActivity(myIntent);
}
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
Profile profile = Profile.getCurrentProfile();
ParseUser.logInInBackground(profile.getId(), "0", new LogInCallback() {
public void done(ParseUser user, ParseException e) {
if (user == null) {
//No such user, create a new user.
ParseUser newUser = new ParseUser();
Profile profile = Profile.getCurrentProfile();
newUser.setUsername(profile.getId());
newUser.setPassword("0");
newUser.signUpInBackground();
//Send required data to home page
Intent myIntent = new Intent(getBaseContext(), Home.class);
myIntent.putExtra("user_id", profile.getId());
myIntent.putExtra("user_name", profile.getName());
MainPage.this.startActivity(myIntent);
System.out.println("NEW USER CREATED! LOGGED IN AND SENT TO HOMEPAGE");
} else {
Profile profile = Profile.getCurrentProfile();
//Send required data to home page
Intent myIntent = new Intent(getBaseContext(), Home.class);
myIntent.putExtra("user_id", profile.getId());
myIntent.putExtra("user_name", profile.getName());
MainPage.this.startActivity(myIntent);
System.out.println("USER LOGGED IN! SENT TO HOMEPAGE");
}
}
});
}
#Override
public void onCancel() {
info.setText("Login attempt canceled .");
}
#Override
public void onError(FacebookException e) {
info.setText("Login attempt failed.");
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}
The error appears to happen just after loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>()
The error:
Process: com.george.coffeeconversation, PID: 16920
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=64206, result=-1, data=Intent { (has extras) }} to activity {com.george.coffeeconversation/com.george.coffeeconversation.MainPage}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.facebook.Profile.getId()' on a null object reference
at android.app.ActivityThread.deliverResults(ActivityThread.java:3680)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3723)
at android.app.ActivityThread.access$1300(ActivityThread.java:156)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1400)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:211)
at android.app.ActivityThread.main(ActivityThread.java:5373)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1020)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:815)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.facebook.Profile.getId()' on a null object reference
at com.george.coffeeconversation.MainPage.run(MainPage.java:108)
at com.george.coffeeconversation.MainPage$1.onSuccess(MainPage.java:90)
at com.george.coffeeconversation.MainPage$1.onSuccess(MainPage.java:87)
at com.facebook.login.LoginManager.finishLogin(LoginManager.java:510)
at com.facebook.login.LoginManager.onActivityResult(LoginManager.java:193)
at com.facebook.login.LoginManager$1.onActivityResult(LoginManager.java:136)
at com.facebook.internal.CallbackManagerImpl.onActivityResult(CallbackManagerImpl.java:82)
at com.george.coffeeconversation.MainPage.onActivityResult(MainPage.java:144)
at android.app.Activity.dispatchActivityResult(Activity.java:6192)
at android.app.ActivityThread.deliverResults(ActivityThread.java:3676)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3723)
at android.app.ActivityThread.access$1300(ActivityThread.java:156)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1400)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:211)
at android.app.ActivityThread.main(ActivityThread.java:5373)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1020)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:815)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.facebook.Profile.getId()' on a null object reference
Apparently the Profile object you're trying to access is null at the point in time you're referencing it.
Since you mentioned it's occurring after returning from Facebook, it's probably happening in either done(ParseUser user, ParseException e) or onSuccess(LoginResult loginResult).
Try logging whether Profile.getCurrentProfile() is null at those points and you'll be able to track it down.