繁体   English   中英

使用Facebook Android App登录

[英]Login With Facebook Android App

我正在尝试在我的Android应用上使用Facebook登录。 我正在使用以下教程http://code.tutsplus.com/tutorials/quick-tip-add-facebook-login-to-your-android-app--cms-23837 我的代码中没有错误,但是当我尝试访问使用Facebook登录按钮所在的活动时,出现运行时错误。 它无法加载活动。

Logcat

04-06 14:57:05.024 8470-8470/com.example.martin.ivebeenthere E/AndroidRuntime: FATAL EXCEPTION: main
                                                                               java.lang.ExceptionInInitializerError
                                                                                   at java.lang.reflect.Constructor.constructNative(Native Method)
                                                                                   at java.lang.reflect.Constructor.newInstance(Constructor.java:417)
                                                                                   at android.view.LayoutInflater.createView(LayoutInflater.java:587)
                                                                                   at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:687)
                                                                                   at android.view.LayoutInflater.rInflate(LayoutInflater.java:746)
                                                                                   at android.view.LayoutInflater.parseInclude(LayoutInflater.java:830)
                                                                                   at android.view.LayoutInflater.rInflate(LayoutInflater.java:736)
                                                                                   at android.view.LayoutInflater.inflate(LayoutInflater.java:489)
                                                                                   at android.view.LayoutInflater.inflate(LayoutInflater.java:396)
                                                                                   at android.view.LayoutInflater.inflate(LayoutInflater.java:352)
                                                                                   at android.support.v7.app.AppCompatDelegateImplV7.setContentView(AppCompatDelegateImplV7.java:256)
                                                                                   at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:109)
                                                                                   at com.example.martin.ivebeenthere.Login.onCreate(Login.java:34)
                                                                                   at android.app.Activity.performCreate(Activity.java:5047)
                                                                                   at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1094)
                                                                                   at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2056)
                                                                                   at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2117)
                                                                                   at android.app.ActivityThread.access$700(ActivityThread.java:134)
                                                                                   at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1218)
                                                                                   at android.os.Handler.dispatchMessage(Handler.java:99)
                                                                                   at android.os.Looper.loop(Looper.java:137)
                                                                                   at android.app.ActivityThread.main(ActivityThread.java:4867)
                                                                                   at java.lang.reflect.Method.invokeNative(Native Method)
                                                                                   at java.lang.reflect.Method.invoke(Method.java:511)
                                                                                   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1007)
                                                                                   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:774)
                                                                                   at dalvik.system.NativeStart.main(Native Method)
                                                                                Caused by: null
                                                                                   at com.facebook.internal.Validate.sdkInitialized(Validate.java:99)
                                                                                   at com.facebook.FacebookSdk.getCallbackRequestCodeOffset(FacebookSdk.java:735)
                                                                                   at com.facebook.internal.CallbackManagerImpl$RequestCodeOffset.toRequestCode(CallbackManagerImpl.java:109)
                                                                                   at com.facebook.login.widget.LoginButton.<clinit>(LoginButton.java:58)
                                                                                   at java.lang.reflect.Constructor.constructNative(Native Method) 
                                                                                   at java.lang.reflect.Constructor.newInstance(Constructor.java:417) 
                                                                                   at android.view.LayoutInflater.createView(LayoutInflater.java:587) 
                                                                                   at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:687) 
                                                                                   at android.view.LayoutInflater.rInflate(LayoutInflater.java:746) 
                                                                                   at android.view.LayoutInflater.parseInclude(LayoutInflater.java:830) 
                                                                                   at android.view.LayoutInflater.rInflate(LayoutInflater.java:736) 
                                                                                   at android.view.LayoutInflater.inflate(LayoutInflater.java:489) 
                                                                                   at android.view.LayoutInflater.inflate(LayoutInflater.java:396) 
                                                                                   at android.view.LayoutInflater.inflate(LayoutInflater.java:352) 
                                                                                   at android.support.v7.app.AppCompatDelegateImplV7.setContentView(AppCompatDelegateImplV7.java:256) 
                                                                                   at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:109) 
                                                                                   at com.example.martin.ivebeenthere.Login.onCreate(Login.java:34) 
                                                                                   at android.app.Activity.performCreate(Activity.java:5047) 
                                                                                   at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1094) 
                                                                                   at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2056) 
                                                                                   at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2117) 
                                                                                   at android.app.ActivityThread.access$700(ActivityThread.java:134) 
                                                                                   at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1218) 
                                                                                   at android.os.Handler.dispatchMessage(Handler.java:99) 
                                                                                   at android.os.Looper.loop(Looper.java:137) 
                                                                                   at android.app.ActivityThread.main(ActivityThread.java:4867) 
                                                                                   at java.lang.reflect.Method.invokeNative(Native Method) 
                                                                                   at java.lang.reflect.Method.invoke(Method.java:511) 
                                                                                   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1007) 
                                                                                   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:774) 
                                                                                   at dalvik.system.NativeStart.main(Native Method) 

