Android: How to post update on Facebook wall automatically? - android

I want my android application to automatically post a preset message when the user click on a button. The preset message will be set by the user, so I am guessing that is not a violation of Facebook policies. How do I do this?

private static final String[] PERMISSIONS =
new String[] {"publish_stream", "read_stream", "offline_access"};
Facebook authenticatedFacebook = new Facebook(APP_ID);
postButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
authenticatedFacebook.authorize(Tests.this, PERMISSIONS,
new TestPostListener());
}
});
public class TestPostListener implements DialogListener {
public void onComplete(Bundle values) {
try {
Log.d("Tests", "Testing request for 'me'");
String response = authenticatedFacebook.request("me");
JSONObject obj = Util.parseJson(response);
Log.d("Tests", "Testing graph API wall post");
Bundle parameters = new Bundle();
parameters.putString("message", "Amit Siddhpura");
parameters.putString("description", "Hi Mr. Amit Siddhpura");
response = authenticatedFacebook.request("me/feed", parameters,
"POST");
Log.d("Tests", "got response: " + response);
} catch (Throwable e) {
e.printStackTrace();
}
}
public void onCancel() {
}
public void onError(DialogError e) {
e.printStackTrace();
}
public void onFacebookError(FacebookError e) {
e.printStackTrace();
}
}

You have to create Application on Facebook
And get authenticate from user, then you can get a access_token to post some message through Graph API
I think your application have to request extended permissions : publish_stream, offline_access
There is Facebook-Android-SDK source code on github, you can refer it.
http://developers.facebook.com/docs/guides/mobile

http://www.androidpeople.com/android-facebook-api-example-using-fbrocket/

Related

invite friends to facebook app - android, no invitations sent

I have created a facebook event with my android coding and now I want to invite friends to it.
Below is my code to invite friends:
private void inviteFriends()
{
try
{
Bundle params = new Bundle();
params.putString("title", "invite friends");
params.putString("message", "come join us!");
facebook.dialog(this, "apprequests", params, new DialogListener() {
#Override
public void onComplete(Bundle values) {}
#Override
public void onFacebookError(FacebookError error) {}
#Override
public void onError(DialogError e) {}
#Override
public void onCancel() {}
public void onComplete(String response, Object state)
{
try
{
JSONObject eventResponse = new JSONObject(response);
//event_id = event.getString("id");
Log.i(TAG, "Event Response => "+eventResponse);
Log.w("myapp", friends);
//Toast.makeText(getApplicationContext(), "New Event Created!!", Toast.LENGTH_LONG).show();
}
catch (Exception e)
{
}
}
});
}
catch (Exception e)
{
}
}
The code works up to selecting friends, the title and message comes with the friend list. I can send the invitation but no notifications are sent to selected people.
Please tell me what needs to be done. Thank you in advance!
this image.
Have you turned on the App omn Facebbok Tab in your app developer setting like this.
If don't then it will not sent notification to your friends.

Post the comment on any wall of Facebook in Android

