Facebook SDK 4.0.1 Login without login button

2019-01-21 20:02发布

问题:

I'm trying to log in without using login button. I followed facebook tutorial but i can not get it work, always give me NullPointerException. My Manifest:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.hema.testfcaebooksdk" >

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

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >

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

        <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" />

        <provider android:authorities="com.facebook.app.FacebookContentProvider****************"
            android:name="com.facebook.FacebookContentProvider"
            android:exported="true" />

        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

My Activity that i use it to login facebook:

public class MainActivity extends ActionBarActivity {

    CallbackManager callbackManager;
    LoginManager loginManager;

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

        FacebookSdk.sdkInitialize(getApplicationContext());

        callbackManager = CallbackManager.Factory.create();

        loginManager = LoginManager.getInstance();

        loginManager.registerCallback(callbackManager,
                new FacebookCallback<LoginResult>() {
                    @Override
                    public void onSuccess(LoginResult loginResult) {
                        // App code
                        Toast.makeText(getApplicationContext(), loginResult.getAccessToken().toString(), Toast.LENGTH_SHORT).show();

                    }

                    @Override
                    public void onCancel() {
                        // App code
                    }

                    @Override
                    public void onError(FacebookException exception) {
                        // App code
                    }
                });

        Collection<String> permissions = Arrays.asList("public_profile", "user_friends");

        loginManager.logInWithReadPermissions(this, permissions); // Null Pointer Exception here
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

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

My Log cat:

04-14 20:03:46.840    8075-8075/com.example.hema.testfacebooksdk E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.example.hema.testfacebooksdk, PID: 8075
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.hema.testfacebooksdk/com.example.hema.testfacebooksdk.MainActivity}: java.lang.NullPointerException
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2413)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2471)
            at android.app.ActivityThread.access$900(ActivityThread.java:175)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1308)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:146)
            at android.app.ActivityThread.main(ActivityThread.java:5602)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
            at dalvik.system.NativeStart.main(Native Method)
     Caused by: java.lang.NullPointerException
            at com.facebook.login.LoginManager.getLogger(LoginManager.java:391)
            at com.facebook.login.LoginManager.logCompleteLogin(LoginManager.java:414)
            at com.facebook.login.LoginManager.startLogin(LoginManager.java:384)
            at com.facebook.login.LoginManager.logInWithReadPermissions(LoginManager.java:262)
            at com.example.hema.testfacebooksdk.MainActivity.onCreate(MainActivity.java:59)
            at android.app.Activity.performCreate(Activity.java:5451)
            at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1093)
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2377)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2471)
            at android.app.ActivityThread.access$900(ActivityThread.java:175)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1308)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:146)
            at android.app.ActivityThread.main(ActivityThread.java:5602)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
            at dalvik.system.NativeStart.main(Native Method)

I tried every thing but ended up with NullPointerException Please help me!

回答1:

Ok I don't know if you had already solve your problem but here is how I solved it

 List<String> permissionNeeds= Arrays.asList("user_photos", "friends_photos", "email", "user_birthday", "user_friends");




 super.onCreate(savedInstanceState);
    FacebookSdk.sdkInitialize(getApplicationContext());
    mCallbackManager = CallbackManager.Factory.create();
    LoginManager.getInstance().logInWithReadPermissions(
            this,
           permissionNeeds);
    LoginManager.getInstance().registerCallback(mCallbackManager,
            new FacebookCallback<LoginResult>() {
                @Override
                public void onSuccess(LoginResult loginResults) {

                    GraphRequest request = GraphRequest.newMeRequest(
                            loginResults.getAccessToken(),
                            new GraphRequest.GraphJSONObjectCallback() {
                                @Override
                                public void onCompleted(
                                        JSONObject object,
                                        GraphResponse response) {
                                    // Application code
                                    Log.v("LoginActivity", response.toString());
                                }
                            });
                    Bundle parameters = new Bundle();
                    parameters.putString("fields", "id,name,email,gender, birthday");
                    request.setParameters(parameters);
                    request.executeAsync();

                }
                @Override
                public void onCancel() {

                    Log.e("dd","facebook login canceled");

                }


                @Override
                public void onError(FacebookException e) {



                    Log.e("dd", "facebook login failed error");

                }
            });


回答2:

Try moving your meta-data and activity under the application node rather than the first activity node.

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >

    <meta-data android:name="com.facebook.sdk.ApplicationId" android:value="@string/facebook_app_id"/>
    <activity
        android:name=".MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity android:name="com.facebook.FacebookActivity" />
</application>


回答3:

Your issue is that you use FacebookSdk.sdkInitialize(getApplicationContext()); after setContentView(R.layout.activity_main);. You should use it before setContentView(). A full facebook login example with sample code can be found here.



回答4:

Try in this way:

  • Create Android app on Facebook developer and set it to public instead development mode.

  • Manifest:

        <meta-data android:name="com.facebook.sdk.ApplicationId" android:value="@string/facebook_app_id"/>
    <activity
        android:name="com.facebook.FacebookActivity"
        android:configChanges="keyboard|keyboardHidden|screenLayout|screenSize|orientation"
        android:label="@string/app_name"/>
    
  • Strings.xml

    XXXXXXXXXXXXXX

  • If you want to use fragment for Login the proper way is:

Step 1:

    CallbackManager mCallbackManager;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //@Deprecated for latest version, without this line working fine. 
        //FacebookSdk.sdkInitialize(getActivity().getApplicationContext());


        mCallbackManager = CallbackManager.Factory.create();

        LoginManager.getInstance().registerCallback(mCallbackManager,
            new FacebookCallback<LoginResult>() {
                @Override
                public void onSuccess(LoginResult loginResult) {
                    // App code
                    Log.e("Success", "Login");
                    Bundle parameters = new Bundle();
                    parameters.putString("fields", "id, first_name, last_name ,email, gender, birthday");

                    GraphRequest gr = GraphRequest.newMeRequest(
                            loginResult.getAccessToken(), new GraphRequest.GraphJSONObjectCallback() {
                                @Override
                                public void onCompleted(JSONObject json, GraphResponse response) {
                                    if (response.getError() != null) {
                                        // handle error
                                        System.out.println("ERROR "+response.getError().toString());
                                    } else {
                                        //System.out.println("Success");
                                        try {

                                            String jsonresult = String.valueOf(json);
                                            System.out.println("JSON Result"+jsonresult);
                                            String resp = String.valueOf(response.getJSONObject());
                                            System.out.println("JSON resp "+resp);


                                        } catch (JSONException e) {
                                            e.printStackTrace();
                                        }
                                    }
                                }

                            });
                    gr.setParameters(parameters);
                    gr.executeAsync();

                }

                @Override
                public void onCancel() {
                    // App code
                    Log.e("onCancel", "Login");
                }

                @Override
                public void onError(FacebookException onError) {
                    // App code
                    Log.e("onError", "Login "+onError.getMessage());
                }
            });
    }

Step 2:

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            mCallbackManager.onActivityResult(requestCode, resultCode, data);
        }
    }

Step 3: - inside OnClickListener

LoginManager.getInstance().logInWithReadPermissions(YourFragment.this, Arrays.asList("public_profile"));

I was using getActivity() and because of this every time something flashes instead showing Facebook Login view. Basically instead getActivity() have to use FragmentClaseName.this. I hope this will help u. Happy coding!!!



回答5:

maybe your forgot that add this code as bellowed in your AndroidManifest.xml

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


回答6:

1) u should initialize sdk before setContentView()

2) u should write Loginmanager.getInstance().logInWithReadPermission(.....) on some button click listener