Hello Every One I am building an android app for my project and I have error in Facebook login and Twitter Login is not working
Here is my code for mainActivity.java
package com.example.creative.fbtest;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.GraphRequest;
import com.facebook.GraphResponse;
import com.facebook.login.LoginManager;
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.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.auth.api.signin.GoogleSignInResult;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.SignInButton;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Status;
import com.twitter.sdk.android.core.Callback;
import com.twitter.sdk.android.core.Result;
import com.twitter.sdk.android.core.TwitterAuthConfig;
import com.twitter.sdk.android.core.TwitterException;
import com.twitter.sdk.android.core.TwitterSession;
import com.twitter.sdk.android.core.identity.TwitterLoginButton;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.Arrays;
public class MainActivity extends AppCompatActivity implements android.view.View.OnClickListener,GoogleApiClient.OnConnectionFailedListener {
//initialization
private LoginButton loginButtonFb;
private TextView textViewStatus;
private CallbackManager FBcallbackManager;
private LoginManager loginManager;
private SignInButton signInButtonGoogle;
private Button signOutButtonGoogle;
private GoogleApiClient googleApiClient;
private TextView txtEmail,txtName;
private static final int request_code = 10;
private LinearLayout profile_google;
private ImageView prof_pic;
private TwitterLoginButton signInButtonTwitter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//initializing Facebook Sdk
// FacebookSdk.sdkInitialize(getApplicationContext());
setContentView(R.layout.activity_main);
loginButtonFb = (LoginButton) findViewById(R.id.fb_login_button);
textViewStatus = (TextView) findViewById(R.id.txt_login_status);
//initialize
profile_google = (LinearLayout) findViewById(R.id.profile_google_layout);
signOutButtonGoogle = (Button) findViewById(R.id.gmail_logout_btn);
signInButtonGoogle = (SignInButton) findViewById(R.id.google_sign_in_button);
txtEmail = (TextView) findViewById(R.id.txt_gmail_email);
txtName=(TextView)findViewById(R.id.txt_gmail_name);
prof_pic=(ImageView)findViewById(R.id.google_prof_pic);
//for twitter Login
signInButtonTwitter=(TwitterLoginButton) findViewById(R.id.twitter_login_button);
signInButtonTwitter.setCallback(new Callback<TwitterSession>() {
@Override
public void success(Result<TwitterSession> result) {
textViewStatus.setText("Login Successfull Twitter");
}
@Override
public void failure(TwitterException e) {
textViewStatus.setText("Login Failed Twitter!");
}
});
//set on click listener
signInButtonGoogle.setOnClickListener(this);
signOutButtonGoogle.setOnClickListener(this);
//display profile after login
profile_google.setVisibility(View.GONE);
//initializing sign in options to fetch user
GoogleSignInOptions signInOptions = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN).requestEmail().build();
// ATTENTION: This "addApi(AppIndex.API)"was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
googleApiClient = new GoogleApiClient.Builder(this).enableAutoManage(this, this).addApi(Auth.GOOGLE_SIGN_IN_API, signInOptions).build();
//for accessing user information
loginButtonFb.setReadPermissions(Arrays.asList("public_profile", "email", "user_birthday", "user_friends"));
//initialize Callback Manger
FBcallbackManager= CallbackManager.Factory.create();
loginButtonFb.registerCallback(FBcallbackManager, new FacebookCallback<LoginResult>() {
//on success
@Override
public void onSuccess(final LoginResult loginResult) {
//TODO: use the profile class to get information
//app
GraphRequest request=GraphRequest.newMeRequest(
loginResult.getAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
@Override
public void onCompleted(JSONObject object, GraphResponse response) {
try {
//application code
String name=object.getString("name");
String email=object.getString("email");
Log.e("Name=",""+name);
Toast.makeText(MainActivity.this, "Email"+email, Toast.LENGTH_SHORT).show();
}
catch (JSONException e)
{
Log.e("MYAPP", "unexpected JSON exception", e);
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,email,gender,birthday");
request.setParameters(parameters);
request.executeAsync();
Toast.makeText(MainActivity.this, "Login Successful", Toast.LENGTH_SHORT).show();
textViewStatus.setText("Login Successful" + loginResult.getAccessToken().getUserId());
signInButtonGoogle.setVisibility(View.GONE);
profile_google.setVisibility(View.GONE);
}
@Override
public void onCancel()
{
Toast.makeText(MainActivity.this, "Login Cancel", Toast.LENGTH_SHORT).show();
loginManager.getInstance().logOut();
textViewStatus.setText("Login Cancel");
}
@Override
public void onError(FacebookException error) {
textViewStatus.setText("Some Error Occured"+"/n"+"Error"+error.toString());
signInButtonGoogle.setVisibility(View.GONE);
signInButtonTwitter.setVisibility(View.GONE);
Log.e("Error","Facebook Error",error);
Toast.makeText(MainActivity.this, error.toString(), Toast.LENGTH_SHORT).show();
}
//to get username
});
}
@Override
protected void onActivityResult(int requestCode,int resultCode,Intent data)
{
super.onActivityResult(requestCode,resultCode,data);
//TO DO:Error occurs of facebook and Twitter is not working
if (requestCode == request_code)
{
GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
handleResult(result);
}
else if(requestCode==TwitterAuthConfig.DEFAULT_AUTH_REQUEST_CODE)
{
// Pass the activity result to the login button.
signInButtonTwitter.onActivityResult(requestCode, resultCode, data);
}
else
{
FBcallbackManager.onActivityResult(requestCode,requestCode,data);
}
}
//which button is clicked by user
@Override
public void onClick(View v) {
switch (v.getId())
{
case R.id.google_sign_in_button:
signIn();
break;
case R.id.gmail_logout_btn:
signOut();;
break;
}
}
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
}
private void signIn()
{
try {
//creating intent variable
Intent intentGoogleSignIn = Auth.GoogleSignInApi.getSignInIntent(googleApiClient);
startActivityForResult(intentGoogleSignIn, request_code);
}
catch (Exception ex)
{
Toast.makeText(getApplicationContext(),ex.getMessage(),Toast.LENGTH_SHORT).show();
}
}
private void signOut()
{
Auth.GoogleSignInApi.signOut(googleApiClient).setResultCallback(new ResultCallback<Status>() {
@Override
public void onResult(@NonNull Status status) {
updateUI(false);
}
});
}
private void handleResult(GoogleSignInResult result)
{
//on login success
if(result.isSuccess())
{
//fetching the user information
GoogleSignInAccount account=result.getSignInAccount();
String name=account.getDisplayName();
String email=account.getEmail();
//String image_url=account.getPhotoUrl().toString();
//setting the user information
txtName.setText(name);
txtEmail.setText(email);
//Glide.with(this).load(image_url).into(prof_pic);
updateUI(true);
}
else
{
updateUI(false);
}
}
private void updateUI(Boolean isLogin)
{
if(isLogin)
{
profile_google.setVisibility(View.VISIBLE);
signInButtonGoogle.setVisibility(View.GONE);
}
else
{
profile_google.setVisibility(View.GONE);
signInButtonGoogle.setVisibility(View.VISIBLE);
}
}
}
Google Login is perfectly working there are 2 errors
- I got error “Unhandled Exception LoginManager.onResultActivity” and code is directly jump to on error block after the login part and authorize part in facebook login.
2.I have written code for twitter but none of the click event is fired although I have written in the above code.
I guess that these two errors is in the below code but not sure
@Override
protected void onActivityResult(int requestCode,int resultCode,Intent data)
{
super.onActivityResult(requestCode,resultCode,data);
//TO DO:Error occurs of facebook and Twitter is not working
if (requestCode == request_code)
{
GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
handleResult(result);
}
else if(requestCode==TwitterAuthConfig.DEFAULT_AUTH_REQUEST_CODE)
{
// Pass the activity result to the login button.
signInButtonTwitter.onActivityResult(requestCode, resultCode, data);
}
else
{
FBcallbackManager.onActivityResult(requestCode,requestCode,data);
}
}
I got stucked in my project please someone help me Thank You
4
Answers
I have Solved the problem There are some changes I made
//Initialized Twitter Sdk fabric
//Here was mistake I made FBcallbackManager.onActivityResult(requestCode, requestCode, data);
//correct is
Try this way..
I was able to achieve with this implementation. Please try this: