I am working in Android app with Facebook integration but I am getting issue as whenever I try to logout the Facebook is not getting completely logout,
I searched a lot and finally I have used the code as follows:
public Facebook mFacebook = new Facebook(APP_ID);
SessionStore.clear(logoutActivity.this);
try {
mFacebook.logout(logoutActivity.this);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I tried the above code but not at all working,the Facebook is not getting complete logout. Could somebody help me out??
This May Will help to you...
Activity.mAsyncRunner.logout(this, new RequestListener() {
public void onComplete(String response, Object state) {
Log.d("Logout from Facebook", response);
if (Boolean.parseBoolean(response) == true) {
// User successfully Logged out
Toast.makeText(getApplicationContext(), "Successfully logged out ", Toast.LENGTH_LONG).show();
}
}
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) {
}
});
Example below url
http://www.androidhive.info/2012/03/android-facebook-connect-tutorial/
Related
I have developed a physics based (Box2d) game for android using Processing and I want to add score sharing option to it so that the user can share his/her best score on their facebook timeline after the game. I have setup Facebook SDK in eclipse. I have searched over internet and found this solution:
public class FacebookConnector {
private static final String APP_ID = "*************";
private Facebook facebook;
private AsyncFacebookRunner mAsyncRunner;
String FILENAME = "AndroidSSO_data";
SharedPreferences mPrefs;
public FacebookConnector() {
facebook = new Facebook(APP_ID);
mAsyncRunner = new AsyncFacebookRunner(facebook);
}
public void loginToFacebook() {
mPrefs = getPreferences(MODE_PRIVATE);
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(LocalPakistaniGames.this,
new String[] { "email",
"publish_stream" }, 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();
}
public void onError(DialogError error) {
// Function to handle error
}
public void onFacebookError(FacebookError fberror) {
// Function to handle Facebook errors
}
});
}
}
public void logoutFromFacebook() {
mAsyncRunner.logout(LocalPakistaniGames.this,
new RequestListener() {
#Override
public void onComplete(String response, Object state) {
Log.d("Logout from Facebook", response);
if (Boolean.parseBoolean(response) == true) {
// User successfully Logged out
}
}
#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) {
}
});
}
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
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 onIOException1(IOException e, Object state) {
}
public void onFileNotFoundException1(FileNotFoundException e,
Object state) {
}
public void onMalformedURLException1(MalformedURLException e,
Object state) {
}
#Override
public void onFacebookError(FacebookError e, Object state) {
}
#Override
public void onIOException(IOException e, Object state) {
// TODO Auto-generated method stub
}
#Override
public void onFileNotFoundException(FileNotFoundException e,
Object state) {
// TODO Auto-generated method stub
}
#Override
public void onMalformedURLException(MalformedURLException e,
Object state) {
// TODO Auto-generated method stub
}
});
}
public void postToWall(int level, int score) {
// post on user's wall.
String msg = "I just made new best score in Level " + level
+ ". My new Best Score is " + score + ". Beat my score!";
final Bundle parameters = new Bundle();
parameters.putString("description", msg);
parameters.putString("picture", "http://i57.tinypic.com/fui2o.png");
parameters.putString("link",
"https://www.facebook.com/LocalPakistaniGamesAndroid");
parameters.putString("name", "Local Pakistani Games");
parameters.putString("caption",
"Share this. Be a part of preserving Pakistani culture.");
LocalPakistaniGames.this.runOnUiThread(new Runnable() {
public void run() {
facebook.dialog(LocalPakistaniGames.this, "feed",
parameters, new DialogListener() {
#Override
public void onComplete(Bundle values) {
// TODO Auto-generated method stub
if (values != null) {
Toast.makeText(LocalPakistaniGames.this,
"Shared successfully on your timeline!",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(
LocalPakistaniGames.this,
"Share cancelled!",
Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFacebookError(FacebookError e) {
// TODO Auto-generated method stub
Toast.makeText(LocalPakistaniGames.this,
"Facebook Error!",
Toast.LENGTH_SHORT)
.show();
}
#Override
public void onError(DialogError e) {
// TODO Auto-generated method stub
Toast.makeText(LocalPakistaniGames.this,
"Error!", Toast.LENGTH_SHORT)
.show();
}
#Override
public void onCancel() {
// TODO Auto-generated method stub
Toast.makeText(LocalPakistaniGames.this,
"Share cancelled!",
Toast.LENGTH_SHORT).show();
}
});
}
});
}
}
Its working fine and giving a pre-filled dialog box where user can either share or close the dialog box. I have checked and It's sharing correctly on Facebook timeline. But the problem is that it is not using Facebook app installed on the device. Its using chrome on my device to login to Facebook.
Is there any way to force it to use Facebook app for android instead of going to chrome (or any other browser)??
There are many issues with your use of the Facebook SDK, but I will jump straight to your problem.
You're using the "feed" dialog to share. This is a web dialog, which is why it's popping up a WebView (not the actual browser app). You also do not pass any session or access tokens to the feed dialog, which is why the user needs to login before they can share.
If you want to share using the Facebook app, I would recommend this doc: https://developers.facebook.com/docs/android/share
If you want to properly use the Facebook SDK (rather than the old deprecated one), please start here: https://developers.facebook.com/docs/android/getting-started/
Here is the solution to your problem. If you want to make automatic publications on facebook wall, you have to use graph api.
Also, the first thing that you have to do is login with facebook and after that, you have to do another request for permissions.
If you are using LoginManager:
LoginManager.getInstance().logInWithPublishPermissions(this, Arrays.asList("publish_actions"));
this line of code gives to your app the permissions to make publications in behalf to the user
I am Upload video from my application and get the information of that video (likes,comments)
Problem 1
I have done uploading but when i get video information it throws me error
Error
{"error":{"message":"Cannot specify type in both the path and query parameter.","type":"OAuthException","code":2500}}
I am using Facebook SDK 3.8
Problem 2
When i upload video it Only visible in my account but not visible from other account even though it is public
Code For Upload Video
private void Upload_Video() {
mDialog = new ProgressDialog(AndroidFacebookConnectActivity.this);
mDialog.setMessage("Uploding video...");
mDialog.show();
String path="/mnt/sdcard/abc/Mirror.mp4";
if (new File(path).exists()) {
try {
Bundle param;
try {
InputStream is = new FileInputStream(path);
byte[] data = readBytes(is);
param = new Bundle();
param.putString("title", "Test 2");
param.putString("message", "uploaded");
param.putByteArray("video.mov", data);
param.putString("contentType", "video/quicktime");
mAsyncRunner.request("kmavadhiya/videos", param, "POST",new FBRequestListener(), null);
Toast.makeText(getApplicationContext(), "Uploading...", Toast.LENGTH_SHORT).show();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
} else {
Toast.makeText(getApplicationContext(), "No videos found in sdcard ",Toast.LENGTH_SHORT).show();
}
}
public byte[] readBytes(InputStream inputStream) throws IOException {
// This dynamically extends to take the bytes you read.
ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
// This is storage overwritten on each iteration with bytes.
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
// We need to know how may bytes were read to write them to the byteBuffer.
int len = 0;
while ((len = inputStream.read(buffer)) != -1) {
byteBuffer.write(buffer, 0, len);
}
// And then we can return your byte array.
return byteBuffer.toByteArray();
}
Upload Request Listner
public class FBRequestListener implements RequestListener {
#Override
public void onComplete(String response, Object state) {
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(AndroidFacebookConnectActivity.this, "Upload Video Successfully...",Toast.LENGTH_LONG).show();
mDialog.dismiss();
}
});
Log.e("response", response);
try {
JSONObject jObject = new JSONObject(response);
String Id = (String) jObject.get("id");
Log.d("Video Id = ",""+Id);
Bundle param = new Bundle();
param.putString("type", "uploaded");
mAsyncRunner.request("kmavadhiya/videos/"+Id, param, "GET",new VideoDataRequestListener(), null);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void onIOException(IOException e, Object state) {
e.printStackTrace();
}
#Override
public void onFileNotFoundException(FileNotFoundException e,
Object state) {
Log.e("", "onFileNotFoundException");
e.printStackTrace();
}
#Override
public void onMalformedURLException(MalformedURLException e,
Object state) {
Log.e("", "onMalformedURLException");
e.printStackTrace();
}
#Override
public void onFacebookError(FacebookError e, Object state) {
Log.e("", "onFacebookError");
e.printStackTrace();
}
}
Video Data Listner
public class VideoDataRequestListener implements RequestListener {
#Override
public void onComplete(String response, Object state) {
// TODO Auto-generated method stub
Log.e("response", response);
}
#Override
public void onIOException(IOException e, Object state) {
// TODO Auto-generated method stub
}
#Override
public void onFileNotFoundException(FileNotFoundException e,
Object state) {
// TODO Auto-generated method stub
}
#Override
public void onMalformedURLException(MalformedURLException e,
Object state) {
// TODO Auto-generated method stub
}
#Override
public void onFacebookError(FacebookError e, Object state) {
// TODO Auto-generated method stub
}
}
If I changed This Line
mAsyncRunner.request("kmavadhiya/videos/"+Id, param, "GET",new VideoDataRequestListener(), null);
With
mAsyncRunner.request("kmavadhiya/videos/", param, "GET",new VideoDataRequestListener(), null);
** I got Blank Response**
Reference
Link 1
Graph Api Reference Link
I Forget To Request Permission At Login time So Its Authentication Error
Add This In Login click
Session session = Session.getActiveSession();
if (!session.isOpened() && !session.isClosed()) {
session.openForRead(new Session.OpenRequest(this)
.setPermissions(Arrays.asList("basic_info","user_about_me","email","video_upload","user_videos")) // Permission List That You Want To Get
.setCallback(statusCallback));
} else {
Session.openActiveSession(this, true, statusCallback);
}
Reference
Permission List
https://developers.facebook.com/docs/facebook-login/access-tokens/
Set Permission Reference
https://developers.facebook.com/docs/android/login-with-facebook#permissions
my english is not so perfect but i want to learn, so i hope you can understand me. I wanna know how can i change the facebook profile pic using facebook android sdk. im able to upload pictures from my app to any album, including "Profile Pictures" (i use the next code:)
params=new Bundle();
params.putByteArray("photo", photo);
params.putString("caption", description);
mAsyncRunner.request(idAlbum+"/photos", params,"POST",new RequestListener() {
#Override
public void onMalformedURLException(MalformedURLException e, Object state) {}
#Override
public void onIOException(IOException e,Object state) {}
#Override
public void onFileNotFoundException(FileNotFoundException e, Object state){}
#Override
public void onFacebookError(FacebookError e,Object state) {}
#Override
public void onComplete(String response, Object state) {
mHandler.post(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),"Success", Toast.LENGTH_LONG).show();
}
});
}
}, null);
but i dont know how to set the uploaded image as the profile pic. maybe adding some code to this? I know that what i ask is posible using facebook sdk for php. also, i have seen an Apple app that do this too. Then, i think i can do it in android. somebody has information about what im looking for? thanks in advance.
Ok, I found the way to do that. and this is the code:
params=new Bundle();
try {
params.putByteArray("photo", photo);
} catch (IOException e) {
e.printStackTrace();
}
params.putString("caption", description);
mAsyncRunner.request(idAlbum+"/photos", params,"POST",
new RequestListener() {
#Override
public void onMalformedURLException(MalformedURLException
e, Object state) {}
#Override
public void onIOException(IOException e,Object state) {}
#Override
public void onFileNotFoundException(
FileNotFoundException e, Object state){}
#Override
public void onFacebookError(FacebookError e,Object state) {}
#Override
public void onComplete(final String response, Object state) {
mHandler.post(new Runnable() {
#Override
public void run() {
try {
JSONObject json=new JSONObject(response);
JSONObject obj=new JSONObject(
facebook.request("me"));
final String photoId=json.getString("id");
String userId=obj.getString("id");
String url="https://m.facebook.com/photo." +
"php?fbid="+photoId+"&id="+userId+
"&prof&__user="+userId;
Intent mIntent=new Intent(Intent.ACTION_VIEW,
Uri.parse(url));
startActivity(mIntent);
} catch (JSONException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
}, null);
Post the photo on a specific album, get the photoID with a JSONObject, and then redirect to a web page where the user can confirm to set the photo as his/her profile picture.
I have made a sample for posting on Facebook using the basic Facebook library provided at developer.facebook.com and it works just fine with SSO,
btnPostOnFb.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
{
facebook.authorize(FBIntegrationSampleActivity.this, new String[]{ "user_photos,publish_checkins,publish_actions,publish_stream"}, new DialogListener() {
#Override
public void onComplete(Bundle values) {
if(values!=null && values.containsKey("access_token")){
postOnWall("NEW POST from" +count+"Android -Anuj");
Log.e("post on wall", "WALLPOST");
Toast.makeText(getApplicationContext(), "SUCCESSFULLY POSTED MSG ON WALL", Toast.LENGTH_SHORT).show();
}else if(values!=null)
Log.e("LOGINE SUCCESS", "LOGIN SUCCESS");
Toast.makeText(getApplicationContext(), "SUCCESSFULLY LOGGED IN", Toast.LENGTH_SHORT).show();
}
#Override
public void onFacebookError(FacebookError error) {
Log.e("onFBERROR", "ONFBERROR");
}
#Override
public void onError(DialogError e) {
Log.e("on DESI ERROR", "ON_ERROR");
}
#Override
public void onCancel() {
Log.e("onCANCEL", "ONCANCEL");
}
});
}
}
});
Which successfully posts on the Facebook wall, what i want is, I need to show the user that he has successfully signed in, and a message would be posted there after.
The Issue i face is the onComplete(Bundle values) method is called for both successful login and for successful post, how can i differentiate between both of them, is there a key in the Bundle values that can help to find the differnence?
Any suggestions are welcome.
Problem is that you are using for Authentication and Posting. No need to do like this :
For Authentication use
facebook.authorize(a, PERMISSIONS,-1,new LoginListener());
And for posting :
1) Without Dialog facebook.request(parameters)
2) With Dialog
facebook.dialog(this,"stream.publish",parameters,new TestUiServerListener());
public class TestUiServerListener implements DialogListener {
public void onComplete(Bundle values) {
final String postId = values.getString("post_id");
if (postId != null) {
new AsyncFacebookRunner(ZValues.authenticatedFacebook).request(postId,new TestPostRequestListener());
} else {
Post_Message_Title.this.runOnUiThread(new Runnable() {
public void run() {
}
});
}
}
public void onCancel() {
}
public void onError(DialogError e) {
e.printStackTrace();
}
public void onFacebookError(FacebookError e) {
e.printStackTrace();
}
}
public class TestPostRequestListener implements RequestListener {
public void onComplete(final String response, final Object state) {
try {
JSONObject json = Util.parseJson(response);
String postId = json.getString("id");
this.runOnUiThread(new Runnable() {
public void run() {
successLoginShowDialog(); // Dialog after Login succeeds
}
});
} catch (Throwable e) {
}
}
public void onFacebookError(FacebookError e, final Object state) {
e.printStackTrace();
}
public void onFileNotFoundException(FileNotFoundException e,
final Object state) {
e.printStackTrace();
}
public void onIOException(IOException e, final Object state) {
e.printStackTrace();
}
public void onMalformedURLException(MalformedURLException e,
final Object state) {
e.printStackTrace();
}
}
Just create a method successLoginShowDialog() and show whatever you want ,
If Post is success , In TestPostRequestListener below Thread will be called , so do all stuffs in this Thread :
this.runOnUiThread(new Runnable() {
public void run() {
successLoginShowDialog(); // Dialog after Login succeeds
}
});
to postOnWall() you can get its response:
public void postToWall(String message) {
Bundle parameters = new Bundle();
parameters.putString("message", message);
parameters.putString("description", "topic share");
try {
fbObj.request("me");
String response = fbObj.request("me/feed", parameters, "POST");
Log.d("Tests", "got response: " + response);
if (response == null || response.equals("")
|| response.equals("false")) {
// showToast("Blank response.");
Toast.makeText(context, "blank response", Toast.LENGTH_SHORT)
.show();
} else {
// showToast("Message posted to your facebook wall!");
Toast.makeText(context,
"Message posted to your facebook wall!",
Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
// showToast("Failed to post to wall!");
e.printStackTrace();
}
}
I use the single sign on in my application (http://developers.facebook.com/docs/mobile/android/build/). It seems working fine on the emulator (i log in succefully and get the access_token). But in my Nexus S, the webview shows up, but I always get "login failed".
There is my code:
((Button)findViewById(R.id.BtnFacebook)).setOnClickListener(new OnClickListener(){
public void onClick(View v) {
//startActivity(intentLoginFacebook);
facebook.authorize(Login.this, new String[] {"user_about_me","user_activities","user_birthday","user_education_history","user_events","user_groups","user_hometown","user_interests","user_likes","user_location","user_religion_politics","user_status","user_website","user_work_history","read_requests","read_stream","friends_events","email","create_event","manage_friendlists","offline_access","rsvp_event"}, new DialogListener() {
#Override
public void onComplete(Bundle values) {
String id = "";
String access_token = facebook.getAccessToken();
System.out.println("ACCESSTOKENNNN:" + access_token);
try {
String response = facebook.request("me");
JSONObject obj = new JSONObject(response);
id = obj.getString("id");
System.out.println("response: "+response);
} catch (IOException ex) {
Log.d("Facebook", ex.getMessage());
} catch (Exception e) {
Log.d("Facebook", e.getMessage());
}
//Verification du login/password
new LoginFacebook().execute(id,access_token);
System.out.println("IDDDDDDDD:" + id);
}
#Override
public void onFacebookError(FacebookError error) {
Toast.makeText(getApplicationContext(), "Facebook error: login failed", Toast.LENGTH_LONG).show();
}
#Override
public void onCancel() {
}
#Override
public void onError(DialogError e) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "Login failed", Toast.LENGTH_LONG).show();
}
});
}
});
Thanks for your help!
Most likely the SDK stores your access_token and expires_in paramters in SharedPreferences. You need to log the detailed error. If you get OAuth exception on an API call you need to delete access_token from SharedPreferences and simply reauthorize.
hope this helps