Post the comment on any wall of Facebook in Android - 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);
}

Related

Post Photo to Facebook from Android Application, Photo taken from Android Gallery

I am currently developing an Android Application target build is 4.0 Ice-Cream Sandwich.
So far, I am able to post a normal Text onto Facebook with this code:
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() {
}
});
}
However, I am unable to post a photo onto Facebook with Captions. I've search around online and one of the codes I found is this:
public void postToWall() {
// post on user's wall.
byte[] data = null;
Bitmap bi = BitmapFactory.decodeFile(photoToPost);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bi.compress(Bitmap.CompressFormat.JPEG, 100, baos);
data = baos.toByteArray();
Bundle params = new Bundle();
params.putString("method", "photos.upload");
params.putByteArray("picture", data);
AsyncFacebookRunner mAsyncRunner = new AsyncFacebookRunner(facebook);
mAsyncRunner.request(null, params, "POST", new SampleUploadListener(), null);
}
The problem is, the above code is not working as I don't know whats:
1.photoToPost
2.mAsyncRunner.request keeps giving me an error stating that I cannot put "null" as it is an invalid arguement
3.SampleUploadListener, supposedly is from the FacebookSDK is not working as well (I keep getting an error to create a Class)
Is there a simpler code out here ? Or could someone explain to me the errors I am experiencing.
I am using an "On Click" so far to post normal Text onto Facebook and it points to this method. My goal is to upload a Photo with a Caption onto Facebook.
Thank you all for helping !
1-This is your photo that will be send to wall , it can be an image from your SD card or anywhere else
2-This a class from Facebook SDK , that accepts facebook object (one u created before)
3-This a class from Facebook SDK again
it seems there is something wrong with your Facebook SDK
try to set it again using Right Click on Project >> Properties >> Android and see if library exist or not
The problem lies in following line
mAsyncRunner.request(null, params, "POST", new SampleUploadListener(), null);
you are passing null as graph path this should be like this = "me/feed"
Update
write this line of code
mAsyncRunner.request("me/feed", params, "POST", new SampleUploadListener(), null);
then it should work.
public class CardShared extends Activity{
public static final String APP_ID = "YOUR APP ID";
private Facebook mFacebook;
private AsyncFacebookRunner mAsyncRunner ;
boolean isLoggedIn = false;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setContentView(R.layout.main);
mFacebook = new Facebook(APP_ID);
mAsyncRunner = new AsyncFacebookRunner(mFacebook);
//Implementing SSO
mFacebook.authorize(this, new String[]{"publish_stream"}, new DialogListener(){
public void onComplete(Bundle values) {
sharePicture(values.getString(Facebook.TOKEN));
Toast.makeText(getApplicationContext(), "Picture Shared Successfully", Toast.LENGTH_SHORT).show();
CardShared.this.finish();
}
public void onFacebookError(FacebookError e) {
Log.d("FACEBOOK ERROR","FB ERROR. MSG: "+e.getMessage()+", CAUSE: "+e.getCause());
}
public void onError(DialogError e) {
Log.e("ERROR","AUTH ERROR. MSG: "+e.getMessage()+", CAUSE: "+e.getCause());
}
public void onCancel() {
Log.d("CANCELLED","AUTH CANCELLED");
}
});
}
//updating Status
public void sharePicture(String accessToken){
byte[] data = null;
try {
Bitmap image = BitmapFactory.decodeResource(getResources(), R.drawable.image_to_be_uploaded);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.JPEG, 100, baos);
data = baos.toByteArray();
Bundle params = new Bundle();
params.putString("method", "photos.upload");
params
.putString(Facebook.TOKEN, mFacebook
.getAccessToken());
params.putByteArray("picture", data);
mAsyncRunner.request(null, params, "POST",
new SampleUploadListener(), null);
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.d("onActivityResult","onActivityResult");
mFacebook.authorizeCallback(requestCode, resultCode, data);
}
public class SampleUploadListener extends BaseRequestListener {
public void onComplete(final String response, final Object state) {
try {
Log.d("Facebook-Example", "Response: " + response.toString());
JSONObject json = Util.parseJson(response);
final String f = json.getString("src");
} catch (JSONException e) {
Log.w("Facebook-Example", "JSON Error in response");
} catch (FacebookError e) {
Log.w("Facebook-Example", "Facebook Error: " + e.getMessage());
}
}
}
}
put like this
mAsyncRunner.request("me/feed", params, "POST", new SampleUploadListener())
See this link. That will show you how to post image on FaceBook wall as how to post text on wall.
Its good to learn.

invalid application id

