tutorial studio sesion inicio iniciar español crear con boton app android facebook-login facebook-sdk-4.0

inicio - iniciar sesion con facebook android studio



Facebook SDK 4.0.1 Inicio de sesión sin botón de inicio de sesión (6)

Estoy intentando iniciar sesión sin usar el botón de inicio de sesión. Seguí el tutorial de Facebook pero no puedo hacerlo funcionar, siempre dame NullPointerException. Mi manifiesto

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

Mi actividad que uso para iniciar sesión en 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); } }

Mi gato de registro:

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)

Intenté todo pero terminé con NullPointerException ¡ Por favor, ayúdame!


1) Debes inicializar sdk antes de setContentView ()

2) Debes escribir Loginmanager.getInstance (). LogInWithReadPermission (.....) en un oyente de clic de botón


Intenta de esta manera:

  • Cree una aplicación de Android en el desarrollador de Facebook y configúrela en modo de desarrollo público.

  • Manifiesto:

    <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

  • Si quieres usar el fragmento para iniciar sesión de la forma correcta es:

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

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

Paso 3: - dentro de OnClickListener

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

Estaba usando getActivity() y debido a esto cada vez que algo parpadea, se muestra la vista Inicio de sesión de Facebook. Básicamente, en cambio, getActivity() tiene que usar FragmentClaseName.this . Espero que esto te ayude. Feliz codificacion !!!


Intente mover sus metadatos y actividad en el nodo de la aplicación en lugar del primer nodo de actividad.

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


Ok, no sé si ya habías resuelto tu problema pero aquí es cómo lo resolví

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


Su problema es que utiliza FacebookSdk.sdkInitialize(getApplicationContext()); después de setContentView(R.layout.activity_main); . Deberías usarlo antes de setContentView() . Un ejemplo completo de inicio de sesión en Facebook con código de ejemplo se puede encontrar here .


quizás olvidó que agregar este código como se ve en su 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" />