Friday 30 December 2011

How to Update Facebook Status from Android Application?

First Download Facebook Android SDK from github then Create New Project and Write below Code into OnClicklistener of Button.

MainActivity.java

Facebook facebook = new Facebook(APP_ID);
restoreCredentials(facebook);
messageToPost = "Hello Everyone.";
if (!facebook.isSessionValid()) {
            loginAndPostToWall();
} else {
            postToWall(messageToPost);
}


Declare below variables into MainActivity.java

private Facebook facebook;
private String messageToPost;
private static final String APP_ID = "152424051507008";
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";


Add below methods into your MainActivity.java

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();
}

public void loginAndPostToWall() {
    facebook.authorize(this, PERMISSIONS,Facebook.FORCE_DIALOG_AUTH, 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!");
        }
    } catch (Exception e) {
        showToast("Failed to post to wall!");
        e.printStackTrace();
    }
}

class LoginDialogListener implements DialogListener {
    public void onComplete(Bundle values) {
        saveCredentials(facebook);
        if (messageToPost != null) {
            postToWall(messageToPost);
        }
    }

    public void onFacebookError(FacebookError error) {
        showToast("Authentication with Facebook failed!");
    }

    public void onError(DialogError error) {
        showToast("Authentication with Facebook failed!");
    }

    public void onCancel() {
        showToast("Authentication with Facebook cancelled!");
    }
}

private void showToast(String message) {
    Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT)
                .show();
}


Now Run Your Project

Enjoy :-)

You can download complete source code from this link.

Android - Facebook Integration

Don’t forget to provide feedback or follow this blog, if you find this blog is useful.

38 comments:

  1. i'm getting this error:

    Failed to find provider info for com.facebook.katana.provider.AttributionIdProvider

    ReplyDelete
    Replies
    1. Please see my update and download complete source code.

      Delete
    2. is it possible to give update to more than one social network sites in android?








      Delete
  2. Hi....
    this is my first attempt on android app with facebook integration .
    i m also getting the same error , please tell me what should i do to solve this.
    i am eagerly to solve this issue.please help me to get out of this.

    Thanks in advance

    my error as:-
    "Failed to find provider info for com.facebook.katana.provider.AttributionIdProvider"

    ReplyDelete
    Replies
    1. Hello Yogesh,

      Please Download code from above link and put your APP_ID in Main_Activity file and after that if you have any issue then give me your email address i will send you demo application.

      Delete
    2. ajithnair05@gmail.com

      This is my email Address send me the demo app.

      Delete
  3. darjidhruvit@gmail.com can you please send me a demo application i urgently require that cause i have to include this thing into project and i am having error in other code like ,,,solution for Failed to find provider info for com.facebook.katana.provider.AttributionIdProvider

    ReplyDelete
    Replies
    1. Hello Dhruvit,

      You can download source code of this post from below link.

      http://www.mediafire.com/?3n34v50c6p64r4a

      Delete
  4. Hello! Now I'm having this Error: "message": "An active access token must be used to query information about the current user". "type": "OAuthException"..

    ReplyDelete
    Replies
    1. Hello Luz,

      There is some problems in your Access_Token or APP_ID so please check it first.

      Delete
  5. Thanks it is very helpful for me.grate work.

    ReplyDelete
    Replies
    1. Hello Krishna,

      Welcome........

      Delete
  6. error on LoginDialogListener
    new LoginDialogListener());
    say can't resolved

    ReplyDelete
    Replies
    1. Hello,

      You can download source code of this post from below link.

      http://www.mediafire.com/?3n34v50c6p64r4a

      Delete
  7. Thanks to Dipak Keshariya . It is good tutorial . I got a some doubt . how to integrate the code to share with text(message) and image .

    ReplyDelete
  8. hello when i click on log in facebook...it start loading...and then finish application. no option for post

    ReplyDelete
  9. success,but This application in not possible log in of another user.
    please give me idea..........

    ReplyDelete
  10. Hi

    iam not finding any source code on this link:
    http://www.mediafire.com/?3n34v50c6p64r4a

    Please provide me source code link.

    Thanks & Regards
    Pavan.

    ReplyDelete
  11. Whats the app_id,where we will get our app-id

    ReplyDelete
  12. Please upload the source code again as the link is not available now

    ReplyDelete
  13. this app is getting logged in but , post to wall is getting failure, in jellybean.... please resolve this asap

    ReplyDelete
  14. haseeb539@gmail.com can you please send me a demo application

    ReplyDelete
  15. this app is getting logged in but , post to wall is getting failure, in android 4.4

    ReplyDelete
  16. Iam getting "Failed to post to wall!"., please help me ASAP

    ReplyDelete
  17. laxman7489@gmail.com can you please send me a demo application

    ReplyDelete
  18. Am always getting failed to post on wall. What can be the reason. The login credentials and app id are correct. I m new to this. Please explain.

    ReplyDelete
  19. how can update my fb status automatically(without enter username&password.ie,at an emergency case) from an android application

    ReplyDelete
  20. i get message posted successfully toast but nothing is being posted on my wall

    ReplyDelete
  21. Iam getting "Failed to post to wall!"., please help me..And my

    Atulrockstar786@gmail.com This is my email Address send me the demo app.plz and thanx

    ReplyDelete
    Replies
    1. Hi atul...
      had you solved your problem?
      Please help me..

      Delete
  22. Iam getting "Failed to post to wall!". wht m i do plz guide me...

    ReplyDelete
    Replies
    1. This comment has been removed by the author.

      Delete
    2. Hi atul...
      had you solved your problem?
      Please help me..

      Delete
  23. Hi Dipak/All ,

    When i click on post to wall in the emulator through the APK, it crashes saying unfortunately facebook has stopped. When I try to debug , it stops with null point exception on the line " facebook.authorize(this, PERMISSIONS, Facebook.FORCE_DIALOG_AUTH, new LoginDialogListener());"
    Can you please give pointers on fixing this issue ?

    Thanks

    ReplyDelete
    Replies
    1. Hi,
      Even I am also getting the same error:
      E/AndroidRuntime: FATAL EXCEPTION: main
      Process: com.chuckree.tapordie, PID: 18405
      java.lang.NullPointerException
      at com.chuckree.crazy3.GameActivity.loginAndPostToWall(GameActivity.java:683)
      at com.chuckree.crazy3.GameActivity.onClick(GameActivity.java:633)
      at android.view.View.performClick(View.java:4444)
      at android.view.View$PerformClick.run(View.java:18440)
      at android.os.Handler.handleCallback(Handler.java:733)
      at android.os.Handler.dispatchMessage(Handler.java:95)
      at android.os.Looper.loop(Looper.java:136)
      at android.app.ActivityThread.main(ActivityThread.java:5052)
      at java.lang.reflect.Method.invokeNative(Native Method)
      at java.lang.reflect.Method.invoke(Method.java:515)
      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:609)
      at dalvik.system.NativeStart.main(Native Method)

      Delete
  24. Please provide me sample source, Thanks. email: abbaserode@yahoo.com

    ReplyDelete
  25. Hi,
    I get each and every time this toast :- Failed to post to wall!
    why?
    Please help me...

    ReplyDelete

  26. get free robux
    In the event that you are hoping to download Roblox in your Windows/Xbox/Android and iOS then we have the all out arrangement pack directly here. It is exceptionally simple, in the first place. Roblox is one of the most messed around on the Microsoft Store at the present time

    ReplyDelete