Get Facebook Username on MainActivity from 3rd Activity - android

I have 3 Activity's.
MainActivity has the side_nav_menu (Later I want the circle picture).
FacebookActivity has the facebook SDK and and the Fragment.
BlankFragment has all the facebook login with a txtView that gets the current user name.
Whats the best way to get the user name, picture and email. So I can show it on side_nav_menu.
How this callbackManager works?
FacebookActivity extends to Fragment
private BlankFragment mainFragment;
private LoginButton loginButton;
private CallbackManager callbackManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_facebook);
FacebookSdk.sdkInitialize(getApplicationContext());
callbackManager = CallbackManager.Factory.create();
loginButton = (LoginButton) findViewById(R.id.login_button);
printHashkey();
if (savedInstanceState == null) {
// Add the fragment on initial activity setup
mainFragment = new BlankFragment();
getSupportFragmentManager().beginTransaction()
.add(android.R.id.content, mainFragment).commit();
} else {
// Or set the fragment from restored state info
mainFragment = (BlankFragment) getSupportFragmentManager()
.findFragmentById(android.R.id.content);
}
}
public void printHashkey(){
try {
PackageInfo info = getPackageManager().getPackageInfo(
"BLA BLA BLA BLA BLA BLA",
PackageManager.GET_SIGNATURES);
for (Signature signature : info.signatures) {
MessageDigest md = MessageDigest.getInstance("SHA");
md.update(signature.toByteArray());
Log.d("KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT));
}
} catch (PackageManager.NameNotFoundException e) {
} catch (NoSuchAlgorithmException e) {
}
}
And the Fragment
private CallbackManager callbackManager;
private TextView textView;
private ImageView imv;
private AccessTokenTracker accessTokenTracker;
private ProfileTracker profileTracker;
private FacebookCallback<LoginResult> callback = new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
AccessToken accessToken = loginResult.getAccessToken();
Profile profile = Profile.getCurrentProfile();
displayMessage(profile);
}
#Override
public void onCancel() {
}
#Override
public void onError(FacebookException e) {
}
};
public BlankFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getActivity().getApplicationContext());
callbackManager = CallbackManager.Factory.create();
accessTokenTracker= new AccessTokenTracker() {
#Override
protected void onCurrentAccessTokenChanged(AccessToken oldToken, AccessToken newToken) {
}
};
profileTracker = new ProfileTracker() {
#Override
protected void onCurrentProfileChanged(Profile oldProfile, Profile newProfile) {
displayMessage(newProfile);
}
};
accessTokenTracker.startTracking();
profileTracker.startTracking();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_blank, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
LoginButton loginButton = (LoginButton) view.findViewById(R.id.login_button);
textView = (TextView) view.findViewById(R.id.textView);
loginButton.setReadPermissions("public_profile");
loginButton.setFragment(this);
loginButton.registerCallback(callbackManager, callback);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}
private void displayMessage(Profile profile){
TextView textView = (TextView) getActivity().findViewById(R.id.textView);
ProfilePictureView profileImage = (ProfilePictureView) getActivity().findViewById(R.id.profilePicture);
if(profile != null){
textView.setText(profile.getName());
profileImage.setProfileId(profile.getId());
}
}
#Override
public void onStop() {
super.onStop();
accessTokenTracker.stopTracking();
profileTracker.stopTracking();
}
#Override
public void onResume() {
super.onResume();
Profile profile = Profile.getCurrentProfile();
displayMessage(profile);
}
How can I get user Name, and Picture. Send to MainActivity on the side_nav_menu?
This part here show the pic and the name on the fragment.
private void displayMessage(Profile profile){
TextView textView = (TextView) getActivity().findViewById(R.id.textView);
ProfilePictureView profileImage = (ProfilePictureView) getActivity().findViewById(R.id.profilePicture);
profileImage.setProfileId(profile.getId());
if(profile != null){
textView.setText(profile.getName());
profileImage.setProfileId(profile.getId());
}
}

You should probably save it in SharedPreferences (for image just save path so you can load it from sdcard, or just save image url)

Related

Using Shared Preferences with Log in with Facebook