Login.java

package com.example.martin.ivebeenthere;

import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.TextView;

import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.FacebookSdk;
import com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;
import com.microsoft.windowsazure.mobileservices.MobileServiceClient;
import com.microsoft.windowsazure.mobileservices.http.ServiceFilterResponse;
import com.microsoft.windowsazure.mobileservices.table.TableOperationCallback;

import java.net.MalformedURLException;

public class Login extends AppCompatActivity {

    private TextView info;
    private LoginButton loginButton;

    private CallbackManager callbackManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FacebookSdk.sdkInitialize(getApplicationContext());
        callbackManager = CallbackManager.Factory.create();

        setContentView(R.layout.activity_login);
        info = (TextView)findViewById(R.id.info);
        loginButton = (LoginButton)findViewById(R.id.login_button);

        loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
            @Override
            public void onSuccess(LoginResult loginResult) {
                info.setText(
                        "User ID: "
                                + loginResult.getAccessToken().getUserId()
                                + "\n" +
                                "Auth Token: "
                                + loginResult.getAccessToken().getToken()
                );
            }

            @Override
            public void onCancel() {
                info.setText("Login attempt canceled.");
            }

            @Override
            public void onError(FacebookException e) {
                info.setText("Login attempt failed.");
            }
        });
    }

    public void onClickbtnFeed(View view)
    {
        startActivity(new Intent(Login.this, Feed.class));
    }

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

}

AndroidManifest.xml

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

    <!--
         The ACCESS_COARSE/FINE_LOCATION permissions are not required to use
         Google Maps Android API v2, but you must specify either coarse or fine
         location permissions for the 'MyLocation' functionality. 
    -->
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.INTERNET" />


    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity
            android:name=".Home"
            android:label="@string/app_name"
            android:theme="@style/AppTheme.NoActionBar">
            <intent-filter>
                <action android:name="com.example.splash.CLEARSCREEN" />

                <category android:name="android.intent.category.DEFAULT" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".Login"
            android:label="@string/title_activity_login"
            android:theme="@style/AppTheme.NoActionBar" />
        <activity
            android:name=".Register"
            android:label="@string/title_activity_register"
            android:theme="@style/AppTheme.NoActionBar" />
        <!--
             The API key for Google Maps-based APIs is defined as a string resource.
             (See the file "res/values/google_maps_api.xml").
             Note that the API key is linked to the encryption key used to sign the APK.
             You need a different API key for each encryption key, including the release key that is used to
             sign the APK for publishing.
             You can define the keys for the debug and release targets in src/debug/ and src/release/. 
        -->
        <meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value="@string/google_maps_key" />

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

        <activity
            android:name=".Map"
            android:label="@string/title_activity_map" />
        <activity android:name=".Splash">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".Feed"
            android:label="@string/title_activity_feed"
            android:theme="@style/AppTheme.NoActionBar" />
        <activity
            android:name=".CheckinInfo"
            android:label="@string/title_activity_checkin_info"
            android:theme="@style/AppTheme.NoActionBar" />
        <activity
            android:name=".Account"
            android:label="@string/title_activity_account"
            android:theme="@style/AppTheme.NoActionBar" />
        <activity
            android:name=".EditAccount"
            android:label="@string/title_activity_edit_account"
            android:theme="@style/AppTheme.NoActionBar" />
        <activity
            android:name=".Checkin"
            android:label="@string/title_activity_checkin"
            android:theme="@style/AppTheme.NoActionBar" />
    </application>

