Facebook SDK 4.0.1无需登录按钮登录

时间:2015-04-14 18:19:28

标签: android facebook-login facebook-sdk-4.0

我正在尝试不使用登录按钮登录。 我跟着facebook教程,但我不能让它工作,总是给我NullPointerException。 我的清单:

<?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>

我用它来登录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);
    }
}

我的日志猫:

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)

我尝试了所有的东西,但结果是 NullPointerException 请帮帮我!

6 个答案:

答案 0 :(得分:21)

好的,我不知道你是否已经解决了问题,但这就是我解决问题的方法

 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");

                }
            });

答案 1 :(得分:6)

尝试在应用程序节点而不是第一个活动节点下移动元数据和活动。

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

答案 2 :(得分:5)

您的问题是您在FacebookSdk.sdkInitialize(getApplicationContext());之后使用setContentView(R.layout.activity_main);。您应该在之前使用 setContentView()。可以找到带有示例代码的完整 facebook登录示例 here

答案 3 :(得分:4)

尝试这种方式:

  • 在Facebook开发者上创建Android应用并将其设置为公开而非开发模式。

  • 清单:

        <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

  • 如果你想使用片段登录,正确的方法是:

第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());
                }
            });
    }

第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);
        }
    }

第3步: - 在OnClickListener中

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

我正在使用getActivity()因此,每当有人闪烁而不是显示Facebook登录视图时。基本上,getActivity()必须使用FragmentClaseName.this。我希望这会对你有所帮助。快乐的编码!!!

答案 4 :(得分:3)

也许你忘了在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" />

答案 5 :(得分:0)

1)你应该在setContentView()

之前初始化sdk

2)你应该在某个按钮点击监听器上写Loginmanager.getInstance()。logInWithReadPermission(.....)