I'm trying to save user details after logging in (with Facebook). I'm able to fetch data but can't save it. I'm using SharedPreferences but can't save it. Data is not lost when I go on some other activity, but when I click back button and re-open this activity, all data is lost. Here is my code:
Profilee.java
public class Profilee extends Fragment {
String email1, birthday1, gender1;
ImageView imageView;
static int itis = 1;
TextView texty;
LoginButton button;
LinearLayout userinput;
private CallbackManager callbackManager;
private TextView textView;
SharedPreferences pref;
private TextView email, birthday, gende;
private AccessTokenTracker accessTokenTracker;
private ProfileTracker profileTracker;
private FacebookCallback<LoginResult> callback = new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
AccessToken accessToken = loginResult.getAccessToken();
Profile profile = Profile.getCurrentProfile();
GraphRequest graphrequest = GraphRequest.newMeRequest(loginResult.getAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
JSONObject jsonObject = response.getJSONObject();
if (jsonObject != null) {
try {
email1 = jsonObject.getString("email");
gender1 = jsonObject.getString("gender");
birthday1 = jsonObject.getString("birthday");
} catch (JSONException e) {
e.printStackTrace();
}
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "email, gender, birthday");
graphrequest.setParameters(parameters);
graphrequest.executeAsync();
AppEventsLogger.activateApp(getContext());
}
#Override
public void onCancel() {
}
#Override
public void onError(FacebookException e) {
}
};
public Profilee() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getActivity().getApplicationContext());
callbackManager = CallbackManager.Factory.create();
Toast.makeText(getContext(), "Create", Toast.LENGTH_SHORT).show();
pref = getContext().getSharedPreferences("", getContext().MODE_PRIVATE);
pref.getString("name", "asdfgh");
pref.getString("email", "qwerty");
pref.getString("gender", "zxcvb");
accessTokenTracker = new AccessTokenTracker() {
#Override
protected void onCurrentAccessTokenChanged(AccessToken oldToken, AccessToken newToken) {
}
};
profileTracker = new ProfileTracker() {
#Override
protected void onCurrentProfileChanged(Profile oldProfile, Profile newProfile) {
}
};
accessTokenTracker.startTracking();
profileTracker.startTracking();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_profilee, container, false);
button = (LoginButton) v.findViewById(R.id.login_button);
TextView button12 = (TextView) v.findViewById(R.id.edit);
button12.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(getContext(), PrifileEdit.class);
i.putExtra("st", email1);
startActivity(i);
}
});
texty = (TextView) v.findViewById(R.id.emo);
imageView = (ImageView) v.findViewById(R.id.asd);
userinput = (LinearLayout) v.findViewById(R.id.userdetail);
int unicode = 0x1F60E;
String emoji = getEmijoByUnicode(unicode);
String text = "We will never post on your wall without permission ";
texty.setText(text + emoji);
Toast.makeText(getContext(), "CreateView", Toast.LENGTH_SHORT).show();
return v;
}
public String getEmijoByUnicode(int unicode) {
return new String(Character.toChars(unicode));
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
LoginButton loginButton = (LoginButton) view.findViewById(R.id.login_button);
textView = (TextView) view.findViewById(R.id.textView);
email = (TextView) view.findViewById(R.id.emailid);
gende = (TextView) view.findViewById(R.id.gender);
birthday = (TextView) view.findViewById(R.id.birth);
loginButton.setReadPermissions("email");
loginButton.setFragment(this);
loginButton.registerCallback(callbackManager, callback);
Toast.makeText(getContext(), "ViewCreate", Toast.LENGTH_SHORT).show();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
onResume();
}
}, 2000);
}
public void displayMessage(final Profile profile) {
if (itis == 1) {
if (profile != null) {
textView.setText(profile.getName());
email.setText(email1);
gende.setText(gender1);
birthday.setText(birthday1);
button.setVisibility(View.GONE);
texty.setVisibility(View.GONE);
userinput.setVisibility(View.VISIBLE);
pref = getContext().getSharedPreferences("", getContext().MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putString("name", String.valueOf(textView));
editor.putString("email", String.valueOf(email));
editor.putString("gender", String.valueOf(gende));
editor.commit();
}
}
}
#Override
public void onStart() {
super.onStart();
Toast.makeText(getContext(), "Start", Toast.LENGTH_SHORT).show();
}
#Override
public void onStop() {
super.onStop();
accessTokenTracker.stopTracking();
profileTracker.stopTracking();
}
#Override
public void onResume() {
super.onResume();
Profile profile = Profile.getCurrentProfile();
displayMessage(profile);
AppEventsLogger.activateApp(getContext());
}
}
I think this problem is because of displayMessage() method .
when you reopen this Activity , onResume(); method will call , and then displayMessage() .
in displayMessage() you are setting sharedprefrecens values again , and this work cause you lost previous data from this sharedprefrecens.
for solve this problem you must cut onResume codes inside onCreate method
You aren't persisting the data in SharedPreferences correctly. getText() will retrieve the text that is currently displayed in the TextView, allowing you to store it into SharedPreferences.
editor.putString("name", String.valueOf(textView)); // wrong
editor.putString("name", textView.getText().toString()); // right
You can then retrieve the value and display it on screen by calling setText().
String myEmail = pref.getString("email", "qwerty");
textView.setText(myEmail);

