I want facebook profile information in my code. This code works Log.e("in try start", "tryyyyyyyyy"); until here but after that not even single log is executed.
private Facebook facebook;
private AsyncFacebookRunner mAsyncRunner;
String FILENAME = "AndroidSSO_data";
private SharedPreferences mPrefs;
public void loginToFacebook() {
// mPrefs = getPreferences(SharedPreferences.);
// String access_token = mPrefs.getString("access_token", null);
//long expires = mPrefs.getLong("access_expires", 0);
// if (access_token != null) {
// facebook.setAccessToken(access_token);
// }
// if (expires != 0) {
// facebook.setAccessExpires(expires);
// }
if (!facebook.isSessionValid()) {
facebook.authorize(getActivity(),
new String[] { "email", "publish_actions" },
new DialogListener() {
#Override
public void onCancel() {
// Function to handle cancel event
}
#Override
public void onComplete(Bundle values) {
// Function to handle complete event
// Edit Preferences and update facebook acess_token
Toast.makeText(getActivity(), "hiiiiii", Toast.LENGTH_SHORT).show();
//mPrefs=getSharedPreferences("data", getActivity().MODE_PRIVATE);
SharedPreferences.Editor editor = mPrefs.edit();
editor.putString("access_token",
facebook.getAccessToken());
editor.putLong("access_expires",
facebook.getAccessExpires());
editor.commit();
Log.e("getProfileInformation entry", "getProfileInformation");
getProfileInformation();
}
#Override
public void onFacebookError(FacebookError e) {
// TODO Auto-generated method stub
}
#Override
public void onError(DialogError e) {
// TODO Auto-generated method stub
}
});
}
}
public void getProfileInformation() {
Toast.makeText(getActivity(), "byeeeeeee", Toast.LENGTH_SHORT).show();
Log.e("getProfileInformation start", "getProfileInformation");
mAsyncRunner.request("me", new RequestListener() {
#Override
public void onComplete(String response, Object state) {
Log.d("Profile", response);
String json = response;
try {
Log.e("in try start", "tryyyyyyyyy");
JSONObject profile = new JSONObject(json);
// getting name of the user
Log.d("profile", ""+profile);
fb_name = profile.getString("name");
// getting email of the user
fb_email = profile.getString("email");
Log.d("fb_name", "naem"+fb_name+"emial"+fb_email);
//fb_login=true;
// fb_Image = getUserPic(fb_email);
// LoginFuction();
} catch (JSONException e) {
e.printStackTrace();
Log.e("catchhhhhh", ""+e.getMessage());
}
}
public Bitmap getUserPic(String userID) {
String imageURL;
Bitmap bitmap = null;
Log.d("TAG", "Loading Picture");
imageURL = "http://graph.facebook.com/"+userID+"/picture?type=small";
try {
bitmap = BitmapFactory.decodeStream((InputStream)new URL(imageURL).getContent());
} catch (Exception e) {
Log.d("TAG", "Loading Picture FAILED");
e.printStackTrace();
}
return bitmap;
}
#Override
public void onIOException(IOException e, Object state) {
}
#Override
public void onFileNotFoundException(FileNotFoundException e,
Object state) {
}
#Override
public void onMalformedURLException(MalformedURLException e,
Object state) {
}
#Override
public void onFacebookError(FacebookError e, Object state) {
}
});
}
This code does not give me any name or emailId.
-Hello Abhishek !
- I have tried using Facebook sdk4.+ and i am getting profile info perfectly.
-Firs of all add below code into your oncreate method before setcontentview
FacebookSdk.sdkInitialize(getApplicationContext());
-Then Create you Callbackmanager using below code:-
callbackManager = CallbackManager.Factory.create();
-Add Permissions using below code:-
permission.add("publish_actions");
-Below code is used for Login
LoginManager.getInstance().registerCallback(callbackManager,
new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(final LoginResult loginResult) {
// App code
GraphRequest request = GraphRequest.newMeRequest(
act,
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(
JSONObject object,
GraphResponse response) {
// Application code
if (!TextUtils.isEmpty(object.toString())) {
try {
JSONObject jresJsonObject = new JSONObject(object.toString());
String id = "", name = "", gender = "";
if (!(jresJsonObject.isNull("id"))) {
id = jresJsonObject.getString("id");
}
if (!(jresJsonObject.isNull("gender"))) {
gender = jresJsonObject.getString("gender");
if (gender.equals("male")) {
gender = "0";
} else {
gender = "1";
}
}
if (!(jresJsonObject.isNull("name"))) {
name = jresJsonObject.getString("name");
}
} catch (Exception e) {
}
}
Log.e("graphrequest", response.toString());
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,gender,link");
request.setParameters(parameters);
request.executeAndWait();
}
#Override
public void onCancel() {
Log.i("", "Access Token:: " + "loginResult.getAccessToken()");
}
#Override
public void onError(FacebookException exception) {
Log.i("", "Access Token:: " + "loginResult.getAccessToken()");
}
});
LoginManager.getInstance().logInWithPublishPermissions(this, permission);
-Last but no least add below code in your OnActivitResult
callbackManager.onActivityResult(requestCode, resultCode, data);
NOTE:- This is using latest Facebook sdk
-Please inform me if it is not usefull or you are still getting issue in this.
Related
Heres the method im using and it returns the id and name no problems.
// Private method to handle Facebook login and callback
private void onFblogin() {
callbackmanager = CallbackManager.Factory.create();
// Set permissions
LoginManager.getInstance().logInWithReadPermissions(this, Arrays.asList("email", "public_profile"));
LoginManager.getInstance().registerCallback(callbackmanager,
new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
System.out.println("Success");
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");
} else {
System.out.println("Success");
try {
String jsonresult = String.valueOf(json);
System.out.println("JSON Result" + jsonresult);
// String str_email = json.getString("email");
String str_email = json.getString("email");
String str_name = json.getString("name");
String str_id = json.getString("id");
//
// Save your info
settings = getSharedPreferences("login_details", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("name", str_name);
editor.putString("email", str_email);
editor.commit();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}).executeAsync();
Intent openNewActivity = new Intent(getApplicationContext(), MainActivity.class);
startActivity(openNewActivity);
}
#Override
public void onCancel() {
Log.d("TAG_CANCEL", "On cancel");
}
#Override
public void onError(FacebookException error) {
Log.d("TAG_ERROR", error.toString());
}
});
}
The problem i have is that email doesnt return.
Ive tested the permissions with another app that can get my email when i sign in so permissions seem fine. Im assuming im calling it wrong now.
Try this just before executing your AsyncTask.
You can do this inside your onSuccess() method of the FacebookCallback().
GraphRequest request = GraphRequest.newMeRequest(accessToken, new GraphRequest.GraphJSONObjectCallback(){
#Override
public void onCompleted(JSONObject jsonObject, GraphResponse graphResponse) {
try {
email = jsonObject.getString("email");
fullName = jsonObject.getString("name");
} catch (Exception e) {
Log.d("FacebookActivity", "onCompleted - undetermined FB exception");
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,email");
request.setParameters(parameters);
request.executeAsync();
}
#Override public void onCancel(){}
#Override public void onError(){}
Good luck!
I am using latest Facebook sdk for android in my applicaton.
public class MainActivity extends AppCompatActivity {
public static CallbackManager callbackmanager;
private AccessTokenTracker mTokenTracker;
private ProfileTracker mProfileTracker;
Button fb_login;
private boolean fb_signincllicked = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getApplicationContext());
setContentView(R.layout.activity_main);
fb_login = (Button) findViewById(R.id.fb_login_button);
fb_login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onFblogin(true);
}
});
}
public void onFblogin(boolean fb_btn) {
fb_signincllicked = fb_btn;
callbackmanager = CallbackManager.Factory.create();
// setupTokenTracker();
// setupProfileTracker();
// mTokenTracker.startTracking();
// mProfileTracker.startTracking();
// Set permissions
LoginManager.getInstance().logInWithReadPermissions(this, Arrays.asList("public_profile", "email"));
LoginManager.getInstance().registerCallback(callbackmanager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
// AccessToken accessToken = loginResult.getAccessToken();
// Profile profile = Profile.getCurrentProfile();
final Set<String> deniedPermissions = loginResult.getRecentlyDeniedPermissions();
GraphRequest.newMeRequest(loginResult.getAccessToken(), new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject json, GraphResponse response) {
if (response.getError() != null) {
// handle error
} else {
try {
// if (deniedPermissions.contains("email")) {
// LoginManager.getInstance().logInWithReadPermissions(Login_Activity.this, Arrays.asList("email"));
// }
JSONObject jsonObject = new JSONObject();
if (jsonObject.has("picture")) {
String profilePicUrl = jsonObject.getJSONObject("picture").getJSONObject("data").getString("url");
System.out.println("111015:profilePicUrl" + profilePicUrl);
} else {
System.out.println("111015:profilePicUrl" + "No Data");
}
jsonObject.put("full_name", json.getString("name"));
Toast.makeText(getApplicationContext(), json.get("id").toString() + json.getString("name"), Toast.LENGTH_LONG).show();
jsonObject.put("device_id", Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID));
jsonObject.put("fb_id", json.getString("id"));
jsonObject.put("signuptype", "1");
Intent i = new Intent(getBaseContext(), Profile.class);
i.putExtra("prof_name", json.getString("name"));
i.putExtra("fb_id", json.getString("id"));
startActivity(i);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}).executeAsync();
}
#Override
public void onCancel() {
Log.d("Cancel", "On cancel");
}
#Override
public void onError(FacebookException error) {
Log.d("Error", error.toString());
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (fb_signincllicked) {
callbackmanager.onActivityResult(requestCode, resultCode, data);
}
}
#Override
public void onStop() {
super.onStop();
// mTokenTracker.stopTracking();
// mProfileTracker.stopTracking();
}
// 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);
// }
// };
// }
}
After success full login(which succeeded) i want to go to another activity.There i want to show the following,
Facebook profile picture in a custom image view(not in the image
view which Facebook provided).
Primary-Email
Phone Number(If user provided in Face Book)
Facebook link of the user.
Please help me. Thanks in advance.
On your onActivityCreated() put this code :
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
updateWithToken(AccessToken.getCurrentAccessToken());
}
then here is my code which i'm currently using it to make facebook login :
private void updateWithToken(AccessToken currentAccessToken) {
mTokenTracker.startTracking();
mProfileTracker.startTracking();
if (currentAccessToken != null) {
String accessToken = currentAccessToken
.getToken();
Log.i("accessToken", accessToken);
GraphRequest request = GraphRequest.newMeRequest(
currentAccessToken,
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object,
GraphResponse response) {
Log.i("LoginActivity",
response.toString());
try {
String id = object.getString("id");
try {
URL profile_pic = new URL(
"http://graph.facebook.com/" + id + "/picture?type=large");
Log.i("profile_pic",
profile_pic + "");
} catch (MalformedURLException e) {
e.printStackTrace();
}
if (!sessionManagerFacebook.isLoggedIn()) {
sessionManagerFacebook.createLoginSession(object.getString("email"), getResources().getConfiguration().locale.toString());
if (cameFromQuestionExtra != null && cameFromQuestionExtra.getString("cameFromQuestion").equals("yes")) {
getActivity().setResult(1);
getActivity().finish();
}
//startActivity(new Intent(getActivity(), MainActivity.class));
} else {
user = sessionManagerFacebook.getUserDetails();
startActivity(new Intent(getActivity(), MainActivity.class));
}
getActivity().finish();
} catch (JSONException e) {
e.printStackTrace();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields",
"id,name,email,gender");
request.setParameters(parameters);
request.executeAsync();
}
}
And on your second activity u just have to make new profile variable :
Profile profile = Profile.getCurrentProfile();
if (profile != null) {
Toast.makeText(MainActivity.this, profile.getName(), Toast.LENGTH_SHORT).show();
loadImages(profile.getProfilePictureUri(120, 120).toString());
profileName.setText(profile.getName());
mDrawer.getMenu().findItem(R.id.nav_myAccount).setVisible(false);
Bundle extra = getIntent().getExtras();
String email;
if (extra != null) {
email = extra.getString("email");
profileEmail.setText(email);
Toast.makeText(MainActivity.this, email, Toast.LENGTH_SHORT).show();
} else if (sessionManagerFacebook.isLoggedIn()) {
profileEmail.setText(userFacebook.get(SessionManagerFacebook.KEY_EMAIL));
Toast.makeText(MainActivity.this, userFacebook.get(SessionManagerFacebook.KEY_EMAIL), Toast.LENGTH_SHORT).show();
}
}
https://developers.facebook.com/docs/reference/android/current/class/Profile/
This is my login function:-
public void loginToFacebook() {
mPrefs = getPreferences(MODE_PRIVATE);
access_token = mPrefs.getString("access_token", null);
long expires = mPrefs.getLong("access_expires", 0);
if (access_token != null) {
facebook.setAccessToken(access_token);
}
if (expires != 0) {
facebook.setAccessExpires(expires);
}
if (!facebook.isSessionValid()) {
facebook.authorize(this,new String[] { "email", "publish_stream" },
new DialogListener() {
#Override
public void onCancel() {
// Function to handle cancel event
}
#Override
public void onComplete(Bundle values) {
// Function to handle complete event
// Edit Preferences and update facebook acess_token
SharedPreferences.Editor editor = mPrefs.edit();
editor.putString("access_token",
facebook.getAccessToken());
editor.putLong("access_expires",
facebook.getAccessExpires());
editor.commit();
}
#Override
public void onError(DialogError error) {
// Function to handle error
}
#Override
public void onFacebookError(FacebookError fberror) {
// Function to handle Facebook errors
}
});
}
}
This my function to get facebook likes and attributes:
public void getProfileInformation() {
mAsyncRunner.request("me", new RequestListener() {
#Override
public void onComplete(String response, Object state) {
Log.d("Profile", response);
String json = response;
try {
JSONObject profile = new JSONObject(json);
id=profile.getString("id");
// getting name of the user
name = profile.getString("name");
// getting email of the user
email = profile.getString("email");
//about=profile.getString(about);
bio=profile.getString(bio);
birthday=profile.getString(birthday);
gender=profile.getString(gender);
link=profile.getString(link);
locale=profile.getString(locale);
political=profile.getString(political);
quotes=profile.getString(quotes);
relationship_status=profile.getString(relationship_status);
relegion=profile.getString(relegion);
website=profile.getString(website);
Log.d("Name",name);
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "Name: " + name + "\nEmail: " + email, Toast.LENGTH_LONG).show();
}
});
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onIOException(IOException e, Object state) {
}
#Override
public void onFileNotFoundException(FileNotFoundException e,
Object state) {
}
#Override
public void onMalformedURLException(MalformedURLException e,
Object state) {
}
#Override
public void onFacebookError(FacebookError e, Object state) {
}
});
//Getting Facebook Like
Session session = Session.getActiveSession();
new Request(
session,
"/{id}/likes",
null,
HttpMethod.GET,
new Request.Callback() {
public void onCompleted(Response response) {
Log.d("Facebook Likes", response.toString());
}
}
).executeAsync();
/*Session session = Session.getActiveSession();
Request.Callback callback = new Request.Callback() {
#Override
public void onCompleted(Response response) {
// response should have the likes
Toast.makeText(getApplicationContext(), response.toString(), Toast.LENGTH_LONG).show();
Log.d("Facebook Likes", response.toString());
}
};
Request request = new Request(session, "me/likes", null, HttpMethod.GET, callback);
RequestAsyncTask task = new RequestAsyncTask(request);
task.execute();*/
ERROR:-
D/Request﹕ Warning: Sessionless Request needs token but missing either application ID or client token.
I am getting other attributes as
28959-29486/com.example.sensetest D/Profile﹕ {"id":"************","email":"***********","first_name":"***","gender":"male","last_name":"****","link":"****","locale":"en_US","middle_name":"Singh","name":"Rituraj Singh Rathore","timezone":5.5,"updated_time":"2015-03-22T11:01:08+0000","verified":true}
The problem is I am not able to get facebook likes of user who has logged in. I have tried also How to get user likes from Facebook with Android sdk 3.0.
But I didn't got desired result.
Help me regarding this, Where am i doing wrong. What should i do to make it right?
im my application,i can login to facebook and get the data,but when i click on logout,and then click on login again,it toast the message already login,but i want after logout,on login it again ask the login id and password,as all login requires.in on destroy i tried to clear the session,but it shows an error null exception in onDestroy. please suggest somthing
MainActivity
public class MainActivity extends Activity {
Facebook fb;
Button login,getData,logout;
ImageView ig;
String app_id;
String access_token;
long expires;
private static AsyncFacebookRunner mAsyncRunner;
private SharedPreferences mPrefs;
SharedPreferences.Editor editor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
app_id= getString(R.string.app_id);
fb= new Facebook(app_id);
login=(Button) findViewById(R.id.login);
logout=(Button) findViewById(R.id.logout);
getData=(Button) findViewById(R.id.getData);
// ig= (ImageView) findViewById(R.id.profile_pic);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
loginToFacebook();
}
});
getData.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getProfileInformation();
}
});
logout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(fb.isSessionValid()){
Session.initializeStaticContext(MainActivity.this.getApplicationContext());
logoutFromFacebook();
}
}
});
mAsyncRunner = new AsyncFacebookRunner(fb);
//updateButtonImage();
try {
PackageInfo info = getPackageManager().getPackageInfo(getPackageName(), 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 (NameNotFoundException e) {
Log.e("name not found", e.toString());
} catch (NoSuchAlgorithmException e) {
Log.e("no such an algorithm", e.toString());
}
}
#SuppressWarnings("deprecation")
public void loginToFacebook() {
mPrefs = getPreferences(MODE_PRIVATE);
access_token = mPrefs.getString("access_token", null);
expires = mPrefs.getLong("access_expires", 0);
if (access_token != null) {
fb.setAccessToken(access_token);
login.setVisibility(View.VISIBLE);
// Making get profile button visible
getData.setVisibility(View.VISIBLE);
Log.d("FB Sessions", "" + fb.isSessionValid());
}
if (expires != 0) {
fb.setAccessExpires(expires);
Toast.makeText(MainActivity.this, "already login", Toast.LENGTH_LONG).show();}
if (!fb.isSessionValid()) {
fb.authorize(this,
new String[] { "email", "publish_stream" },
new DialogListener() {
#Override
public void onCancel() {
// Function to handle cancel event
}
#Override
public void onComplete(Bundle values) {
// Function to handle complete event
// Edit Preferences and update facebook acess_token
editor = mPrefs.edit();
editor.putString("access_token",
fb.getAccessToken());
editor.putLong("access_expires",
fb.getAccessExpires());
editor.commit();
// Making Login button invisible
login.setVisibility(View.VISIBLE);
// Making logout Button visible
getData.setVisibility(View.VISIBLE);
}
#Override
public void onError(DialogError error) {
// Function to handle error
}
#Override
public void onFacebookError(FacebookError fberror) {
// Function to handle Facebook errors
}
});
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
fb.authorizeCallback(requestCode, resultCode, data);
}
#SuppressWarnings("deprecation")
public void getProfileInformation() {
mAsyncRunner.request("me", new RequestListener() {
public void onComplete(String response, Object state) {
Log.d("Profile", response);
String json = response;
try {
// Facebook Profile JSON data
JSONObject profile = new JSONObject(json);
// getting name of the user
final String name = profile.getString("name");
// getting email of the user
final String email = profile.getString("email");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "Name: " + name + "\nEmail: " + email, Toast.LENGTH_LONG).show();
}
});
} catch (JSONException e) {
e.printStackTrace();
}
}
public void onIOException(IOException e, Object state) {
}
public void onFileNotFoundException(FileNotFoundException e,
Object state) {
}
public void onMalformedURLException(MalformedURLException e,
Object state) {
}
public void onFacebookError(FacebookError e, Object state) {
}
});
}
#Deprecated
public void logoutFromFacebook() {
mAsyncRunner.logout(MainActivity.this, new RequestListener() {
#Override
public void onComplete(String response, Object state) {
Log.d("Logout from Facebook", response);
if (Boolean.parseBoolean(response) == true) {
runOnUiThread(new Runnable() {
#Override
public void run() {
// make Login button visible
login.setVisibility(View.VISIBLE);
// making all remaining buttons invisible
getData.setVisibility(View.INVISIBLE);
}
});
}
}
#Override
public void onIOException(IOException e, Object state) {
}
#Override
public void onFileNotFoundException(FileNotFoundException e,
Object state) {
}
#Override
public void onMalformedURLException(MalformedURLException e,
Object state) {
}
#Override
public void onFacebookError(FacebookError e, Object state) {
}
});
}
#Override protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
// if(fb.isSessionValid()){
Session.getActiveSession().closeAndClearTokenInformation();
// }
}
}
It is not guaranteed that onDestroy() method will call always called on activity finish.
So better you put that code of session clear in onPause() method.
UPDATE:
Do One more thing
SharedPreferences.Editor editor = getPreferences(MODE_PRIVATE).edit();
editor.putString("access_token", null);
editor.commit();
SharedPreferences.Editor editor2 = getPreferences(MODE_PRIVATE).edit();
editor2.putLong("access_expires", 0);
editor2.commit();
Add this lines in your facebookLogout() method.
Because In your code I found that you are not checking for the session you checking this two variables to identify whether the user is login or not.
You can't rely to onDestroy to be called just after quiting your activity (finish()). it's usually the case but ondestroy can be called after a considerable delay.
you can call your cleaning code in onPause and you can enhance it like following:
#Override protected void onDestroy() {
super.onDestroy();
Session session = Session.getActiveSession();
if (session != null){
session.closeAndClearTokenInformation();
}
}
it is not known when onDestroy is going to call. it only invoke onStop and then move your activity to back. It is happen because if user again start this application , it will not have to load activity in ram again.because it a costly process to load activity in ram. so dont do any saving of data or any other work in onDestroy.move that work in onPause or in onStop.
read more here
I'm creating app that has share button on Facebook and I'm getting an error:
This Page Contains the following errors:
error on line 2 at column 182: Entityref: expecting ';'
Below is a rendering of the page up to the first error.
I don't get this error when I run the app on the Emulator. I'm only getting this kind of error when I run the app on the device.
What is the possible cause of this error?
Your help is highly appreciated. Thanks!
Code below is sample code for Facebook SDK:
public class FacebookShare extends Activity
{
private String APP_ID, APP_SECRET, Name, Link, Description, Picture;
private int fbTYPE;
private Facebook facebook;
private AsyncFacebookRunner mAsyncRunner;
private Activity ctx;
private Bitmap bitmap;
SharedPreferences mPrefs;
public FacebookShare(Activity ctx)
{
APP_ID = "...obfuscated...";
facebook = new Facebook(APP_ID);
mAsyncRunner = new AsyncFacebookRunner(facebook);
this.ctx = ctx;
}
public void shareFB(int TypeOfSharing)
{
APP_ID = "...obfuscated...";
facebook = new Facebook(APP_ID);
mAsyncRunner = new AsyncFacebookRunner(facebook);
this.fbTYPE = TypeOfSharing;
loginToFacebook();
}
public void loginToFacebook()
{
Log.v("debugging", "Entered Login to facebook");
String access_token = mPrefs.getString("access_token", "");
long expires = mPrefs.getLong("access_expires", 0);
if (!access_token.equals(""))
{
facebook.setAccessToken(access_token);
Log.v("Access Token", facebook.getAccessToken());
}
if (expires != 0)
{
facebook.setAccessExpires(expires);
}
if (!facebook.isSessionValid())
{
Log.v("debugging", "Session is Invalid");
facebook.authorize(ctx, new String[]{
"email","publish_stream"
}, facebook.FORCE_DIALOG_AUTH, new DialogListener()
{
public void onCancel()
{
// Function to handle cancel event
}
public void onComplete(Bundle values)
{
// Function to handle complete event
// Edit Preferences and update facebook acess_token
SharedPreferences.Editor editor = mPrefs.edit();
editor.putString("access_token", facebook.getAccessToken());
editor.putLong("access_expires", facebook.getAccessExpires());
editor.commit();
if (fbTYPE == 1)
{
postToWall();
}
else if (fbTYPE == 0)
{
postToWall(getBitmap());
}
}
public void onError(DialogError error)
{
Log.v("debugging", error.getMessage());
}
public void onFacebookError(FacebookError fberror)
{
Log.v("debugging", fberror.getMessage());
}
});
Log.v("debugging", "Passed from authorization");
}
else
{
if (fbTYPE == 1)
{
Log.v("debugging", "Entered Post to facebook");
postToWall();
}
else if (fbTYPE == 0)
{
Log.v("debugging", "Entered Post image to facebook");
postToWall(getBitmap());
}
}
}
public void clearCredentials()
{
try
{
facebook.logout(ctx);
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
public void postToWall()
{
// post on user's wall.
Bundle params = new Bundle();
params.putString("description", getDescription());
params.putString("picture", getPicture());
params.putString("name", getName());
params.putString("link", getLink());
facebook.dialog(ctx, "feed", params, new DialogListener()
{
public void onFacebookError(FacebookError e)
{
}
public void onError(DialogError e)
{
}
public void onComplete(Bundle values)
{
Toast.makeText(ctx, "Thanks for sharing JOLENPOP", Toast.LENGTH_SHORT).show();
}
public void onCancel()
{
// Login_Activity.asyncFBLogin fblogin = null;
// fblogin.execute();
}
});
}
public void postToWall(Bitmap bmImage)
{
Log.v("debugging", "entered postToWall(bitmap)");
byte[] data = null;
Bitmap bm = Bitmap.createBitmap(bmImage);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(CompressFormat.JPEG, 100, baos);
data = baos.toByteArray();
Bundle params = new Bundle();
params.putString("method", "post");
params.putString("message", getDescription());
params.putByteArray("image", data);
try
{
String response = facebook.request("me");
response = facebook.request("me/photos", params, "POST");
if (response == null || response.equals("") || response.equals("false"))
{
Log.v("response String", response);
return;
}
else if (response.toLowerCase().contains("error"))
{
Log.v("response String", response);
return;
}
}
catch (Exception e)
{
return;
}
Toast.makeText(ctx, "Your photo has been successfuly published!", Toast.LENGTH_LONG).show();
}
public void getProfileInformation()
{
mAsyncRunner.request("me", new RequestListener()
{
public void onComplete(String response, Object state)
{
Log.d("Profile", response);
String json = response;
try
{
JSONObject profile = new JSONObject(json);
// getting name of the user
String name = profile.getString("name");
// getting email of the user
String email = profile.getString("email");
runOnUiThread(new Runnable()
{
public void run()
{
// Toast.makeText(getApplicationContext(), "Name: " + name
// + "\nEmail: " + email, Toast.LENGTH_LONG).show();
}
});
}
catch (JSONException e)
{
e.printStackTrace();
}
}
public void onIOException(IOException e, Object state)
{
}
public void onFileNotFoundException(FileNotFoundException e, Object state)
{
}
public void onMalformedURLException(MalformedURLException e, Object state)
{
}
public void onFacebookError(FacebookError e, Object state)
{
}
});
}
/**
* setters
* */
public void setFacebook(Facebook facebook)
{
this.facebook = facebook;
}
public void setAsyncRunner(AsyncFacebookRunner mAsyncRunner)
{
this.mAsyncRunner = mAsyncRunner;
}
public void setPrefs(SharedPreferences mPrefs)
{
this.mPrefs = mPrefs;
}
public void setName(String val)
{
this.Name = val;
}
public void setLink(String val)
{
this.Link = val;
}
public void setBitmap(Bitmap val)
{
this.bitmap = val;
}
public void setDescription(String val)
{
this.Description = val;
}
public void setPicture(String val)
{
this.Picture = val;
}
/**
* getters
* */
public String getAppID()
{
return this.APP_ID;
}
public String getName()
{
return this.Name;
}
public String getLink()
{
return this.Link;
}
public String getDescription()
{
return this.Description;
}
public String getPicture()
{
return this.Picture;
}
public Bitmap getBitmap()
{
return this.bitmap;
}
}
Here how I used it:
fbShare = new FacebookShare(this);
mPrefs = PreferenceManager.getDefaultSharedPreferences(this);
then;
Bitmap screenshot = this.glSurfaceView.mRenderer.screenCapture;
fbShare.setName("JOLENPOP");
fbShare.setDescription("I got a score of " + this.glSurfaceView.mRenderer.Score + " in JOLENPOP! Try to beat me!");
fbShare.setBitmap(screenshot);
fbShare.setPrefs(mPrefs);
fbShare.shareFB(0);