Through this post, I would like to present a sample project that by login with your Facebook account process, user can get the profile information responding in Graph API and show data to views.
DEMO VIDEO:
Register your app
All apps that use the Facebook SDK must be registered with Facebook. Log in to the Facebook Developers website and click Create a New App in the top right corner. With some simple steps, enter your new app name, select category, platform (Android), app's package name and launching Activity name..., make sure you remember the values you entered.
Key hashes field will be opened and we must fill it. Launch Terminal (in Mac, Linux) or Command Prompt (in Windows) and type this command:
keytool -exportcert -alias androiddebugkey -keystore ~/.android/debug.keystore | openssl sha1 -binary | openssl base64After enter password for Android debug.keystore (default is android), a key hash has been generated:
Copy and paste it to App register form, make sure Single Sign On is set to Yes and click the Save Changes button. Your app is now registered:
And our app dashboard will be like this:
Add Facebook SDK to Project
compile 'com.facebook.android:facebook-android-sdk:4.7.0'
Add the Application ID
Designing project layout
Programmatically coding
The SDK needs to be initialized before using any of its methods. You can do so by calling sdkInitialize() method and passing the application's context to it. Put this line in Activity onCreate():
FacebookSdk.sdkInitialize(getApplicationContext());After that, initialize an instance of CallbackManager using the CallbackManager.Factory.create() method:
callbackManager = CallbackManager.Factory.create();Now, set a call back to handle results of the login attempts, register it with CallbackManager instance above. Implements FacebookCallBack interface, we have ButtonLogin registerCallback:
btnLogin.registerCallback(callbackManager, new FacebookCallback<LoginResult>() { @Override public void onSuccess(LoginResult loginResult) { GraphRequest request = GraphRequest.newMeRequest( loginResult.getAccessToken(), new GraphRequest.GraphJSONObjectCallback() { @Override public void onCompleted(JSONObject object, GraphResponse response) { Log.v("Main", response.toString()); setProfileToView(object); } }); Bundle parameters = new Bundle(); parameters.putString("fields", "id,name,email,gender, birthday"); request.setParameters(parameters); request.executeAsync(); } @Override public void onCancel() { // App code } @Override public void onError(FacebookException exception) { Toast.makeText(MainActivity.this, "error to Login Facebook", Toast.LENGTH_SHORT).show(); } });The responding data is in JSONObject, parsing it based on key name and set to views:
private void setProfileToView(JSONObject jsonObject) { try { email.setText(jsonObject.getString("email")); gender.setText(jsonObject.getString("gender")); facebookName.setText(jsonObject.getString("name")); profilePictureView.setPresetSize(ProfilePictureView.NORMAL); profilePictureView.setProfileId(jsonObject.getString("id")); infoLayout.setVisibility(View.VISIBLE); } catch (JSONException e) { e.printStackTrace(); } }Overriding onActivityResult() to get data in CallbackManager:
@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); callbackManager.onActivityResult(requestCode, resultCode, data); }Finally, we have full code for main Activity:
package info.devexchanges.facebookintegration; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; 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 com.facebook.login.widget.ProfilePictureView; import org.json.JSONException; import org.json.JSONObject; import java.util.Arrays; public class MainActivity extends AppCompatActivity { private LoginButton btnLogin; private CallbackManager callbackManager; private ProfilePictureView profilePictureView; private LinearLayout infoLayout; private TextView email; private TextView gender; private TextView facebookName; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); FacebookSdk.sdkInitialize(getApplicationContext()); setContentView(R.layout.activity_main); btnLogin = (LoginButton)findViewById(R.id.login_button); email = (TextView)findViewById(R.id.email); facebookName = (TextView)findViewById(R.id.name); gender = (TextView)findViewById(R.id.gender); infoLayout = (LinearLayout)findViewById(R.id.layout_info); profilePictureView = (ProfilePictureView)findViewById(R.id.image); btnLogin.setReadPermissions(Arrays.asList("public_profile, email, user_birthday")); callbackManager = CallbackManager.Factory.create(); // Callback registration btnLogin.registerCallback(callbackManager, new FacebookCallback<LoginResult>() { @Override public void onSuccess(LoginResult loginResult) { GraphRequest request = GraphRequest.newMeRequest( loginResult.getAccessToken(), new GraphRequest.GraphJSONObjectCallback() { @Override public void onCompleted(JSONObject object, GraphResponse response) { Log.v("Main", response.toString()); setProfileToView(object); } }); Bundle parameters = new Bundle(); parameters.putString("fields", "id,name,email,gender, birthday"); request.setParameters(parameters); request.executeAsync(); } @Override public void onCancel() { } @Override public void onError(FacebookException exception) { Toast.makeText(MainActivity.this, "error to Login Facebook", Toast.LENGTH_SHORT).show(); } }); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); callbackManager.onActivityResult(requestCode, resultCode, data); } private void setProfileToView(JSONObject jsonObject) { try { email.setText(jsonObject.getString("email")); gender.setText(jsonObject.getString("gender")); facebookName.setText(jsonObject.getString("name")); profilePictureView.setPresetSize(ProfilePictureView.NORMAL); profilePictureView.setProfileId(jsonObject.getString("id")); infoLayout.setVisibility(View.VISIBLE); } catch (JSONException e) { e.printStackTrace(); } } }Our result after login Facebook and fetching data: