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.
Related
I have added Facebook Login code inside fragment. Everything works fine,i can login into my app but when i change fragment or reopen app after login every data are gone i.e email,name,birthday.it doesn't shows any data.so, what should i do to save those data.
code
public class ProfileFragment extends Fragment{
ProfileTracker profileTracker;
RelativeLayout fbbg;
RelativeLayout rl;
LoginButton btnLogin;
CallbackManager callbackManager;
AccessTokenTracker accessTokenTracker;
CircleImageView profilePicture;
TextView email;
TextView gender;
TextView facebookName;
TextView birthday;
SharedPreferences pref;
public static final List<String> mPermissions = new ArrayList<String>() {{
add("public_profile");
add("email");
add("user_photos");
add("user_birthday");
}};
#Nullable
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstantState) {
View view = inflater.inflate(R.layout.profile, container, false);
FacebookSdk.sdkInitialize(getActivity());
btnLogin = (LoginButton)view.findViewById(R.id.view);
email = (TextView)view.findViewById(R.id.un2);
facebookName = (TextView)view.findViewById(R.id.username);
birthday = (TextView)view.findViewById(R.id.bd2);
gender = (TextView)view.findViewById(R.id.gnd2);
profilePicture = (CircleImageView)view.findViewById(R.id.profile_image);
rl = (RelativeLayout) view.findViewById(R.id.rl);
fbbg = (RelativeLayout) view.findViewById(R.id.relativeLayout);
callbackManager = CallbackManager.Factory.create();
btnLogin.setReadPermissions(mPermissions);
btnLogin.setFragment(this);
btnLogin.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
AccessToken accessToken = loginResult.getAccessToken();
Profile profile = Profile.getCurrentProfile();
GraphRequest request = GraphRequest.newMeRequest(
loginResult.getAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
Log.d("JSON", ""+response.getJSONObject().toString());
try {
fbbg.setVisibility(View.GONE);
rl.setVisibility(View.VISIBLE);
email.setText(object.getString("email"));
gender.setText(object.getString("gender"));
facebookName.setText(object.getString("name"));
birthday.setText(object.getString("birthday"));
Glide.with(getActivity())
.load("https://graph.facebook.com/" + object.getString("id") + "/picture?type=large")
.into(profilePicture);
pref = getActivity().getSharedPreferences("", getActivity().MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putString("name", String.valueOf(facebookName));
editor.putString("email", String.valueOf(email));
editor.putString("gender", String.valueOf(gender));
editor.putString("birthday", String.valueOf(birthday));
editor.commit();
} catch (JSONException e) {
e.printStackTrace();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,email,gender,birthday");
request.setParameters(parameters);
request.executeAsync();
accessTokenTracker = new AccessTokenTracker() {
#Override
protected void onCurrentAccessTokenChanged(AccessToken oldAccessToken,
AccessToken currentAccessToken) {
if (currentAccessToken == null) {
facebookName.setText("");
email.setText("");
gender.setText("");
birthday.setText("");
profilePicture.setImageResource(R.drawable.user);
}
}
};
profileTracker = new ProfileTracker() {
#Override
protected void onCurrentProfileChanged(Profile oldProfile, Profile newProfile) {
}
};
accessTokenTracker.startTracking();
profileTracker.startTracking();
}
#Override
public void onCancel() {
Toast.makeText(getActivity(),"Cancled to Login Facebook", Toast.LENGTH_SHORT).show();
}
#Override
public void onError(FacebookException exception) {
Toast.makeText(getActivity(),"Error to Login Facebook", Toast.LENGTH_SHORT).show();
}
}); return view;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
pref = getActivity().getSharedPreferences("", getActivity().MODE_PRIVATE);
pref.getString("name", "asdfgh");
pref.getString("email", "qwerty");
pref.getString("gender", "zxcvb");
pref.getString("birthday", "kdhfaj");
}
#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);
}
}
After login pic
After reopening app pic
#Override
public void onResume() {
super.onResume();
Profile profile = Profile.getCurrentProfile();
AppEventsLogger.activateApp(getActivity());
}
No need to do this.
whenever you are resuming the fragment then that time it is creating the fresh instance of your facebook profile thats why data loss is happening.
on resume just reload fragment dont create new instace.
whenever you get data from facebook api immediately store it to shared preferences. after that you can fetch that data whenever you require.
public UpdateFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
v = inflater.inflate(R.layout.fragment_updates, container, false);
listView = (ListView) v.findViewById(R.id.listView);
// define your xml resources here
return v;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setRetainInstance(true);
loadUpdates();
}
private void loadUpdates() {
// api call
}
}
Try to embed your code into this fragment lifecycle. it will surely work.
There is no need to add onResume()
just do your stuff in loadUpdates(); method.
I have modified your code wrt SharedPreference.
You can try that.
pref = getActivity().getSharedPreferences("GIVE SOME name TO FILE", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putString("name", object.getString("name"));
editor.putString("email", object.getString("email"));
editor.putString("gender", object.getString("gender"));
editor.putString("birthday", object.getString("birthday"));
editor.apply();
Replace above code with your existing code, once you successfully get user profile information from FB
I think your problem is your SharedPreferences was initialized with an Activity. To avoid your data is lost when the Activity destroyed, you should use ApplicationContext().
I made a separated class with SharedPreference like this:
public class SessionManager {
// Shared Preferences reference
public SharedPreferences pref;
// Editor reference for Shared preferences
private Editor editor;
#SuppressWarnings("unused")
private Context context;
int PRIVATE_MODE = 0;
public static final String PREFER_NAME = "login";
public static final String KEY_USER_NAME = "username";
public SessionManager(Context context) {
this.context = context;
pref = context.getSharedPreferences(PREFER_NAME, PRIVATE_MODE);
editor = pref.edit();
}
public String getUserName() {
return pref.getString(KEY_USER_NAME, "");
}
public void setUserName(String userName) {
editor.putString(KEY_USER_NAME, userName);
editor.commit();
}
In your Fragment, initializing SharedPreferences with:
sessionManager = new SessionManager(getActivity.getApplicationContext());
saving your data:
session.setUserName(object.getString("name"));
Retrieving data at later times by called:
String userName = session.getUserName();
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);
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)
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
}
}
I'm trying to get working a native android project that uses Worklight form based authentication. I'm already able to authenticate the user through the native APIs. The problem appears when I change between activities (intents). Once the user enters his information and submits the form, it is authenticated but the worklight server connection is lost.
This is the code:
MainActivity.java
public class MainActivity extends Activity {
private Button buttonConnect = null;
private Button buttonInvoke = null;
private static TextView textView = null;
private static MainActivity _this;
private MyChallengeHadler challengeHandler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
_this = this;
buttonConnect = (Button)findViewById(R.id.buttonConnect);
buttonInvoke = (Button)findViewById(R.id.buttonInvoke);
textView = (TextView)findViewById(R.id.textView);
final WLClient client = WLClient.createInstance(this);
buttonConnect.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
updateTextView("Connecting...");
client.connect(new MyConnectListener());
challengeHandler = new MyChallengeHadler(MainActivity.this, "BasicAuth");
client.registerChallengeHandler(challengeHandler);
}
});
buttonInvoke.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
updateTextView("Invoking procedure...");
String adapterName = "RSSReader";
String procedureName = "getStoriesFiltered";
WLProcedureInvocationData invocationData =
new WLProcedureInvocationData(adapterName, procedureName);
Object[] parameters = new Object[] {"world"};
invocationData.setParameters(parameters);
WLRequestOptions options = new WLRequestOptions();
options.setTimeout(30000);
WLClient client = WLClient.getInstance();
client.invokeProcedure(invocationData, new MyInvokeListener(), options);
}
});
}
public static void updateTextView(final String str){
Runnable run = new Runnable() {
public void run() {
textView.setText(str);
}
};
_this.runOnUiThread(run);
}
}
LoginActivity.java
public class LoginActivity extends Activity {
private Button Submit = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
Submit = (Button)findViewById(R.id.button1);
Submit.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
MyChallengeHadler challengeHandler = new MyChallengeHadler(LoginActivity.this, "BasicAuth");
challengeHandler.submitLogin(0, "maria", "maria", false);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.login, 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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
MyChallengeHadler.java
public class MyChallengeHadler extends ChallengeHandler {
private WLResponse cachedResponse;
private final Activity parentActivity;
public MyChallengeHadler(final Activity a, String realm) {
super(realm);
this.parentActivity =a;
// TODO Auto-generated constructor stub
}
#Override
public void onFailure(WLFailResponse arg0) {
// TODO Auto-generated method stub
}
#Override
public void onSuccess(WLResponse arg0) {
// TODO Auto-generated method stub
}
#Override
public boolean isCustomResponse(WLResponse response) {
if (response == null || response.getResponseText() == null
|| response.getResponseText().indexOf("j_security_check") == -1) {
return false;
}
return true;
}
#Override
public void handleChallenge(WLResponse response){
if (!isCustomResponse(response)) {
submitSuccess(response);
} else {
cachedResponse = response;
Intent login = new Intent(parentActivity, LoginActivity.class);
parentActivity.startActivityForResult(login, 1);
}
}
public void submitLogin(int resultCode, String userName, String password, boolean back){
HashMap<String, String> params = new HashMap<String, String>();
params.put("j_username", userName);
params.put("j_password", password);
submitLoginForm("/j_security_check", params, null, 0, "post");
Intent login = new Intent(parentActivity, MainActivity.class);
parentActivity.startActivityForResult(login, 1);
}
}
I have already solved my code's problem. I was using wrongly android's intents. This is the new version of the code:
LoginActivity.java
public class LoginActivity extends Activity {
private Button Submit;
private Intent result;
public static final String Back = "back";
public static final String UserNameExtra = "username";
public static final String PasswordExtra = "password";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
Submit = (Button)findViewById(R.id.button1);
result = new Intent();
Submit.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
result.putExtra(UserNameExtra, "maria");
result.putExtra(PasswordExtra, "maria");
result.putExtra(Back, false);
setResult(RESULT_OK, result);
finish();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.login, 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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
MainActivity.java
public class MainActivity extends Activity {
private Button buttonConnect = null;
private Button buttonInvoke = null;
private static TextView textView = null;
private static MainActivity _this;
private MyChallengeHadler challengeHandler;
private String realm = "BasicAuth";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
_this = this;
buttonConnect = (Button)findViewById(R.id.buttonConnect);
buttonInvoke = (Button)findViewById(R.id.buttonInvoke);
textView = (TextView)findViewById(R.id.textView);
final WLClient client = WLClient.createInstance(this);
buttonConnect.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
updateTextView("Connecting...");
client.connect(new MyConnectListener());
challengeHandler = new MyChallengeHadler(MainActivity.this, realm);
client.registerChallengeHandler(challengeHandler);
}
});
buttonInvoke.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
updateTextView("Invoking procedure...");
String adapterName = "SOAPAdapter";
String procedureName = "getStories";
WLProcedureInvocationData invocationData =
new WLProcedureInvocationData(adapterName, procedureName);
//Object[] parameters = new Object[] {"world"};
//invocationData.setParameters(parameters);
WLRequestOptions options = new WLRequestOptions();
options.setTimeout(30000);
WLClient client = WLClient.getInstance();
client.invokeProcedure(invocationData, new MyResponseListener(), options);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
boolean back = data.getBooleanExtra(LoginActivity.Back, true);
String username = data.getStringExtra(LoginActivity.UserNameExtra);
String password = data.getStringExtra(LoginActivity.PasswordExtra);
challengeHandler.submitLogin(resultCode, username, password, back);
}
public static void updateTextView(final String str){
Runnable run = new Runnable() {
public void run() {
textView.setText(str);
}
};
_this.runOnUiThread(run);
}
}
MyChallengeHadler.java
public class MyChallengeHadler extends ChallengeHandler {
private WLResponse cachedResponse;
private final Activity parentActivity;
public MyChallengeHadler(final Activity a, String realm) {
super(realm);
parentActivity =a;
// TODO Auto-generated constructor stub
}
#Override
public void onFailure(WLFailResponse arg0) {
// TODO Auto-generated method stub
}
#Override
public void onSuccess(WLResponse arg0) {
// TODO Auto-generated method stub
}
#Override
public boolean isCustomResponse(WLResponse response) {
if (response == null || response.getResponseText() == null
|| response.getResponseText().indexOf("j_security_check") == -1) {
return false;
}
return true;
}
#Override
public void handleChallenge(WLResponse response){
if (!isCustomResponse(response)) {
submitSuccess(response);
} else {
cachedResponse = response;
Intent login = new Intent(parentActivity, LoginActivity.class);
parentActivity.startActivityForResult(login, 1);
}
}
public void submitLogin(int resultCode, String userName, String password, boolean back){
if (resultCode != Activity.RESULT_OK || back) {
submitFailure(cachedResponse);
} else {
HashMap<String, String> params = new HashMap<String, String>();
params.put("j_username", userName);
params.put("j_password", password);
submitLoginForm("/j_security_check", params, null, 0, "post");
}
}
}