</manifest>

activity_login.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context="com.example.martin.ivebeenthere.Login">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

    </android.support.design.widget.AppBarLayout>

    <include layout="@layout/content_login" />

</android.support.design.widget.CoordinatorLayout>

content_login.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.example.martin.ivebeenthere.Login"
    tools:showIn="@layout/activity_login">

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/imageView"
        android:src="@drawable/logo"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_marginBottom="276dp" />

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:inputType="textPersonName"
        android:ems="10"
        android:hint="Username"
        android:id="@+id/editText"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true" />

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:inputType="textPassword"
        android:ems="10"
        android:hint="Password"
        android:id="@+id/editText2"
        android:layout_below="@+id/editText"
        android:layout_centerHorizontal="true" />

    <Button
        android:layout_width="200dp"
        android:layout_height="wrap_content"
        android:text="Login"
        android:id="@+id/button3"
        android:layout_below="@+id/editText2"
        android:layout_centerHorizontal="true"
        android:onClick="onClickbtnFeed"/>

    <!--<Button
        android:layout_width="200dp"
        android:layout_height="wrap_content"
        android:text="Login With Facebook"
        android:id="@+id/button4"
        android:background="#3b5998"
        android:textColor="#ffffff"
        android:layout_below="@+id/button3"
        android:layout_alignLeft="@+id/button3"
        android:layout_alignStart="@+id/button3"
        android:layout_marginTop="25dp" />-->

    <com.facebook.login.widget.LoginButton
        android:id="@+id/login_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/info"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:textSize="18sp"
        />

</RelativeLayout>

用下面的代码更新。

activity_login.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:facebook="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">


    <com.facebook.widget.LoginButton
        android:id="@+id/fb_login_button"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="5dp"
        facebook:confirm_logout="false"
        facebook:fetch_user_info="true" />

    <TextView
        android:id="@+id/username"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_margin="10dp"
        android:textSize="16sp" />

</LinearLayout>

Login.java

import java.util.Arrays;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.widget.TextView;

import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.UiLifecycleHelper;
import com.facebook.model.GraphUser;
import com.facebook.widget.LoginButton;
import com.facebook.widget.LoginButton.UserInfoChangedCallback;

public class Login extends FragmentActivity {

    private LoginButton loginBtn;
    private TextView username;
    private UiLifecycleHelper uiHelper;

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

        uiHelper = new UiLifecycleHelper(this, statusCallback);
        uiHelper.onCreate(savedInstanceState);

        setContentView(R.layout.activity_login);

        username = (TextView) findViewById(R.id.username);
        loginBtn = (LoginButton) findViewById(R.id.fb_login_button);
        loginBtn.setReadPermissions(Arrays.asList("email"));
        loginBtn.setUserInfoChangedCallback(new UserInfoChangedCallback() {
            @Override
            public void onUserInfoFetched(GraphUser user) {
                if (user != null) {
                    username.setText("You are currently logged in as " + user.getName());
                } else {
                    username.setText("You are not logged in.");
                }
            }
        });
    }

    private Session.StatusCallback statusCallback = new Session.StatusCallback() {
        @Override
        public void call(Session session, SessionState state,
                Exception exception) {
            if (state.isOpened()) {
                Log.d("Login", "Facebook session opened.");
            } else if (state.isClosed()) {
                Log.d("Login", "Facebook session closed.");
            }
        }
    };

    @Override
    public void onResume() {
        super.onResume();
        uiHelper.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
        uiHelper.onPause();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        uiHelper.onDestroy();
    }

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

    @Override
    public void onSaveInstanceState(Bundle savedState) {
        super.onSaveInstanceState(savedState);
        uiHelper.onSaveInstanceState(savedState);
    }
}

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.martin.ivebeenthere"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="19" />
    <uses-permission android:name="android.permission.INTERNET"/>

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".Login"
            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.LoginActivity"
            android:theme="@android:style/Theme.Translucent.NoTitleBar" />
        <meta-data android:name="com.facebook.sdk.ApplicationId"
            android:value="@string/APP_ID" />
    </application>

</manifest>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM