Facebook image sharing not working in android - java

I have made an app in that I want to share an image and a text ,I have successfully get the login Dialog of facebook..But after Login it gives me error that Warning: Sessionless Request needs token but missing either application ID or client token.
What should i do to solve it.My code is as below ,Please help needed..
#SuppressWarnings("deprecation")
public void loginToFacebook() {
mPrefs = getPreferences(MODE_PRIVATE);
String access_token = mPrefs.getString("access_token", null);
long expires = mPrefs.getLong("access_expires", 0);
Session session = facebook.getSession();
if (access_token != null) {
SessionState st = SessionState.OPENED;
facebook.setAccessToken(access_token);
Exception e = new FacebookError("Error");
System.out.println("::::::::::::::aCEESS TOKEN::::::::;;"
+ access_token);
postToWall();
/*fbImageSubmit(facebook, big_img, "3sMAniquines", "Maniquines",
cat_nem, big_img);*/
onSessionStateChange(session, st, e);
Log.d("FB Sessions", "" + facebook.isSessionValid());
}
if (facebook.isSessionValid()) {
}
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
}
});
}
* */
#SuppressWarnings("deprecation")
public void postToWall() {
// post on user's wall.
facebook.dialog(this, "feed", new DialogListener() {
#Override
public void onFacebookError(FacebookError e) {
}
#Override
public void onError(DialogError e) {
}
#Override
public void onComplete(Bundle values) {
}
#Override
public void onCancel() {
}
});
}

You have to save the access token of logged user for maintaining Session for further task.
according to your code following code will give you currently logged in user's access token.
String access_token = Const.fb.getAccessToken();

Related

How do I make signOut Google+ in onNavigationItemSelected

I'm doing Sign In with Google+ that leads to the Navigation.activity. Ive follow the instruction on Google developer but I only took signIn method(Success) but now im stuck at navigation.activity. How do i make logout from navigationItemSelected?
What is the problem :
Google plus signIn in Main Activity but need to Logout from Navigation Activity...
TY for helping
else if (id == R.id.logout) {
}
This is my onResult
#Override
public void onResult(GoogleSignInResult googleSignInResult) {
hideProgressDialog();
handleSignInResult(googleSignInResult);
}
It will call hideprogress and handleSignInResult method..
private void handleSignInResult(GoogleSignInResult result) {
Log.d(TAG, "handleSignInResult:" + result.isSuccess());
if (result.isSuccess()) {
// Signed in successfully, show authenticated UI.
Intent intent = new Intent(Main.this,HomeActivity.class);
startActivity(intent);
} else {
// Signed out
}
}
private void hideProgressDialog() {
if (mProgressDialog != null && mProgressDialog.isShowing()) {
mProgressDialog.hide();
}
}
You can visit Signing Out Users and Disconnecting Accounts official link to perform SignOut and Revoke Access operation
Singout
private void signOut() {
Auth.GoogleSignInApi.signOut(mGoogleApiClient).setResultCallback(
new ResultCallback<Status>() {
#Override
public void onResult(Status status) {
// ...
}
});
}
Disconnect account
private void revokeAccess() {
Auth.GoogleSignInApi.revokeAccess(mGoogleApiClient).setResultCallback(
new ResultCallback<Status>() {
#Override
public void onResult(Status status) {
// ...
}
});
}

unable to post game score on facebook wall in android using libgdx framework

