Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

facebook login null pointer exception android

I searched a lot through stackoverflow but I couldn't find an answer that resolves my issue. Hence I am posting this.

I have a sample Android App in which I'm trying to use facebook Login. Here are the steps that I followed:

Environment: Android studio Android SDK version : 22 Facebook SDK : 4.0

Followed the steps to install FB APK on the emulator, generated the Developer hash key and updated it in app-> settings. My android manifest has these code

<uses-permission android:name="android.permission.INTERNET"/>

<activity android:name="com.facebook.FacebookActivity"
        android:configChanges="keyboard|keyboardHidden|screenLayout|screenSize|orientation"
        android:theme="@android:style/Theme.Translucent.NoTitleBar" android:label="@string/app_name" />

<meta-data android:name="com.facebook.sdk.ApplicationId" android:value="@string/facebook_app_id"/>

In my activity_main.xml layout file, I have this piece of code

<com.facebook.login.widget.LoginButton
    android:id="@+id/fblogin_button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center_horizontal"
    android:layout_marginTop="30dp"
    android:layout_marginBottom="30dp" />

And finally in my main Activity I have this

public class MainActivity extends Activity {
LoginButton loginButton;
CallbackManager callbackManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    FacebookSdk.sdkInitialize(getApplicationContext());
    callbackManager = CallbackManager.Factory.create();
    loginButton = (LoginButton) findViewById(R.id.fblogin_button);
    loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
        @Override
        public void onSuccess(LoginResult loginResult) {
            Toast.makeText(getApplicationContext(),"Fb Login Success",Toast.LENGTH_LONG);
        }

        @Override
        public void onCancel() {
            Toast.makeText(getApplicationContext(),"Fb on cancel",Toast.LENGTH_LONG);
        }

        @Override
        public void onError(FacebookException e) {
            Toast.makeText(getApplicationContext(),"Fb Login Error",Toast.LENGTH_LONG);
        }
    });
    setContentView(R.layout.activity_main);

}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data){
    super.onActivityResult(requestCode, resultCode, data);
    Log.d("Inside Fb login","on Activiry result");
    callbackManager.onActivityResult(requestCode, resultCode, data);
}}

I am getting a null pointer exception as shown below

 java.lang.RuntimeException: Unable to start activity componentInfo{PROJECT.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.facebook.login.widget.LoginButton.registerCallback(com.facebook.CallbackManager, com.facebook.FacebookCallback)' on a null object reference
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
        at android.app.ActivityThread.access$800(ActivityThread.java:144)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:135)
        at android.app.ActivityThread.main(ActivityThread.java:5221)
        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:899)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)

What am I missing here ?

like image 416
user2752910 Avatar asked Apr 05 '15 05:04

user2752910


2 Answers

Looks like you're getting a NullPointerException because you're calling findViewById() before you call setContentView(), so loginButton is null when you call loginButton.registerCallback().

Just move the call to setContentView() to the top:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    FacebookSdk.sdkInitialize(getApplicationContext());

    setContentView(R.layout.activity_main); //Moved up here to resolve NPE

    callbackManager = CallbackManager.Factory.create();
    loginButton = (LoginButton) findViewById(R.id.fblogin_button);
    loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
        @Override
        public void onSuccess(LoginResult loginResult) {
            Toast.makeText(getApplicationContext(),"Fb Login Success",Toast.LENGTH_LONG);
        }

        @Override
        public void onCancel() {
            Toast.makeText(getApplicationContext(),"Fb on cancel",Toast.LENGTH_LONG);
        }

        @Override
        public void onError(FacebookException e) {
            Toast.makeText(getApplicationContext(),"Fb Login Error",Toast.LENGTH_LONG);
        }
    });

}
like image 195
Daniel Nugent Avatar answered Nov 12 '22 05:11

Daniel Nugent


The crash seems to be related to the applicationId we are setting in the AndoridMenifest.xml file. As i figured out that when facebook sdk is tying to create the LoginFramment then ApplicationId is comming as null.Here is onCreate method of com.facebook.login.LoginFragment class

public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if(savedInstanceState != null) {
            this.loginClient = (LoginClient)savedInstanceState.getParcelable("loginClient");
            this.loginClient.setFragment(this);
        } else {
            this.loginClient = new LoginClient(this);
        }

        this.loginClient.setOnCompletedListener(new OnCompletedListener() {
            public void onCompleted(Result outcome) {
                LoginFragment.this.onLoginClientCompleted(outcome);
            }
        });
        FragmentActivity activity = this.getActivity();
        if(activity != null) {
            this.initializeCallingPackage(activity);
            if(activity.getIntent() != null) {
                //the applicationId in this.request object is null 
                this.request = (Request)activity.getIntent().getParcelableExtra("request");

            }

        }
    }

As pointed out by the varoius post the applicationId is coming null because the string resource app_id is not being parsed correctly by android. https://github.com/jamesward/AndroidStringBug

I solved this probelm by setting the applicationId manually after initializing the facebook sdk as given below in onCreate method.

FacebookSdk.sdkInitialize(getApplicationContext());
FacebookSdk.setApplicationId(getResources().getString(R.string.app_id));
mFacebookCallbackManager = CallbackManager.Factory.create();
like image 27
anj Avatar answered Nov 12 '22 06:11

anj