I am using Facebook sdk, (https://github.com/facebook/facebook-android-sdk/) to show the NewsFeed. I can be show the all newsfeed wall in my application.
Now I need to send the comment on the any wall which is visible by me. And how I can be like the wall and the comment through my application. Can anybody plz help me in this?
Thanks in advance.
To be clear:
you can only comment on posts (not the actual wall itself)
you can only like a comment or post (not the actual wall itself)
Using the Facebook SDK you can do the following for comments:
Facebook facebook = new Facebook(APP_ID);
String commentText = "I love blu-ray";
String postId = "7568536355_333422146668093"; //a lifehacker post about blu-ray
String graphPath = postId + "/comments";
Bundle params = new Bundle();
params.putString("message", commentText);
facebook.request(graphPath, params, "POST");
... and the following for likes:
Facebook facebook = new Facebook(APP_ID);
String postId = "7568536355_333422146668093"; //a lifehacker post about blu-ray
String graphPath = postId + "/likes";
facebook.request(graphPath, new Bundle(), "POST");
You can parse all feeds using graph api by passing
mAsyncRunner.request("me/home", params, new graphApiRequestListener());
it returns you json data with all your post and comments and likes
you can parse that data get all commnets
for further information search for hackbook for android example
You should get familiar with Facebook Android SDK usage of Graph API, Post object (comments connection) and Comment Object Graph API documentation (likes section).
You can't comment on the wall itself but on one of the posts.
You can post on the wall via Graph API
You can comment on post via Graph API
You can create likes for both Posts and Comments via Graph API
Update:
Example below about creating comment and liking it (samples of how to create comment for post and like the post already shown in other answer to this question):
// I assume you already have post_id (which is constructed from USERID_MESSAGEID)
Facebook mFacebook = new Facebook(APP_ID);
Bundle params = new Bundle();
params.putString("message", "This is a comment text");
String comment_id = facebook.request(post_id + "/comments", params, "POST");
// Once you have comment_id it can be used for liking it.
facebook.request(comment_id + "/likes", new Bundle(), "POST");
'Use Facebook Api as library download api and use it as library'
private static final String FACEBOOK_APPID = "Your Api key";
Facebook facebook = new Facebook(FACEBOOK_APPID);
facebook.authorize(this,new String[] { "user_photos,publish_checkins,publish_actions,publish_stream" },
new DialogListener() {
#Override
public void onComplete(Bundle values) {
postImageonWall();
try {
facebook.logout(TestActivity.this);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// finish();
}
#Override
public void onFacebookError(FacebookError error) {
}
#Override
public void onError(DialogError e) {
}
#Override
public void onCancel() {
}
use postImageOnWall method
public void postImageonWall() {
byte[] data = null;
Bitmap bi = BitmapFactory.decodeFile(filepath);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bi.compress(Bitmap.CompressFormat.JPEG, 100, baos);
data = baos.toByteArray();
AsyncFacebookRunner mAsyncRunner = new AsyncFacebookRunner(facebook);
mAsyncRunner.request(null, params, "POST", new RequestListener() {
#Override
public void onMalformedURLException(MalformedURLException e,
Object state) {
Log.d("MalformedURLException", e.getMessage());
}
#Override
public void onIOException(IOException e, Object state) {
Log.d("onIOException", e.getMessage());
}
#Override
public void onFileNotFoundException(FileNotFoundException e,
Object state) {
Log.d("FileNotFoundException", e.getMessage());
}
#Override
public void onFacebookError(FacebookError e, Object state) {
Log.d("onFacebookError", e.getMessage());
}
#Override
public void onComplete(String response, Object state) {
Log.d("onComplete", response);
}
}, null);
}

Post text to Facebook Wall

Im develop a app to post a simple text to facebook.here is the code I'm using..
Bundle parameters = new Bundle();
parameters.putString("message", msgWillPost);
response = mFacebook.request("me/feed", parameters, "POST");
it work... but the problem I'm facing now is when the "msgWillPost" length too longer, then it will return error. here is the error:
{"error":{"type":"OAuthException","message":"(#1) An unknown error occurred"}}
which I get return from response.
May I konw isn't Facebook request have any limit character to post? or it was other issue. Thank you.
P/S: sorry about my english hope u guys understand what I'm talking about.
Thanks.
Regards,
WynixToo
btnLogin.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
facebook.authorize(FbdemoActivity.this, new String[]{ "user_photos,publish_checkins,publish_actions,publish_stream"},new DialogListener() {
#Override
public void onComplete(Bundle values) {
}
#Override
public void onFacebookError(FacebookError error) {
}
#Override
public void onError(DialogError e) {
}
#Override
public void onCancel() {
}
});
}
});
public void postOnWall(String msg) {
Log.d("Tests", "Testing graph API wall post");
try {
String response = facebook.request("me");
Bundle parameters = new Bundle();
parameters.putString("message", msg);
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();
}
add permission in authorize method
I know status updates must be less than 420 characters. Have you tried 419 characters to make sure that post succeeds?
If this is really the issue (which is weird that the error message isn't very helpful), then you'll probably want to do input validation in your app prior to posting to Facebook.

Why does my android facebook sdk give a

i am trying to publish something on my wall. i am using this code, called by OnClickListener of a Button
public void postOnWall(String msg) {
mFacebook.authorize(this,new String[] {"publish_stream", "read_stream", "offline_access"},
new DialogListener() {
public void onError(DialogError e) {
}
public void onFacebookError(FacebookError e) {
}
public void onCancel() {
}
public void onComplete(Bundle values) {
}
}
);
Log.d("Tests", "Testing graph API wall post");
try {
Bundle parameters = new Bundle();
parameters.putString("message", msg);
parameters.putString("description", "test test test");
String 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();
}
}
The response string however reads
{"error":{"type":"OAuthException","message":"An active access token must be used to query information about the current user."}}
Also, the Dialog that should be requesting permissions never stays. it starts loading, but then dissapears.
It seems like you haven't properly authenticated the user.
I'm not sure if you just left out that part of your code or you're not doing it at all but I would take a look at the example provided with the API.

Post on Facebook wall using Facebook Android SDK without opening dialog box

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

Categories

Resources