17

Using the Facebook SDK, I can login and store my access_token into a database. When I try to create a post, the Facebook wall is still empty on both my phone and emulator due to these problems:

1) I fetch an access_token from the database and pass the access_token to Facebook, but I'm not allowed to post on a wall.

2) I cannot post my message without opening a dialog box.

   mPostButton.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                String message = "Post this to my wall";

                Bundle params = new Bundle();             

                params.putString("message", message);

                mAsyncRunner.request("me/feed", params, "POST", new WallPostRequestListener());

            }
        });

 public class WallPostRequestListener extends BaseRequestListener {

        public void onComplete(final String response) {
            Log.d("Facebook-Example", "Got response: " + response);
            String message = "<empty>";
            try {
                JSONObject json = Util.parseJson(response);
                message = json.getString("message");
            } catch (JSONException e) {
                Log.w("Facebook-Example", "JSON Error in response");
            } catch (FacebookError e) {
                Log.w("Facebook-Example", "Facebook Error: " + e.getMessage());
            }
            final String text = "Your Wall Post: " + message;
            Example.this.runOnUiThread(new Runnable() {
                public void run() {
                    mText.setText(text);
                }
            });
        }
    }

How can I post to Facebook without opening the dialog box?

RoShamBo
  • 41
  • 4
Ankit
  • 1,148
  • 3
  • 15
  • 31
  • It seems to be so easy, but I tryed the code of Ankit and get the following error: 02-02 16:52:58.672: WARN/Bundle(6774): Key access_token expected byte[] but value was a java.lang.String. The default value was returned. Why? –  Feb 10 '11 at 02:20
  • It seems you have not restored Access_Token and Token_Exprires values in Facebook Object before doing **response = mFacebook.request("me/feed", parameters,"POST");** so the solution towards your problem could be, **SessionStore.restore(mFacebook, this);** (method given in facebook example with filename SessionStore) Or else **FacebookObject.setAccessToken(restore access_token provided by Facebook);FacebookObject.setAccessExpires(restore access_expires provided by facebook);** – Ankit Feb 10 '11 at 02:20

5 Answers5

37

i applied following code and could successfully posted my message on wall.

public void postOnWall(String msg) {
        Log.d("Tests", "Testing graph API wall post");
         try {
                String response = mFacebook.request("me");
                Bundle parameters = new Bundle();
                parameters.putString("message", msg);
                parameters.putString("description", "test test test");
                response = mFacebook.request("me/feed", parameters, 
                        "POST");
                Log.d("Tests", "got response: " + response);
                if (response == null || response.equals("") || 
                        response.equals("false")) {
                   Log.v("Error", "Blank response");
                }
         } catch(Exception e) {
             e.printStackTrace();
         }
    }
Ankit
  • 1,148
  • 3
  • 15
  • 31
  • 1
    Yet i m looking for a solution to make post on a wall, from another activity as when i try to post message on wall from other activities it gives me an error, of handling message and all. – Ankit Dec 07 '10 at 12:15
  • I found solution for this as well, i just restored my facebook session from the page i want to make posts, by calling "SessionStore.restore(mFacebook, this);" (method given in facebook example with filename SessionStore) – Ankit Dec 15 '10 at 07:15
  • 1
    Hi Ankit, Can you tell me how are you authorizing the user before calling this function. I tried creating a facebook object passing the application id, and then calling the authorize function, the login box appears but after logging in, nothing happens – Mako Jan 22 '11 at 07:57
  • **mFb.authorize(this, new String[] {"publish_stream", "read_stream", "offline_access"},new LoginDialogListener());** which provides me AccessToken, TokenExpire Value which i m storing in sharedPreferences then after i have created a Facebook object in an AsyncTask, and by restoring those AccessToken and expire values in Facebook Object i am able to accomplish above task in any activity of my Android Application. – Ankit Jan 24 '11 at 06:42
  • Thank you for your code, works great. I have been experimenting on the emulators and my real phone. It always seems to keep me logged in. Why is it necessary to store token info in Shared Preferences? Is it only necessary when requesting offline_access? Thankyou for your time. – Mel Feb 10 '11 at 02:19
  • 1). Shared Preference is just a way to store, u can store token info into sqlite database as well and later at the time of making posts u can restore token info into facebook object and make posts 2). No, to store token info is required to make posts on wall and to fulfill other tasks, its not that u require it for offline_access only. Technically it is for server to identify request coming from and authenticate as well. – Ankit Feb 10 '11 at 02:19
  • I want to post msg on my face book wall. I tried your coding but i am getting following error "Key message expected byte[] but value was a java.lang.String. The default value was returned". Can you help me solve my problems. – David Feb 18 '11 at 17:22
  • Hi david, i really tried to solve this error: 1). i did **Bundle parameters = new Bundle(); parameters.putByteArray("message", msg.getBytes());** right then it gave me error for access_token expected in Byte[], and it was sending blank message on wall. I even tried to modify facebook code in SDK but didn't succeeded. so at last i just kept above logic in try catch block and it was sending my message successfully.. So u jst try it or if u haven't restored access_token and expire value in facebook object then read my above comments.. u would be able to post message on wall.. – Ankit Feb 19 '11 at 05:43
  • Thanks Ankit, where i need to put Try, Catch block .. still i am getting error. – David Feb 25 '11 at 13:28
  • If u are using this solution/answer then u already using try, catch block, which is mentioned above in answer after Log.d() statement, if not then put it within one. Now try one more solution in above code just add few more lines **SessionStore.restore(mFacebook, this);(if u r using facebook example given with SDK)**, if not then after successful login i hop u would be storing access_token and token_expire value from facebook object, restore them in facebook obj, put those lines in starting of the function. **FbObj.setAccessToken(restore from db);FbObj.setAccessExpires(restore from db);** – Ankit Feb 26 '11 at 12:26
  • Hi, Can any one Please share complete code. I try all but getting errors. – Arslan Anwar Jul 16 '11 at 09:50
  • Hi @Arslan.. Whole code for posting a message on wall or u talking about whole facebook code.. and If u talking about code for posting a message on wall then this is what u need to put to post on a wall.. But u will need to get restore access token and expired value in ur facebook object before making a call... like i have suggested above.. – Ankit Jul 21 '11 at 07:29
  • `System.err(8980): android.os.NetworkOnMainThreadException` while running your code. – Deepak Aug 16 '12 at 08:00
  • I again would like to write here, always use thread or async task while communicating with servers / web services as it blocks your UIThread, so it is but obvious to throw an error / sometimes block your UI or black out the screen. My code was just to make post on wall, how you use it, its your logic. – Ankit Aug 17 '12 at 05:24
  • I think that post Android SDK 9 (HoneyComb) you can't make network calls on the main thread, which is why you get the NetworkOnMainThreadException. Use the asyncrunner class in the facebook "hackbook" example project. It already has methods that run new Threads to make your facebook requests. – dell116 Sep 01 '12 at 04:06
  • got response: {"error":{"message":"An active access token must be used to query information about the current user.","type":"OAuthException","code":2500}} – Prasad Dec 15 '14 at 12:00
  • Is this still relevant? Also what is `mFacebook` referring to? – Conner Leverett Nov 20 '16 at 02:16
7

I updated my tutorial at http://www.integratingstuff.com/2010/10/14/integrating-facebook-into-an-android-application/ and it is now exactly answering this question. It is based on and basically the same as Ankit's answer, but guides people from start to finish through implementing the whole process.

Integrating Stuff
  • 5,253
  • 2
  • 33
  • 39
2

Well it's not that something gets posted on wall without informing user. When user allows your application, then the Android Facebook sdk presents another page, where there is a text that your applications sends, and a textBox where user can write on his wall, similar to the screenshot i have attached

The actual layout on mobile device is slightly different, but it's in the same format. This process is well shown in the sample examples of facebook android sdk.

Now check the question asked in this post:

Facebook Connect Android -- using stream.publish @ http://api.facebook.com/restserver.php'>Facebook Connect Android -- using stream.publish @ http://api.facebook.com/restserver.php

In that question look for these : postParams.put(), similar type of lines will be there in some of your JAVA files. These are the lines using which you can post the data to Facebook.

For example:

postParams.put("user_message", "TESTING 123");

is the message,

postParams.put("attachment", "{\"name\":\"Facebook Connect for Android\",\"href\":\"http://code.google.com/p/fbconnect-android/\",\"caption\":\"Caption\",\"description\":\"Description\",\"media\":[{\"type\":\"image\",\"src\":\"http://img40.yfrog.com/img40/5914/iphoneconnectbtn.jpg\",\"href\":\"http://developers.facebook.com/connect.php?tab=iphone/\"}],\"properties\":{\"another link\":{\"text\":\"Facebook home page\",\"href\":\"http://www.facebook.com\"}}}");

is the line where you are providing icon for application, description,caption, title etc.

alt text

Community
  • 1
  • 1
viv
  • 6,158
  • 6
  • 39
  • 54
  • Hey viv, thanks for replying. But than how would i handle this as in my application, when user clicks on particular button ,after authenticating him with facebook, something should be posted on his wall without prompting him. – Ankit Nov 18 '10 at 12:34
  • I am not able to get this window .. should I design this window... or if there is any procedure then plz let me know.. thank's – kamal_tech_view Jul 06 '12 at 05:37
  • @kamal_tech_view : There is a new method for this. Open a dialg, check this : https://developers.facebook.com/docs/reference/androidsdk/dialog/ , then use following parameters , check this : https://developers.facebook.com/docs/reference/dialogs/feed/ – viv Jul 07 '12 at 14:18
1

I used Ankit's code for posting on facebook wall but his code give me error android.os.NetworkOnMainThreadException.

After searching on this problem a solution told me that put your code in AsyncTask to get rid out of this problem. After modified his code it's working fine for me.

The modified code is looks like:

public class UiAsyncTask extends AsyncTask<Void, Void, Void> {

    public void onPreExecute() {
        // On first execute
    }

    public Void doInBackground(Void... unused) {
        // Background Work
         Log.d("Tests", "Testing graph API wall post");
         try {
                String response = facebook.request("me");
                Bundle parameters = new Bundle();
                parameters.putString("message", "This test message for wall post");
                parameters.putString("description", "test test test");
                response = facebook.request("me/feed", parameters, "POST");
                Log.d("Tests", "got response: " + response);
                if (response == null || response.equals("") || response.equals("false")) {
                   Log.v("Error", "Blank response");
                }
         } catch(Exception e) {
             e.printStackTrace();
         }
        return null;
    }

    public void onPostExecute(Void unused) {
         // Result
    }
}
Deepak
  • 1,989
  • 1
  • 18
  • 20
  • Thanks Deepak, you should always work with threads / async task while communicating with web services / servers, so indirectly making posts on wall or twit on twitter should be done using thread. Thanks for pointing this. – Ankit Aug 17 '12 at 05:19
1

This class helps me for sent messages on my Facebook wall WITHOUT dialog:

public class FBManager{

  private static final String FB_ACCESS_TOKEN = "fb_access_token";
  private static final String FB_EXPIRES = "fb_expires";

  private Activity context;
  private Facebook facebookApi;

  private Runnable successRunnable=new Runnable(){
    @Override
    public void run() {
        Toast.makeText(context, "Success", Toast.LENGTH_LONG).show();
    }
  };    

  public FBManager(Activity context){

    this.context = context;

    facebookApi = new Facebook(FB_API_ID);

    facebookApi.setAccessToken(restoreAccessToken());

  } 

  public void postOnWall(final String text, final String link){
    new Thread(){
        @Override
        public void run(){
            try {
                Bundle parameters = new Bundle();
                parameters.putString("message", text);
                if(link!=null){
                    parameters.putString("link", link);
                }
                String response = facebookApi.request("me/feed", parameters, "POST");
                if(!response.equals("")){
                    if(!response.contains("error")){
                        context.runOnUiThread(successRunnable);                     
                    }else{
                        Log.e("Facebook error:", response);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }.start();     
  }


  public void save(String access_token, long expires){
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
    Editor editor=prefs.edit();
    editor.putString(FB_ACCESS_TOKEN, access_token);
    editor.putLong(FB_EXPIRES, expires);
    editor.commit();
  }

  public String restoreAccessToken(){
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
    return prefs.getString(FB_ACCESS_TOKEN, null);      
  }

  public long restoreExpires(){
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
    return prefs.getLong(FB_EXPIRES, 0);        
  } 

}

valerybodak
  • 4,195
  • 2
  • 42
  • 53