Set Facebook Name in a dialog

When I'm connected by the facebook login button, I launch a custom dialog (in the onSuccess) and I want to write in this dialog the name of the person connected. It works when I do it in the layout called in onCreate(I make appear the name after connexion). But it doesn't work when I want to write this in the layout called by the dialog after the connexion (but it's the same activity).
Here is my code :
private CallbackManager mCallbackManager2;
private ProfileTracker mProfileTracker2;
private LoginButton loginbutton2;
final Context context = this;
private ProfilePictureView fAvatar2;
private TextView fName2;
private FacebookCallback<LoginResult> mCallback2 = new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
AccessToken accessToken = loginResult.getAccessToken();
Profile profile = Profile.getCurrentProfile();
/*
LAUNCH DIALOG ABOUT FACEBOOK CONNEXION
*/
// custom dialog
final Dialog dialogFacebookConnexion = new Dialog(context);
dialogFacebookConnexion.setContentView(R.layout.dialog_facebook_connect);
Button dialogButton = (Button) dialogFacebookConnexion.findViewById(R.id.dialogOk);
dialogButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialogFacebookConnexion.dismiss();
Intent intentmainpage = new Intent(InfoAccountActivity.this, MainPageActivity.class);
startActivity(intentmainpage);
}
});
dialogFacebookConnexion.setCanceledOnTouchOutside(false);
int dialogHeight = (int) getResources().getDimension(R.dimen.dialog_height);
int dialogWidth = (int) getResources().getDimension(R.dimen.dialog_width);
dialogFacebookConnexion.getWindow().setLayout(dialogWidth, dialogHeight);
dialogFacebookConnexion.show();
}
#Override
public void onCancel() {
}
#Override
public void onError(FacebookException e) {
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getApplicationContext());
setContentView(R.layout.activity_info_account);
mCallbackManager2 = CallbackManager.Factory.create();
loginbutton2 = (LoginButton) findViewById(R.id.login_button2);
loginbutton2.setBackgroundResource(R.drawable.facebookconnexion);
loginbutton2.setReadPermissions("user_friends");
loginbutton2.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);
loginbutton2.registerCallback(mCallbackManager2, mCallback2);
fName2 = (TextView) findViewById(R.id.facebookName2);
fAvatar2 = (ProfilePictureView) findViewById(R.id.facebook_avatar2);
ProfileTracker profileTracker = new ProfileTracker() {
#Override
protected void onCurrentProfileChanged(Profile oldProfile, Profile newProfile) {
OnProfileChanged(newProfile);
}
};
}
private void OnProfileChanged (Profile profile) {
if (profile != null) {
try {
fName2.setText(profile.getName());
fAvatar2.setProfileId(profile.getId());
} catch (Exception ex) {
}
} else {
}
}
#Override
public void onResume() {
super.onResume();
Profile profile = Profile.getCurrentProfile();
OnProfileChanged(profile);
}
#Override
public void onStop() {
super.onStop();
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
mCallbackManager2.onActivityResult(requestCode, resultCode, data);
}
Is it a problem with private or protected ? An information can't be access by the dialog?
In any activity, you can use the following facebook code from their SDK once you have signed into Facebook:
Profile.getCurrentProfile().getName()
Did you try using the Request.newMeRequest using your active open session? It is easy to capture the logged user's profile afterwards.
GraphRequest rq = GraphRequest.newMeRequest(session, new Request.GraphUserCallback() {
#Override
public void onCompleted(final GraphUser user, Response response) { ...
...
rq.executeAndWait();
You can retrieve the user's name by user.getName() in the onCompleted method and use it anywhere.

FaceBook SDK for android login not working

so i created a simple facebook login app following the exact instructions from this video: https://www.youtube.com/watch?v=myWu-q8Q2NA&list=PLonJJ3BVjZW4E1wIRZvuXhbFRGWB1grmh
anyways i am able to sign in but unlike the video, when I sign in, I appear back at the login page, the login button does not change to the logout button,
I click the login button, enter my login details, hit send, then a message says: You have already authorized "LoginExample (app name)". Then I appear back at the login with facebook button.
and on a similar note, I am trying to get a TextView to display a "Welcome", however it does not work, it only works when I do ' android:text="Welcome" '.
Below is my code in a fragment, I do setContentView(activity_fragment); in MainActivity. Again, the Login button appears but the TextView does not.
What is going wrong?
public class MainFragment extends Fragment {
public TextView mTextDetails;
private AccessTokenTracker mtokentracker;
private ProfileTracker mprofiletracker;
CallbackManager mCallBackManager;
private FacebookCallback<LoginResult> mCallBack = new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
AccessToken accessToken = loginResult.getAccessToken();
//TextView mTextDetails = (TextView)getView().findViewById(R.id.textView);
Profile profile = Profile.getCurrentProfile();
if (profile != null){
mTextDetails.setText("Welcome " + profile.getName());
}
//setContentView(R.layout.activity_main);
}
#Override
public void onCancel() {
}
#Override
public void onError(FacebookException e) {
}
};
public MainFragment() {
//TextView mTextDetails = (TextView) getView().findViewById(R.id.textView);
//mTextDetails.setText("Welcome");
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getActivity().getApplicationContext());
mCallBackManager = CallbackManager.Factory.create();
AccessTokenTracker tracker = new AccessTokenTracker() {
#Override
protected void onCurrentAccessTokenChanged(AccessToken old, AccessToken niw) {
Profile profile = Profile.getCurrentProfile();
if (profile != null){
mTextDetails.setText("welcome " + profile.getName());
}
}
};
ProfileTracker profileTracker = new ProfileTracker() {
#Override
protected void onCurrentProfileChanged(Profile old, Profile niw) {
}
};
mtokentracker.startTracking();
mprofiletracker.startTracking();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_main, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
LoginButton loginButton = (LoginButton)view.findViewById(R.id.login_button);
//loginButton.setReadPermissions("user_friends");
loginButton.setFragment(this);
loginButton.registerCallback(mCallBackManager, mCallBack);
TextView mTextDetails = (TextView)getView().findViewById(R.id.textView);
mTextDetails.setText("Welcome");
}
#Override
public void onResume() {
super.onResume();
Profile profile = Profile.getCurrentProfile();
if (profile != null){
mTextDetails.setText("Welcome " + profile.getName());
}
}
#Override
public void onStop() {
super.onStop();
mtokentracker.stopTracking();
mprofiletracker.stopTracking();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
mCallBackManager.onActivityResult(requestCode,resultCode,data);
}
}

