Setting text in facebook statuc from native android application - android

I am trying to set text in facebook status from my app, but its not copying in the status dialog box of facebook post dialog box. Dialog box is opening correctly for fb, but message is not copied in the status box. Thanks
My code is :
facebook = new Facebook("my_app_id");
Bundle parameters = new Bundle();
parameters.putString("message", "HI there");
facebook.dialog(this, "feed", parameters,
new PostDialogListener());
PostDialogListener class
public class PostDialogListener implements DialogListener {
#Override
public void onFacebookError(FacebookError e) {
e.printStackTrace();
}
#Override
public void onComplete(Bundle values) {
final String postId = values.getString("post_id");
if (postId != null) {
} else {
}
}
#Override
public void onError(DialogError e) {
e.printStackTrace();
}
#Override
public void onCancel() {
}
}

Try this code and see if it does the job for you. For me it works perfectly because i want to post a custom message.
new Thread(){
public void run(){
Looper.prepare();
Bundle parameters = new Bundle();
parameters.putString("message", "your_message_here");
parameters.putString("caption", "your_caption");
try {
mFacebook.request("me");
String response = mFacebook.request("me/feed", parameters, "POST");
Log.d("Tests", "got response: " + response);
if (response == null || response.equals("")
|| response.equals("false") || response.startsWith("{\"error\"")) {
mActivity.runOnUiThread(failRunnable);
} else {
mActivity.runOnUiThread(successRunnable);
}
} catch (Exception e) {
showToast("Failed to post to wall!");
e.printStackTrace();
}
}
}.start();
mFacebook is my Facebook Object.

Related

Predefined text directly posted on facebook wall

i am using facebook android sdk provided for facebook i m using their examples-simple provided by them and its working very finely , now on login in fb show a form from fb to post on wall on button click .
but I want to set text directly from code and on button click it directly post the text set by me on fb without calling the wall post form to enter the text and share .
this is my project image conatning all fb related files that i m using and beloow is mu step wise o/p of this project
1.login
after clcik show share form
but after wall post i want to directly upload my post on fb how can i do this and what to change i am not getting any idea i tried but cannot set my predefined text ,how cani directly post on wall without calling the form to share
i have downloaded sdk fron gitstore from this link https://github.com/facebook/facebook-android-sdk/ pls help me thanks in advance
this is my example.java code
mUploadButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Bundle params = new Bundle();
params.putString("method", "photos.upload");
URL uploadFileUrl = null;
try {
uploadFileUrl = new URL(
"http://www.facebook.com/images/devsite/iphone_connect_btn.jpg");
} catch (MalformedURLException e) {
e.printStackTrace();
}
try {
HttpURLConnection conn= (HttpURLConnection)uploadFileUrl.openConnection();
conn.setDoInput(true);
conn.connect();
int length = conn.getContentLength();
byte[] imgData =new byte[length];
InputStream is = conn.getInputStream();
is.read(imgData);
params.putByteArray("picture", imgData);
} catch (IOException e) {
e.printStackTrace();
}
mAsyncRunner.request(null, params, "POST",
new SampleUploadListener(), null);
}
});
mUploadButton.setVisibility(mFacebook.isSessionValid() ?
View.VISIBLE :
View.INVISIBLE);
mPostButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mFacebook.dialog(Example.this, "feed",
new SampleDialogListener());
}
});
mPostButton.setVisibility(mFacebook.isSessionValid() ?
View.VISIBLE :
View.INVISIBLE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode,
Intent data) {
mFacebook.authorizeCallback(requestCode, resultCode, data);
}
public class SampleAuthListener implements AuthListener {
public void onAuthSucceed() {
mText.setText("You have logged in! ");
mRequestButton.setVisibility(View.VISIBLE);
mUploadButton.setVisibility(View.VISIBLE);
mPostButton.setVisibility(View.VISIBLE);
}
public void onAuthFail(String error) {
mText.setText("Login Failed: " + error);
}
}
public class SampleLogoutListener implements LogoutListener {
public void onLogoutBegin() {
mText.setText("Logging out...");
}
public void onLogoutFinish() {
mText.setText("You have logged out! ");
mRequestButton.setVisibility(View.INVISIBLE);
mUploadButton.setVisibility(View.INVISIBLE);
mPostButton.setVisibility(View.INVISIBLE);
}
}
public class SampleRequestListener extends BaseRequestListener {
public void onComplete(final String response, final Object state) {
try {
// process the response here: executed in background thread
Log.d("Facebook-Example", "Response: " + response.toString());
JSONObject json = Util.parseJson(response);
final String name = json.getString("name");
// then post the processed result back to the UI thread
// if we do not do this, an runtime exception will be generated
// e.g. "CalledFromWrongThreadException: Only the original
// thread that created a view hierarchy can touch its views."
Example.this.runOnUiThread(new Runnable() {
public void run() {
mText.setText("Hello there, " + name + "!");
}
});
} catch (JSONException e) {
Log.w("Facebook-Example", "JSON Error in response");
} catch (FacebookError e) {
Log.w("Facebook-Example", "Facebook Error: " + e.getMessage());
}
}
}
public class SampleUploadListener extends BaseRequestListener {
public void onComplete(final String response, final Object state) {
try {
// process the response here: (executed in background thread)
Log.d("Facebook-Example", "Response: " + response.toString());
JSONObject json = Util.parseJson(response);
final String src = json.getString("src");
// then post the processed result back to the UI thread
// if we do not do this, an runtime exception will be generated
// e.g. "CalledFromWrongThreadException: Only the original
// thread that created a view hierarchy can touch its views."
Example.this.runOnUiThread(new Runnable() {
public void run() {
mText.setText("Hello there, photo has been uploaded at \n" + src);
}
});
} catch (JSONException e) {
Log.w("Facebook-Example", "JSON Error in response");
} catch (FacebookError e) {
Log.w("Facebook-Example", "Facebook Error: " + e.getMessage());
}
}
}
public class WallPostRequestListener extends BaseRequestListener {
public void onComplete(final String response, final Object state) {
Log.d("Facebook-Example", "Got response: " + response);
String message = "<empty>";
try {
JSONObject json = Util.parseJson(response);
message = json.getString("lithe Technologies");
} 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 + "helloooo lithe";
Example.this.runOnUiThread(new Runnable() {
public void run() {
mText.setText(text);
}
});
}
}
public class WallPostDeleteListener extends BaseRequestListener {
public void onComplete(final String response, final Object state) {
if (response.equals("true")) {
Log.d("Facebook-Example", "Successfully deleted wall post");
Example.this.runOnUiThread(new Runnable() {
public void run() {
mDeleteButton.setVisibility(View.INVISIBLE);
mText.setText("Deleted Wall Post");
}
});
} else {
Log.d("Facebook-Example", "Could not delete wall post");
}
}
}
public class SampleDialogListener extends BaseDialogListener {
public void onComplete(Bundle values) {
final String postId = values.getString("post_id");
if (postId != null) {
Log.d("Facebook-Example", "Dialog Success! post_id=" + postId);
mAsyncRunner.request(postId, new WallPostRequestListener());
mDeleteButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mAsyncRunner.request(postId, new Bundle(), "DELETE",
new WallPostDeleteListener(), null);
}
});
mDeleteButton.setVisibility(View.VISIBLE);
} else {
Log.d("Facebook-Example", "No wall post made");
}
}
}
}
Write below two functions into your Activity.
public void postToWall() {
String message="Good Morning to All";
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();
}
}
2)
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();
}
3)
public void loginAndPostToWall() {
facebook.authorize(this, PERMISSIONS, Facebook.FORCE_DIALOG_AUTH, new LoginDialogListener());
}
Write below code into your wall post button click event
facebook = new Facebook(APP_ID);
restoreCredentials(facebook);
if (!facebook.isSessionValid()) {
loginAndPostToWall();
} else {
postToWall();
}

