Elgallati Noreddine Elgallati Noreddine - 17 days ago 5
Android Question

why setReadPermissions is rendering NullPointerException in Facebook login in android studio

i am trying to integrate Facebook login into my app but when i try to enter to the activity when my button is.

I followed this tutorial: http://alvarez.tech/login-facebook-en-android/

my activity is like:

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
_THIS=this;
setContentView(R.layout.connexion_layout);

if(savedInstanceState!= null) return;

FrameLayout frameLayout = (FrameLayout)findViewById(R.id.fragment_container);

connexion0 = new connexion0Fragment();
connexion1 = new connexion1Fragment();

changeFragment(0);
connexionViaFacebook();

}

public void connexionViaFacebook(){
callbackManager = CallbackManager.Factory.create();

loginButton = (LoginButton) findViewById(R.id.loginButton);

loginButton.setReadPermissions(Arrays.asList("email"));

loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
@Override
public void onSuccess(LoginResult loginResult) {
goMainScreen();
}

@Override
public void onCancel() {
Toast.makeText(getApplicationContext(), R.string.cancel_login, Toast.LENGTH_SHORT).show();
}

@Override
public void onError(FacebookException error) {
Toast.makeText(getApplicationContext(), R.string.error_login, Toast.LENGTH_SHORT).show();
}
});
}


the error is:

java.lang.NullPointerException: Attempt to invoke virtual method 'void com.facebook.login.widget.LoginButton.setReadPermissions(java.util.List)' on a null object reference

Answer

I think you have forgot to add the facebook initialization code in the oncreate() method of your main activity. FacebookSdk.sdkInitialize(getApplicationContext());

In your reference link, the initialization part has been done in the class extending Application.

Reference:

  1. facebook android integration - Getting started
  2. Setting up fb integration - with pictures
Comments