I am using following code to load an image from android app to facebook. I have installed facebook sdk for android. But the app is not doing the intended. I am getting "invalid application id" in the logcat. What mistake am I making ?
Button mButton=(Button)findViewById(R.id.button);
mButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Facebook mFacebook=new Facebook(yourAppID)
byte[] data = null;
Bitmap bi = BitmapFactory.decodeFile(imageLink);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bi.compress(Bitmap.CompressFormat.PNG, 100, baos);
data = baos.toByteArray();
Bundle params = new Bundle();
params.putString("method", "photos.upload");
params.putByteArray("picture", data);
AsyncFacebookRunner mAsyncRunner = new AsyncFacebookRunner(mFacebook);
mAsyncRunner.request(null, params, "POST",
new SampleUploadListener(), null);
}
});
public class SampleUploadListener extends BaseRequestListener {
#SuppressWarnings("unused")
public void onComplete(final String response, final Object state) {
try {
Log.d("Facebook-Example", "Response: " + response.toString());
JSONObject json = Util.parseJson(response);
String src = json.getString("src");
PublishImage.this.runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(),
"Successfully Uploaded", Toast.LENGTH_SHORT)
.show();
}
});
} catch (JSONException e) {
Log.w("Facebook-Example", "JSON Error in response");
} catch (FacebookError e) {
Log.w("Facebook-Example", "Facebook Error: " + e.getMessage());
}
}
}
public abstract class BaseRequestListener implements RequestListener {
public void onFacebookError(FacebookError e, final Object state) {
Log.e("Facebook", e.getMessage());
e.printStackTrace();
}
public void onFileNotFoundException(FileNotFoundException e,
final Object state) {
Log.e("Facebook", e.getMessage());
e.printStackTrace();
}
public void onIOException(IOException e, final Object state) {
Log.e("Facebook", e.getMessage());
e.printStackTrace();
}
public void onMalformedURLException(MalformedURLException e,
final Object state) {
Log.e("Facebook", e.getMessage());
e.printStackTrace();
}
}
Logcat
06-15 20:00:55.398: W/KeyCharacterMap(629): No keyboard for id 0
06-15 20:00:55.398: W/KeyCharacterMap(629): Using default keymap: /system/usr/keychars/qwerty.kcm.bin
06-15 20:01:02.438: D/dalvikvm(629): GC_EXTERNAL_ALLOC freed 1214K, 59% free 2755K/6599K, external 1995K/2266K, paused 630ms
06-15 20:01:08.998: D/MediaPlayer(629): getMetadata
06-15 20:01:15.529: D/Facebook-Example(629): Response: {"error_code":101,"error_msg":"Invalid application ID.","request_args":[{"key":"method","value":"photos.upload"},{"key":"format","value":"json"}]}
06-15 20:01:15.529: W/Facebook-Example(629): Facebook Error: Invalid application ID.
EDIT: This worked
class ButtonListener1 implements View.OnClickListener{
Facebook facebook=new Facebook(ID);
#Override
public void onClick(View v) {
facebook.authorize(Pic.this, new String[] { "publish_stream" },
new DialogListener() {
#Override
public void onFacebookError(FacebookError e) {
// TODO Auto-generated method stub
}
#Override
public void onError(DialogError dialogError) {
// TODO Auto-generated method stub
}
#Override
public void onComplete(Bundle values) {
postToWall(values.getString(Facebook.TOKEN));
}
private void postToWall(String accessToken) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, baos);
byte[] data = baos.toByteArray();
Bundle bundle = new Bundle();
bundle.putString(Facebook.TOKEN, accessToken);
bundle.putByteArray("facebookPictureData", data);
// The byte array is the data of a picture.
bundle.putByteArray("picture", getIntent().getExtras().getByteArray("data"));
try {
facebook.request("me/photos", bundle, "POST");
} catch (FileNotFoundException fileNotFoundException) {
// makeToast(fileNotFoundException.getMessage());
} catch (MalformedURLException malformedURLException) {
// makeToast(malformedURLException.getMessage());
} catch (IOException ioException) {
// makeToast(ioException.getMessage());
}
}
#Override
public void onCancel() {
// TODO Auto-generated method stub
}
});
}
}
UPDATE:
Here is the link to the Facebook.java class on facebook api reference website:
http://developers.facebook.com/docs/reference/androidsdk/authentication/. Scroll down a few lines to find the authorize method. Are you sure you are using the com.facebook.android.Facebook class from the android sdk and not a class that you might have spun on your own?
The basic auth flow on android apps is as follows:
1. Make an instance of the Facebook class (that you have).
2. Make a call to Facebook.authorize() with the right permissions you need.
3. In the DialogListener call back of the authorize method, you can save the access_token and expiration time for future use.
4. In the activity that you called authorize from, override the "onActivityResult method and if that method is called with Facebook's result code (Facebook.DEFAULT_AUTH_ACTIVITY_CODE), then call Facebook.authorizeCallback with the received intent.
5. After these 4 steps are done, you are free to make graph api requests with Facebook.request() or AsyncFacebookRunner.request(). In these request methods, the first parameter is the graph path you want. So, for example, if you called the request method with path "me", you would get back profile information of the logged in user.
END UPDATE-------
For starters, I think you necessarily need to have the graph path as the first parameter in your code on this line:
mAsyncRunner.request("*********7618/photos", params, "POST",
new SampleUploadListener(), null);
}
});
In my code it is the albumid/photos. Additionally, you need permissions from the user to upload to an album belonging to her. For that, you need to retrieve an access token using Facebook.authorize().
I am not sure I understand why you are getting the error related to the app id being not valid, however, from what I know this are the basic steps you need to do in order to post photos before you post photos.
I am sure someone will post a better answer soon, hope this helps in the meantime.