I dont know how using LOGOUT in FACEBOOK API ANDROID

I have the follow code, but I don't know which is the method that execute when I push in Logout. I only need know which is the method that execute in logout. Or another solution? Thanks for all :) dasasa
public class FBLoginFragment extends Fragment implements IServiceCallback {
private CallbackManager callbackManager;
private TextView textView;
private AccessTokenTracker accessTokenTracker;
private ProfileTracker mProfileTracker;
private FacebookCallback<LoginResult> callback = new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
mProfileTracker = new ProfileTracker() {
#Override
protected void onCurrentProfileChanged(Profile profile, Profile profile2) {
mProfileTracker.stopTracking();
}
};
mProfileTracker.startTracking();
AccessToken accessToken = loginResult.getAccessToken();
Profile profile = Profile.getCurrentProfile();
displayMessage(profile);
}
#Override
public void onCancel() {
}
#Override
public void onError(FacebookException e) {
}
};
public FBLoginFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getActivity().getApplicationContext());
callbackManager = CallbackManager.Factory.create();
accessTokenTracker= new AccessTokenTracker() {
#Override
protected void onCurrentAccessTokenChanged(AccessToken oldToken, AccessToken newToken) {
}
};
mProfileTracker = new ProfileTracker() {
#Override
protected void onCurrentProfileChanged(Profile oldProfile, Profile newProfile) {
displayMessage(newProfile);
if(newProfile != null){
register(newProfile);
}
}
};
accessTokenTracker.startTracking();
mProfileTracker.startTracking();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.facebook_fragment, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
LoginButton loginButton = (LoginButton) view.findViewById(R.id.login_button);
textView = (TextView) view.findViewById(R.id.textView);
loginButton.setReadPermissions(Arrays.asList("public_profile", "user_friends"));
loginButton.setFragment(this);
loginButton.registerCallback(callbackManager, callback);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (callbackManager.onActivityResult(requestCode, resultCode, data))
return;
}
private void displayMessage(Profile profile){
if(profile != null){
textView.setText(profile.getName());
}
}
private void register(Profile profile){
if(profile != null){
new Register(this).run(profile);
}
}
#Override
public void onStop() {
super.onStop();
accessTokenTracker.stopTracking();
mProfileTracker.stopTracking();
}
#Override
public void onResume() {
super.onResume();
Profile profile = Profile.getCurrentProfile();
displayMessage(profile);
}
#Override
public void onSuccess(JSONObject obj, String method) throws JSONException {
User user = new User(obj);
user.insert();
//Intent intent = new Intent(getActivity(), Update.class);
//startActivity(intent);
}
#Override
public void onError(String error) {
}
You need to get the active Session, then then call closeAndClearTokenInformation().
You can get the currently active session via Session.getActiveSession().
Try this method to logout from facebook programmatically in android
/**
* Logout From Facebook
*/
public static void callFacebookLogout(Context context) {
Session session = Session.getActiveSession();
if (session != null) {
if (!session.isClosed()) {
session.closeAndClearTokenInformation();
//clear your preferences if saved
}
} else {
session = new Session(context);
Session.setActiveSession(session);
session.closeAndClearTokenInformation();
//clear your preferences if saved
}
}