I am just trying to make a game where I need to post game score on facebook wall. And I am following libGDX framework. Below is my test activity that just post my custom message on facebook wall.
public class MainActivity extends Activity {
private static final String FB_APP_ID = "1452723631660564";
private static final String FACEBOOK_PERMISSION = "publish_stream";
private static final int FB_AUTH = 2; // ANY INTEGER VALUE
Facebook facebook = new Facebook(FB_APP_ID); //
static String FACEBOOK_UPDATE_MSG;
static String FACEBOOK_UPDATE_FAILURE;
static String FACEBOOK_UPDATE_SUCCESS;
static String FACEBOOK_SIGNIN_FAILED;
Handler fHandler = new Handler();
Map<Object, Object> preferences = new HashMap<Object, Object>();
#SuppressLint("NewApi")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
login("Hello facebook test app");
}
#SuppressWarnings("deprecation")
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case FB_AUTH:
facebook.authorizeCallback(requestCode, resultCode, data);
break;
default:
finish();
break;
}
}
public void postMessageOnWall(final String msg) {
try {
if (facebook.isSessionValid()) {
new Thread(new Runnable() {
#Override
public void run() {
Bundle parameters = new Bundle();
parameters.putString("message", msg);
parameters.putString("link", "ANDROID_MARKET_LINK"); // or any other
// link
parameters.putString("name", "APP/GAME NAME");
try {
#SuppressWarnings("deprecation")
String response = facebook.request("me/feed", parameters,
"POST");
FACEBOOK_UPDATE_MSG = FACEBOOK_UPDATE_SUCCESS;
fHandler.post(mUpdateFacebookNotification);
} catch (IOException e) {
FACEBOOK_UPDATE_MSG = FACEBOOK_UPDATE_FAILURE;
fHandler.post(mUpdateFacebookNotification);
}
}
});
}
} catch (Exception e) {
Log.e("error-----------", e.getLocalizedMessage());
}
}
final Runnable mUpdateFacebookNotification = new Runnable() {
public void run() {
Toast.makeText(getBaseContext(), FACEBOOK_UPDATE_MSG,
Toast.LENGTH_LONG).show();
}
};
#SuppressWarnings("deprecation")
public void login(final String msg) {
/*String access_token = preferences.getString("facebook_access_token",
null);*/
String access_token = (String) preferences.get("facebook_access_token");
long expires = 0;
if (access_token != null) {
facebook.setAccessToken(access_token);
}
if (expires != 0) {
facebook.setAccessExpires(10000000l);
}
/*
* Only call authorize if the access_token has expired.
*/
if (!facebook.isSessionValid()) {
facebook.authorize(this, new String[] { "publish_stream","read_stream", "offline_access" },
FB_AUTH, new DialogListener() {
#Override
public void onComplete(Bundle values) {
/*preferences.putString("access_token",
facebook.getAccessToken());
preferences.putLong("access_expires",
facebook.getAccessExpires());
preferences.flush();*/
preferences.put("access_token", facebook.getAccessToken());
preferences.put("access_expires", facebook.getAccessExpires());
if (msg != "")
postMessageOnWall(msg);
else
OpenFbPage();
}
private void OpenFbPage() {
}
#Override
public void onFacebookError(FacebookError error) {
FACEBOOK_UPDATE_MSG = FACEBOOK_SIGNIN_FAILED;
fHandler.post(mUpdateFacebookNotification);
}
#Override
public void onError(DialogError e) {
FACEBOOK_UPDATE_MSG = FACEBOOK_SIGNIN_FAILED;
fHandler.post(mUpdateFacebookNotification);
}
#Override
public void onCancel() {
}
});
}
}
}
I am not getting any exception/error in above code, but it also doesn't post my custom message on my facebook wall. It just opens an fb application and loading alert over that, nothing else. When I debug that, it neither reach on thread's run() method of postMessageOnWall() , nor I get any response defined in same method.
Please guide me where I am wrong. I know I write my whole code related to facebook post in single activity, but it just an test application. Once it is successful, I will segregate the logic.
among hundreds of things badly wrong with this example, you are not starting the thread (by calling start). If you had actually tried to make a small, self-contained example, as you should have, you would have found out on your own.

java.lang.NullPointerException with facebook onCompleted function

i have a problem
private class SessionStatusCallback implements Session.StatusCallback {
#Override
public void call(Session session, SessionState state,
Exception exception) {
if (session.isOpened()) {
getProfileInformation();
informDB();
runOnUiThread(new Runnable() {
#Override
public void run() {
}
});
}
updateView();
}
}
public void getProfileInformation() {
Request.newMeRequest(session, new Request.GraphUserCallback() {
// callback after Graph API response with user object
#Override
public void onCompleted(GraphUser user, Response response) {
if (user != null) {
// String access_token = session.getAccessToken();
profilePictureView.setProfileId(user.getId());
fbuser = new UserInfo(user.getId().toString(), user
.getName().toString(), null, null, null, null, null);
name = "dada";
us = user;
Toast.makeText(getApplicationContext(),
"Name: " + user.getName(), Toast.LENGTH_LONG)
.show();
}
}
}).executeAsync();
Log.e("errorrr", us.getName());
Log.e("errorrr", name);
}
i have a function getInformation() in which i am trying to create an object UserInfo with args from GraphUser.
the problem is that the fbuser become null and i have NullPointerException
as you can see i set a variable 'name' which is string but and with this i have the same problem

Got error 101, "invalid application id" at Android Facebook Logout