Android - How to upload photo from the SD card to the Facebook wall

I use the Facebook Android SDK.
Goal
Create multiple posts in news feed of Facebook logged in user that will contain photo from the Android device (its SD card) and some comment. The result should be the same as when you do it using the Add photo/video feature directly in Facebook. In the end, it should look like this:
Wanted Facebook result
Problem
I can't do it.
I went through the numerous similar posts on Stack Overflow, but no answer there so far.
What I have tried to implement so far
Approach 1: SD card photos 2 Facebook album
How
Upload pictures from my mobile (its SD card) to an album that is created for my application the first time I upload a picture from it. In this case, when constructing the params object, I use the picture key and put the bytes of the picture as its value. I use me/photos in the request(...) call of the Facebook (or AsyncFacebookRunner) object. **
The problem
Not all uploaded images are displayed on my wall. Instead, there is something like x photos were added to the album xxx.
The code snippet is this (for one picture)
Bundle params = new Bundle();
params.putString("message", "Uploaded on " + now());
params.putByteArray("picture", bytes); //bytes contains photo bytes, no problem here
asyncRunner.request("me/photos", params, "POST", new PostPhotoRequestListener(), null);
Facebook result
Approach 2: Internet photos 2 facebook news feed
How
Display pictures stored somewhere on the Internet in posts on my wall. In this case, when constructing the params object, I use the link key and set the url to picture as its value. I use me/feed in the request(...) call.
The problem
This produces some strange output, but it isn't what I want.
The code snippet is this (for one picture)
Bundle params = new Bundle();
params.putString("message", "Uploaded on " + now());
params.putString("link", "http://i1114.photobucket.com/albums/k538/tom_rada/bota2.jpg");
asyncRunner.request("me/feed", params, "POST", new PostPhotoRequestListener(), null);
Facebook result
Approach 3: Mix of approach 1 and 2
How
I try to use the picture key and set photo bytes as its value (as in 1.), and call the request with me/feed (as in 2.),
The problem
Message is produced as I would like it to be, but no photo is included
The code snippet is this (for one picture)
Bundle params = new Bundle();
params.putString("message", "Uploaded on " + now());
params.putByteArray("picture", bytes); //bytes contains photo bytes, no problem here
asyncRunner.request("me/feed", params, "POST", new PostPhotoRequestListener(), null);
Facebook result
So, any ideas how I could reach my goal?
EDIT - WORKAROUND FOUND
It seems that the only way to create new posts containing photos on user's wall is to add photos and related comments to user's Wall photos album.
How - Code snippet
Beware: The facebook.request call should be replaced with async call, so the operation doesn't block the UI thread !!!
String wallAlbumID = null;
String response = facebook.request("me/albums");
JSONObject json = Util.parseJson(response);
JSONArray albums = json.getJSONArray("data");
for (int i =0; i < albums.length(); i++) {
JSONObject album = albums.getJSONObject(i);
if (album.getString("type").equalsIgnoreCase("wall")) {
wallAlbumID = album.getString("id");
Log.d("JSON", wallAlbumID);
break;
}
}
... and then
if (wallAlbumID != null) {
Bundle params = new Bundle();
params.putString("message", "Uploaded on " + now());
params.putByteArray("source", bytes);
asyncRunner.request(wallAlbumID+"/photos", params, "POST", new PostPhotoRequestListener(), null);
}
Facebook facebook = new Facebook("your appid");
private void uploadImage()
{
Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.icon);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
final byte[] data = stream.toByteArray();
facebook.authorize(FacebookActivity.this, new String[]{ "user_photos,publish_checkins,publish_actions,publish_stream"},new DialogListener()
{
#Override
public void onComplete(Bundle values)
{
//uploadImageOnlyToWall(data, "Uploading Image only to wall","Test Post from Android while uploading photo with message");
uploadImageToWallAndAlbums(imageUrl, "Image via link");
}
#Override
public void onFacebookError(FacebookError error)
{
Toast.makeText(FacebookActivity.this, "FaceBook Error", Toast.LENGTH_LONG).show();
}
#Override
public void onError(DialogError e)
{
Toast.makeText(FacebookActivity.this, "Error", Toast.LENGTH_LONG).show();
}
#Override
public void onCancel()
{
Toast.makeText(FacebookActivity.this, "Canceled", Toast.LENGTH_LONG).show();
}
});
}
private void uploadImageOnlyToAlbum(byte[] byteArray,String caption)
{
Bundle params = new Bundle();
params.putByteArray("picture", byteArray);
params.putString("caption",caption);
AsyncFacebookRunner mAsyncRunner = new AsyncFacebookRunner(facebook);
mAsyncRunner.request("me/photos", params, "POST", new SampleUploadListener(), null);
}
private void uploadImageToWallAndAlbums(byte[] byteArray,String caption)
{
Bundle params = new Bundle();
params.putString("method", "photos.upload");
params.putByteArray("picture", byteArray);
params.putString("caption", caption);
AsyncFacebookRunner mAsyncRunner = new AsyncFacebookRunner(facebook);
mAsyncRunner.request(null, params, "POST", new SampleUploadListener(), null);
}
If the user has not previously posted a photo on his/her wall (there is no wall photo album), you can use me/photo request to post a photo first. This will automatically create a wall album.
Facebook facebook = new Facebook("your App_id");
private void uploadImage()
{
Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.icon);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
final byte[] data = stream.toByteArray();
facebook.authorize(FacebookActivity.this, new String[]{ "user_photos,publish_checkins,publish_actions,publish_stream"},new DialogListener()
{
#Override
public void onComplete(Bundle values)
{
//uploadImageOnlyToWall(data, "Uploading Image only to wall","Test Post from Android while uploading photo with message");
uploadImageToWallAndAlbums(imageUrl, "Image via link");
}
#Override
public void onFacebookError(FacebookError error)
{
Toast.makeText(FacebookActivity.this, " Error", Toast.LENGTH_LONG).show();
}
#Override
public void onError(DialogError e)
{
Toast.makeText(FacebookActivity.this, "Error", Toast.LENGTH_LONG).show();
}
#Override
public void onCancel()
{
Toast.makeText(FacebookActivity.this, "Canceled", Toast.LENGTH_LONG).show();
}
});
}
private void uploadImageOnlyToAlbum(byte[] byteArray,String caption)
{
Bundle params = new Bundle();
params.putByteArray("picture", byteArray);
params.putString("caption",caption);
AsyncFacebookRunner mAsyncRunner = new AsyncFacebookRunner(facebook);
mAsyncRunner.request("me/photos", params, "POST", new SampleUploadListener(), null);
}
private void uploadImageToWallAndAlbums(byte[] byteArray,String caption)
{
Bundle params = new Bundle();
params.putString("method", "photos.upload");
params.putByteArray("picture", byteArray);
params.putString("caption", caption);
AsyncFacebookRunner mAsyncRunner = new AsyncFacebookRunner(facebook);
mAsyncRunner.request(null, params, "POST", new SampleUploadListener(), null);
}
Add this class on your code
public class SampleUploadListener implements RequestListener{
#Override
public void onMalformedURLException(MalformedURLException e, Object state) {
Log.d(TAG, "******************* FACEBOOK::onMalformedURLException *******************");
}
#Override
public void onIOException(IOException e, Object state) {
Log.d(TAG, "******************* FACEBOOK::onIOException *******************");
}
#Override
public void onFileNotFoundException(FileNotFoundException e, Object state) {
Log.d(TAG, "******************* FACEBOOK::onFileNotFoundException *******************");
}
#Override
public void onFacebookError(FacebookError e, Object state) {
Log.d(TAG, "******************* FACEBOOK::onFacebookError *******************");
}
#Override
public void onComplete(String response, Object state) {
Log.d(TAG, "******************* FACEBOOK::onComplete *******************");
}
}

Android: How to post update on Facebook wall automatically?

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/

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