Search code examples
androidfacebookfacebook-android-sdk

Basic Facebook API Login not working


I am new to Android Development and Facebook SDK. I am just trying to link Facebook loginButton with my application. When I click on button it ask me for login details and permissions and then it comes back successfully to app. But again at the same moment when I click on that button it ask me to login again.

    package com.example.pranavjain.pranavapp;

import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;

import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.FacebookSdk;
import com.facebook.GraphRequest;
import com.facebook.GraphResponse;
import com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;

import org.json.JSONObject;


public class MainActivity extends ActionBarActivity {

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





    }





   public void onCreateView(
            LayoutInflater inflater,
            ViewGroup container,
            Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.activity_main, container, false);

        LoginButton loginButton = (LoginButton) view.findViewById(R.id.login_button);
        loginButton.setReadPermissions("user_friends");
        // If using in a fragment

        // Other app specific specialization

        // Callback registration

       CallbackManager callbackManager = CallbackManager.Factory.create();

       loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
           @Override
           public void onSuccess(LoginResult loginResult) {
               // App code


               GraphRequest request = GraphRequest.newMeRequest(
                       loginResult.getAccessToken(), new GraphRequest.GraphJSONObjectCallback() {
                           @Override
                           public void onCompleted(
                                   JSONObject object1,
                                   GraphResponse response) {
                               // Application code
                               Log.d("tagpranav", object1.toString());
                           }
                       });
               Bundle parameters = new Bundle();
               parameters.putString("fields", "id,name,link");
               request.setParameters(parameters);
               request.executeAsync();

           }

           @Override

           public void onCancel() {
               // App code
               Log.v("LoginActivity", "cancel");
           }

           @Override
           public void onError(FacebookException exception) {
               // App code
               Log.v("LoginActivity", exception.getCause().toString());
           }
       });





   }




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

I have already checked that Hash key is right. Nothing gets logged under "tagpranav" or "LoginActivity".


Solution

  • Make sure to add following in your onCreate() method as first line:

    FacebookSdk.sdkInitialize(getApplicationContext());  
    

    Consider moving your code in onCreate() method of your MainActivity. Below I'd mentioned working sample.

    public class MainActivity extends ActionBarActivity {
    
    CallbackManager callbackManager;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
            LoginButton loginButton = (LoginButton)  findViewById(R.id.login_button);
    
            loginButton.setReadPermissions(PERMISSIONS_ARRAY);
    
            callbackManager = CallbackManager.Factory.create();
            // Callback registration
            loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
                @Override
                public void onSuccess(LoginResult loginResult) {
                    Log.i(TAG, "Logged in...");
                    GraphRequest.newMeRequest(AccessToken.getCurrentAccessToken(),
                            new GraphRequest.GraphJSONObjectCallback() {
                                @Override
                                public void onCompleted(JSONObject user, GraphResponse response) {
                                    try {
                                        if (user != null) {
                                            Log.e(TAG, "UserID : " + user.getString("id"));
    
                                        }
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                }
                            }).executeAsync(); 
                }
    
                @Override
                public void onCancel() {
                    // Login canceled
    
                }
    
                @Override
                public void onError(FacebookException exception) {
                    // Login error
                }
            });
        }
     }
    

    In above code PERMISSIONS_ARRAY is array having all your permissions.

    One thing you are missing is, make callbackManager class variable and add following method in your MainActivity.

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);         
        callbackManager.onActivityResult(requestCode, resultCode, data);
        Log.i(TAG, "OnActivityResult...:" + resultCode);
    }
    

    EDIT-1:

    A class variable is something defined in a class and out side of method, so that all methods of class can access it. In your code you have defined callbackManager inside a method, so you can't access it in onActivityResult. I have made relevant changes in my answer.