save info about facebook user to use in another Activity

I'm working on project to my university, and I would like to know how save some information about facebook user like name, e-mail and picture. Then how I can use this information in another Activity? As you can see my code i can show info in the same activity that i logged but i cant have in another activity
MainActivity.java
public class MainActivity extends ActionBarActivity {
public static final int INDEX_SIMPLE_LOGIN = 0;
public static final int INDEX_CUSTOM_LOGIN = 1;
private static final String STATE_SELECTED_FRAGMENT_INDEX = "selected_fragment_index";
public static final String FRAGMENT_TAG = "fragment_tag";
private FragmentManager mFragmentManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mFragmentManager = getSupportFragmentManager();
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
#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;
}
if (id == R.id.action_simple_login) {
toggleFragment(INDEX_SIMPLE_LOGIN);
return true;
}
if (id == R.id.action_custom_login) {
toggleFragment(INDEX_CUSTOM_LOGIN);
return true;
}
return super.onOptionsItemSelected(item);
}
private void toggleFragment(int index) {
Fragment fragment = mFragmentManager.findFragmentByTag(FRAGMENT_TAG);
FragmentTransaction transaction = mFragmentManager.beginTransaction();
switch (index) {
case INDEX_SIMPLE_LOGIN:
transaction.replace(android.R.id.content, new FragmentSimpleLoginButton(), FRAGMENT_TAG);
break;
case INDEX_CUSTOM_LOGIN:
transaction.replace(android.R.id.content, new FragmentCustomLoginButton(), FRAGMENT_TAG);
break;
}
transaction.commit();
}
}
MyApplication.java
public class MyApplication extends Application {
#Override
public void onCreate() {
super.onCreate();
FacebookSdk.sdkInitialize(getApplicationContext());
}
/**
* Call this method inside onCreate once to get your hash key
*/
public void printKeyHash() {
try {
PackageInfo info = getPackageManager().getPackageInfo("vivz.slidenerd.facebookv40helloworld", PackageManager.GET_SIGNATURES);
for (Signature signature : info.signatures) {
MessageDigest md = MessageDigest.getInstance("SHA");
md.update(signature.toByteArray());
Log.e("VIVZ", Base64.encodeToString(md.digest(), Base64.DEFAULT));
}
} catch (PackageManager.NameNotFoundException e) {
} catch (NoSuchAlgorithmException e) {
}
}
}
FragmentSimpleLoginButton.java
public class FragmentSimpleLoginButton extends Fragment {
private TextView mTextDetails;
private CallbackManager mCallbackManager;
private AccessTokenTracker mTokenTracker;
private ProfileTracker mProfileTracker;
private FacebookCallback<LoginResult> mFacebookCallback = new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
Log.d("VIVZ", "onSuccess");
AccessToken accessToken = loginResult.getAccessToken();
Profile profile = Profile.getCurrentProfile();
mTextDetails.setText(constructWelcomeMessage(profile));
}
#Override
public void onCancel() {
Log.d("VIVZ", "onCancel");
}
#Override
public void onError(FacebookException e) {
Log.d("VIVZ", "onError " + e);
}
};
public FragmentSimpleLoginButton() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mCallbackManager = CallbackManager.Factory.create();
setupTokenTracker();
setupProfileTracker();
mTokenTracker.startTracking();
mProfileTracker.startTracking();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_simple_login_button, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
setupTextDetails(view);
setupLoginButton(view);
}
#Override
public void onResume() {
super.onResume();
Profile profile = Profile.getCurrentProfile();
mTextDetails.setText(constructWelcomeMessage(profile));
}
#Override
public void onStop() {
super.onStop();
mTokenTracker.stopTracking();
mProfileTracker.stopTracking();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
mCallbackManager.onActivityResult(requestCode, resultCode, data);
}
private void setupTextDetails(View view) {
mTextDetails = (TextView) view.findViewById(R.id.text_details);
}
private void setupTokenTracker() {
mTokenTracker = new AccessTokenTracker() {
#Override
protected void onCurrentAccessTokenChanged(AccessToken oldAccessToken, AccessToken currentAccessToken) {
Log.d("VIVZ", "" + currentAccessToken);
}
};
}
private void setupProfileTracker() {
mProfileTracker = new ProfileTracker() {
#Override
protected void onCurrentProfileChanged(Profile oldProfile, Profile currentProfile) {
Log.d("VIVZ", "" + currentProfile);
mTextDetails.setText(constructWelcomeMessage(currentProfile));
}
};
}
private void setupLoginButton(View view) {
LoginButton mButtonLogin = (LoginButton) view.findViewById(R.id.login_button);
mButtonLogin.setFragment(this);
mButtonLogin.setReadPermissions("user_friends");
mButtonLogin.registerCallback(mCallbackManager, mFacebookCallback);
}
private String constructWelcomeMessage(Profile profile) {
StringBuffer stringBuffer = new StringBuffer();
if (profile != null) {
stringBuffer.append("Welcome " + profile.getName());
}
return stringBuffer.toString();
}
if you want to send the info to the next activity you can add it to the intent with a bundle.
ACTIVITY:
Intent i=new Intent(Activity.this, SecontActivity.class);
i.putExtra("email", email);
startActivity(i);
SecontActivity:
Intent intent = getIntent();
String email = intent.getStringExtra("email");
if you want the info in all your activities then save it in SharedPreferences
Activity:
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("email", email);
editor.commit();
SecondActivity:
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
String email = sharedPref.getString(email, defaultValue);
Store the info such as name, imageurl and other profile details in a database or (sharedpreferences as indicated here) for access across different activities. This information can be fetched at any stage once saved throughout the history of the app unless the data from the app is cleared.
I would go for the database as it would more structure and can potentially provide multi-user support, incase you want to implement profile switching in your app.

Categories

Resources