Facebook SSO , differentiating the login and wall post messages

I have made a sample for posting on Facebook using the basic Facebook library provided at developer.facebook.com and it works just fine with SSO,
btnPostOnFb.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
{
facebook.authorize(FBIntegrationSampleActivity.this, new String[]{ "user_photos,publish_checkins,publish_actions,publish_stream"}, new DialogListener() {
#Override
public void onComplete(Bundle values) {
if(values!=null && values.containsKey("access_token")){
postOnWall("NEW POST from" +count+"Android -Anuj");
Log.e("post on wall", "WALLPOST");
Toast.makeText(getApplicationContext(), "SUCCESSFULLY POSTED MSG ON WALL", Toast.LENGTH_SHORT).show();
}else if(values!=null)
Log.e("LOGINE SUCCESS", "LOGIN SUCCESS");
Toast.makeText(getApplicationContext(), "SUCCESSFULLY LOGGED IN", Toast.LENGTH_SHORT).show();
}
#Override
public void onFacebookError(FacebookError error) {
Log.e("onFBERROR", "ONFBERROR");
}
#Override
public void onError(DialogError e) {
Log.e("on DESI ERROR", "ON_ERROR");
}
#Override
public void onCancel() {
Log.e("onCANCEL", "ONCANCEL");
}
});
}
}
});
Which successfully posts on the Facebook wall, what i want is, I need to show the user that he has successfully signed in, and a message would be posted there after.
The Issue i face is the onComplete(Bundle values) method is called for both successful login and for successful post, how can i differentiate between both of them, is there a key in the Bundle values that can help to find the differnence?
Any suggestions are welcome.
Problem is that you are using for Authentication and Posting. No need to do like this :
For Authentication use
facebook.authorize(a, PERMISSIONS,-1,new LoginListener());
And for posting :
1) Without Dialog facebook.request(parameters)
2) With Dialog
facebook.dialog(this,"stream.publish",parameters,new TestUiServerListener());
public class TestUiServerListener implements DialogListener {
public void onComplete(Bundle values) {
final String postId = values.getString("post_id");
if (postId != null) {
new AsyncFacebookRunner(ZValues.authenticatedFacebook).request(postId,new TestPostRequestListener());
} else {
Post_Message_Title.this.runOnUiThread(new Runnable() {
public void run() {
}
});
}
}
public void onCancel() {
}
public void onError(DialogError e) {
e.printStackTrace();
}
public void onFacebookError(FacebookError e) {
e.printStackTrace();
}
}
public class TestPostRequestListener implements RequestListener {
public void onComplete(final String response, final Object state) {
try {
JSONObject json = Util.parseJson(response);
String postId = json.getString("id");
this.runOnUiThread(new Runnable() {
public void run() {
successLoginShowDialog(); // Dialog after Login succeeds
}
});
} catch (Throwable e) {
}
}
public void onFacebookError(FacebookError e, final Object state) {
e.printStackTrace();
}
public void onFileNotFoundException(FileNotFoundException e,
final Object state) {
e.printStackTrace();
}
public void onIOException(IOException e, final Object state) {
e.printStackTrace();
}
public void onMalformedURLException(MalformedURLException e,
final Object state) {
e.printStackTrace();
}
}
Just create a method successLoginShowDialog() and show whatever you want ,
If Post is success , In TestPostRequestListener below Thread will be called , so do all stuffs in this Thread :
this.runOnUiThread(new Runnable() {
public void run() {
successLoginShowDialog(); // Dialog after Login succeeds
}
});
to postOnWall() you can get its response:
public void postToWall(String message) {
Bundle parameters = new Bundle();
parameters.putString("message", message);
parameters.putString("description", "topic share");
try {
fbObj.request("me");
String response = fbObj.request("me/feed", parameters, "POST");
Log.d("Tests", "got response: " + response);
if (response == null || response.equals("")
|| response.equals("false")) {
// showToast("Blank response.");
Toast.makeText(context, "blank response", Toast.LENGTH_SHORT)
.show();
} else {
// showToast("Message posted to your facebook wall!");
Toast.makeText(context,
"Message posted to your facebook wall!",
Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
// showToast("Failed to post to wall!");
e.printStackTrace();
}
}

Adding content to facebook feed from Android app

I made a little example for posting messages to facebook feed via Android app.
It works great but i just want to add more content to the post like the facebook page's icon, a link and more stuff..
How can i add these parameters to my facebook dialog to post them as well?
public class MainActivity extends Activity
{
Facebook facebook = new Facebook("Here i got my app id.");
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Posting my message, maybe here i could add paramterers like icon and a link etc..?
facebook.dialog(MainActivity.this, "feed", new PostDialogListener());
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
facebook.authorizeCallback(requestCode, resultCode, data);
}
public abstract class BaseDialogListener implements DialogListener {
#Override
public void onFacebookError(FacebookError e) {
e.printStackTrace();
}
#Override
public void onError(DialogError e) {
e.printStackTrace();
}
#Override
public void onCancel() {
}
}
public class PostDialogListener extends BaseDialogListener {
#Override
public void onComplete(Bundle values) {
final String postId = values.getString("post_id");
if (postId != null) {
ki("Message posted on the wall.");
} else {
ki("No message posted on the wall.");
}
}
}
}
private void publishPhoto(String imageURL) {
Log.d("FACEBOOK", "Post to Facebook!");
try {
JSONObject attachment = new JSONObject();
attachment.put("message", Utils.s(R.string.fb_message));
attachment.put("name", Utils.s(R.string.fb_name));
attachment.put("href", Utils.s(R.string.url_dotzmag));
attachment.put("description", Utils.s(R.string.fb_description));
JSONObject media = new JSONObject();
media.put("type", "image");
media.put("src", imageURL);
media.put("href", Utils.s(R.string.url_dotzmag));
attachment.put("media", new JSONArray().put(media));
JSONObject properties = new JSONObject();
JSONObject prop1 = new JSONObject();
prop1.put("text", "Dotz App on Android Market");
prop1.put("href", Utils.s(R.string.url_android_market));
properties.put("Get the App for free", prop1);
JSONObject prop2 = new JSONObject();
prop2.put("text", "Dotz Tuning on Facebook");
prop2.put("href", Utils.s(R.string.url_facebook_fanpage));
properties.put("Visit our fanpage", prop2);
attachment.put("properties", properties);
Log.d("FACEBOOK", attachment.toString());
Bundle params = new Bundle();
params.putString("attachment", attachment.toString());
mFacebook.dialog(mActivity, "stream.publish", params, new PostPhotoDialogListener());
//mAsyncRunner.request("me/feed", params, "POST", new WallPostRequestListener(), null);
} catch (JSONException e) {
Log.e("FACEBOOK", e.getLocalizedMessage(), e);
}
}
public class PostPhotoDialogListener extends BaseDialogListener {
public void onComplete(Bundle values) {
final String postId = values.getString("post_id");
if (postId != null) {
Log.d("FACEBOOK", "Dialog Success! post_id=" + postId);
Toast.makeText(mActivity, "Successfully shared on Facebook!", Toast.LENGTH_LONG).show();
/*
mAsyncRunner.request(postId, new WallPostRequestListener());
mDeleteButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mAsyncRunner.request(postId, new Bundle(), "DELETE",
new WallPostDeleteListener(), null);
}
});
*/
} else {
Log.d("FACEBOOK", "No wall post made");
}
}
}

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