I have a class which extends ListFragment. MyloginToFacebook()method (see below) works. But once I want to logout and call logoutFromFacebook(), I receive the following error:
{"error_code":101,"error_msg":"Invalid application ID.","request_args":[{"key":"method","value":"auth.expireSession"},{"key":"format","value":"json"}]}
Here are my methods:
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);
btnFbLogin.setVisibility(View.INVISIBLE);
// Making get profile button visible
btnFbGetProfile.setVisibility(View.VISIBLE);
// Making post to wall visible
btnPostToWall.setVisibility(View.VISIBLE);
// Making show access tokens button visible
btnShowAccessTokens.setVisibility(View.VISIBLE);
btnLogout.setVisibility(View.VISIBLE);
Log.d("FB Sessions", "" + facebook.isSessionValid());
}
if (expires != 0) {
facebook.setAccessExpires(expires);
}
if (!facebook.isSessionValid()) {
facebook.authorize(getActivity(),
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();
// Making Login button invisible
btnFbLogin.setVisibility(View.INVISIBLE);
// Making logout Button visible
btnFbGetProfile.setVisibility(View.VISIBLE);
// Making post to wall visible
btnPostToWall.setVisibility(View.VISIBLE);
// Making show access tokens button visible
btnShowAccessTokens.setVisibility(View.VISIBLE);
btnLogout.setVisibility(View.VISIBLE);
}
#Override
public void onError(DialogError error) {
// Function to handle error
}
#Override
public void onFacebookError(FacebookError fberror) {
// Function to handle Facebook errors
}
});
}
}
//---------------------------//
public void logoutFromFacebook() {
mAsyncRunner.logout(getActivity(), 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
btnFbLogin.setVisibility(View.VISIBLE);
// making all remaining buttons invisible
btnFbGetProfile.setVisibility(View.INVISIBLE);
btnPostToWall.setVisibility(View.INVISIBLE);
btnShowAccessTokens.setVisibility(View.INVISIBLE);
btnLogout.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) {
}
});
}
I just wonder if the cause of the problem is extends ListFragment, because when I tried with extends Activity, it runs well.
Would someone out there help me out to solve this problem? any helps would be appreciated.
Thank you

Facebook integration on Android fbconnect broken link

I am trying to implement Facebook integration into my Android app and it goes off and logs in to Facebook fine, but when it tries to pass the access token back to the app it just returns:
The webpage at fbconnect://success#access_token=[ACCESS TOKEN]
might be temporarily down or it may have moved permanently to a new
web address.
Obviously where [ACCESS TOKEN] is a long sequence of chars.
I have got the App ID correct and added the key hash to facebook. But what process could I have missed?
Code:
public class FacebookActivity extends Activity {
private static final String APP_ID = "[MY APP ID]";
private static final String[] PERMISSIONS = new String[] {"publish_stream"};
private static final String TOKEN = "access_token";
private static final String EXPIRES = "expires_in";
private static final String KEY = "facebook-credentials";
private Facebook facebook;
private String messageToPost;
public boolean saveCredentials(Facebook facebook) {
Editor editor = getApplicationContext().getSharedPreferences(KEY, Context.MODE_PRIVATE).edit();
editor.putString(TOKEN, facebook.getAccessToken());
editor.putLong(EXPIRES, facebook.getAccessExpires());
return editor.commit();
}
public boolean restoreCredentials(Facebook facebook) {
SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences(KEY, Context.MODE_PRIVATE);
facebook.setAccessToken(sharedPreferences.getString(TOKEN, null));
facebook.setAccessExpires(sharedPreferences.getLong(EXPIRES, 0));
return facebook.isSessionValid();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
facebook = new Facebook();
restoreCredentials(facebook);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_facebook);
String facebookMessage = getIntent().getStringExtra("facebookMessage");
if (facebookMessage == null){
facebookMessage = "Test wall post";
}
messageToPost = facebookMessage;
if (! facebook.isSessionValid()) {
loginAndPostToWall();
}
else {
postToWall(messageToPost);
}
}
public void loginAndPostToWall(){
facebook.authorize(this, APP_ID, PERMISSIONS, new LoginDialogListener());
}
public void postToWall(String message){
Bundle parameters = new Bundle();
parameters.putString("message", message);
parameters.putString("description", "topic share");
try {
facebook.request("me");
String response = facebook.request("me/feed", parameters, "POST");
Log.d("Tests", "got response: " + response);
if (response == null || response.equals("") ||
response.equals("false")) {
showToast("Blank response.");
}
else {
showToast("Message posted to your facebook wall!");
}
finish();
} catch (Exception e) {
showToast("Failed to post to wall!");
e.printStackTrace();
finish();
}
}
class LoginDialogListener implements DialogListener {
#Override
public void onComplete(Bundle values) {
saveCredentials(facebook);
if (messageToPost != null){
postToWall(messageToPost);
}
}
public void onFacebookError(FacebookError error) {
showToast("Authentication with Facebook failed!");
finish();
}
public void onError(DialogError error) {
showToast("Authentication with Facebook failed!");
finish();
}
public void onCancel() {
showToast("Authentication with Facebook cancelled!");
finish();
}
}
private void showToast(String message){
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
}
}
New to Android development so I'm sure it's something simple.
I updated the native facebook app on the device and everything works.
Seems like the native Facebook App must be version 2 or higher. I am seeing the same issue for 1.9.6 version, and upgrading the Facebook app solves the issue.

Categories

Resources