Android FacebookSDK Login - Accessing User Data in other Activities

I’ve built a simple Facebook Login Script using the FacebookSDK, and I’m getting the following Exception.

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.getfalling.falling44/com.getfalling.falling44.FallingActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.backendless.BackendlessUser.getEmail()' on a null object reference

I’ll start with my Login Script. When a user opens the app for the first time, this is the code that logs them in and adds their User Object to my database.

public class LoginActivity extends FragmentActivity {

    private CallbackManager callbackManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //initialize the facebook sdk
        FacebookSdk.sdkInitialize( this.getApplicationContext() );
        setContentView(R.layout.activity_login);

        //initialize backendless sdk
        Backendless.setUrl( Defaults.SERVER_URL );
        Backendless.initApp( this, Defaults.APPLICATION_ID, Defaults.SECRET_KEY, Defaults.VERSION );

        //set up a facebook callbackmanager to handle the login responses
        callbackManager = CallbackManager.Factory.create();

        //find the facebook_login_button
        LoginButton loginButton = (LoginButton) findViewById(R.id.facbook_login_button);
        loginButton.setOnClickListener( new View.OnClickListener()
        {
            public void onClick( View view )
            {
                Map<String, String> facebookFieldsMappings = new HashMap<>();
                facebookFieldsMappings.put( "email", "email" );
                facebookFieldsMappings.put( "first_name", "fb_first_name" );
                facebookFieldsMappings.put( "last_name", "fb_last_name" );
                facebookFieldsMappings.put( "gender", "fb_gender" );

                List<String> permissions = new ArrayList<>();
                permissions.add( "email" );
                permissions.add("public_profile");

                Backendless.UserService.loginWithFacebookSdk( LoginActivity.this, facebookFieldsMappings, permissions, callbackManager, new AsyncCallback<BackendlessUser>()
                {
                    @Override
                    public void handleResponse( BackendlessUser backendlessUser )
                    {
                        Intent intent = new Intent(LoginActivity.this, FallingActivity.class);
                        FallingActivity(intent);
                        LoginActivity.this.finish();
                    }

                    @Override
                    public void handleFault( BackendlessFault backendlessFault )
                    {
                        Toast toast = Toast.makeText( LoginActivity.this, backendlessFault.toString(), Toast.LENGTH_LONG );
                        toast.show();
                    }
                }, true );
            }
        } );
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult( requestCode, resultCode, data);
        callbackManager.onActivityResult(requestCode, resultCode, data);
    }
}


If the user closes the App and then reopens it, they are sent to a SplashActivity that checks to see whether or not the user is already logged in. If the user IS logged in, then they are sent to the “FallingActivity”, and if they are NOT logged in, they are sent to the “LoginActivity”.

public class SplashActivity extends AppCompatActivity {



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash);

        //initialize backendless sdk
        Backendless.setUrl( Defaults.SERVER_URL );
        Backendless.initApp( this, Defaults.APPLICATION_ID, Defaults.SECRET_KEY, Defaults.VERSION );

        //check to see if the user is already logged in.
        Backendless.UserService.isValidLogin(new AsyncCallback<Boolean>() {

            //this runs if isValidLogin() ran successfully
            @Override
            public void handleResponse(Boolean response) {

                //if the user is logged in, send them to the FallingActivity
                if (response) {

                    Intent intent = new Intent(SplashActivity.this, FallingActivity.class);
                    startActivity(intent);
                    SplashActivity.this.finish();


                    //if the user is not logged in, send them to the login page.
                } else {

                    Intent intent = new Intent(SplashActivity.this, LoginActivity.class);
                    startActivity(intent);
                    SplashActivity.this.finish();

                }

            }

            @Override
            public void handleFault(BackendlessFault fault) {

                Toast.makeText(SplashActivity.this, "Error " + fault.getMessage(), Toast.LENGTH_LONG).show();

            }
        });

    }


When the user is logged in and sent to the “FallingActivity” I’m am trying to do something simple like get the user’s email with the getEmail() method and I keep getting the exception above. Can anyone help me understand why? Here’s the “FallingActivity” code.

public class FallingActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_falling);

        //initialize backendless sdk
        Backendless.setUrl( Defaults.SERVER_URL );
        Backendless.initApp( this, Defaults.APPLICATION_ID, Defaults.SECRET_KEY, Defaults.VERSION );

        BackendlessUser user = Backendless.UserService.CurrentUser();
        String email = user.getEmail();

    }
}

I will add that I’ve been randomly getting the following error. It’s not consistent, but it keeps popping up every once in a while.

Not existing user token ... Relogin user to update your user token.

Thanks for any help!

Chris

IsValidLogin checks whether the user token is valid or not. If the user token is valid, it does not guarantee that BackendlessUserService.CurrentUser will return a non-null value. Which is the reason why you’re getting that NullPointerException.

See the section “Validating User Login” at the URL below for details on how to get the user object is the user token is valid:
https://backendless.com/documentation/users/android/users_login.htm

Regards,
Mark

Mark,

I’m really sorry. I somehow missed your reply. I’d like to thank you for the answer. I’ve got everything working now. Really enjoying BE.

Take care,

Chris

Hey Chris, no worries. Glad you got it working!

Cheers,
Mark