Got "request failed" while trying to post on facebook's wall - android

I'm using facebook connect with SSO to sign in/up users to my app, and want to ask user to post on wall after each login.
But, at the requestListener's onComplete (Post on wall dialog was shown, and user touched on Share), I'm getting a false response. Didn't find out what it means in the FB SDK docs, but anything was posted on my Wall. Response was supposed to return a JSON formated string, so when trying to execute "message = json.getString("message");", I get a FacebookError witch just prints "request failed"...
logcat:
07-27 12:58:09.170: W/FacebookConnect(26086): Activity Started
07-27 12:58:12.300: W/FacebookConnect(26086): User authorized
07-27 12:58:12.300: E/FacebookConnect(26086): onComplete called at facebook.authorize
07-27 12:58:12.300: E/FacebookConnect(26086): Access Token: AAAC1sJLmgzkBAD0M40SQLgluPU...
07-27 12:58:12.860: D/webviewglue(26086): nativeDestroy view: 0x223888
07-27 12:58:13.420: I/SqliteDatabaseCpp(26086): sqlite returned: error code = 14, msg = cannot open file at line 27701 of [8609a15dfa], db=/data/data/androidhive.dashboard/databases/webview.db
07-27 12:58:13.420: I/SqliteDatabaseCpp(26086): sqlite returned: error code = 14, msg = os_unix.c: open() at line 27701 - "" errno=2 path=/CachedGeoposition.db, db=/data/data/androidhive.dashboard/databases/webview.db
07-27 12:58:14.670: D/SampleRequestListener(26086): Response: {"id":"1123123","name"...
07-27 12:58:14.680: E/FacebookConnect(26086): JSON {"work":[{"position"...
07-27 12:58:17.150: E/SampleDialogListener(26086): Dialog Success! post_id=1003157...
07-27 12:58:17.720: E/WallPostRequestListener(26086): Got response: false
07-27 12:58:17.720: E/WallPostRequestListener(26086): Facebook Error: request failed
My code (Error occurs in class WallPostRequestListener):
public class FacebookConnectActivity extends Activity {
private static final String TAG_JSON = "json";
static Facebook facebook = new Facebook("11111111111111");
AsyncFacebookRunner mAsyncRunner;
private SharedPreferences mPrefs;
JSONObject json;
Context ctx = this;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.resgatar_produto_layout);
Log.w("FacebookConnect", "Activity Started");
mPrefs = getPreferences(MODE_PRIVATE);
String access_token = mPrefs.getString("access_token", null);
long expires = mPrefs.getLong("access_expires", 0);
if(access_token != null) {
facebook.setAccessToken(access_token);
}
if(expires != 0) {
facebook.setAccessExpires(expires);
}
if(!facebook.isSessionValid()) {
facebook.authorize(this, new String[] {"email", "user_photos", "user_birthday", "user_hometown", "user_relationships","user_location", "user_work_history", "publish_actions"}, new DialogListener() {
#Override
public void onComplete(Bundle values) {
Log.w("FacebookConnect", "User authorized");
Log.e("FacebookConnect", "onComplete called at facebook.authorize");
Log.e("FacebookConnect", "Access Token: "+facebook.getAccessToken().toString());
mAsyncRunner = new AsyncFacebookRunner(facebook);
mAsyncRunner.request("me", new SampleRequestListener());
Bundle params = new Bundle();
params.putString("link", "www.qranio.com");
facebook.dialog(ctx, "feed", params, new SampleDialogListener());
}
#Override
public void onFacebookError(FacebookError error) {
Log.w("FacebookConnect", "Error authorizing: "+error.toString());
}
#Override
public void onError(DialogError e) {}
#Override
public void onCancel() {}
});
}
}
public static void logoutFB(){
if(facebook.isSessionValid()){
facebook.setAccessToken(null);
}
}
public void startDataProcess(){
Intent a = new Intent(FacebookConnectActivity.this, FacebookDataProcess.class);
a.putExtra(TAG_JSON, json.toString());
startActivity(a);
finish();
}
public class SampleDialogListener extends BaseDialogListener {
public void onComplete(Bundle values) {
final String postId = values.getString("post_id");
if (postId != null) {
Log.e("SampleDialogListener", "Dialog Success! post_id=" + postId);
mAsyncRunner.request(postId, new WallPostRequestListener());
} else {
Log.e("SampleDialogListener", "No wall post made"); //Usuario clicou em Cancelar
startDataProcess();
}
}
public void onCancel(){ //Usuario clicou no X do dialog
Log.w("FacebookConnect", "Post to Wall Canceled");
startDataProcess();
}
}
public class WallPostRequestListener extends BaseRequestListener {
public void onComplete(final String response, final Object state) {
Log.e("WallPostRequestListener", "Got response: " + response);
String message = "<empty>";
try {
JSONObject json = Util.parseJson(response);
message = json.getString("message");
} catch (JSONException e) {
Log.e("WallPostRequestListener", "JSON Error in response");
} catch (FacebookError e) {
Log.e("WallPostRequestListener", "Facebook Error: " + e.getMessage());
//Toast.makeText(ctx, "Erro ao postar no Facebook.", Toast.LENGTH_LONG).show();
}
//startDataProcess();
}
}
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("SampleRequestListener", "Response: " + response.toString());
json = Util.parseJson(response);
Log.e("FacebookConnect", "JSON " + json.toString());
//startDataProcess();
// 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."
} catch (JSONException e) {
Log.w("Facebook-Example", "JSON Error in response");
} catch (FacebookError e) {
Log.w("Facebook-Example", "Facebook Error: " + e.getMessage());
}
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
facebook.authorizeCallback(requestCode, resultCode, data);
try{
mAsyncRunner = new AsyncFacebookRunner(facebook);
mAsyncRunner.request("me", new SampleRequestListener());
Bundle params = new Bundle();
params.putString("link", "www.qranio.com");
//params.putString("display", "touch");
facebook.dialog(ctx, "feed", params, new SampleDialogListener());
Log.e("FacebookConnect", "Authentication authorizeCallback called (onActivityResult)");
Log.e("FacebookConnect", "Access Token: "+facebook.getAccessToken().toString());
//facebook.
//if (facebook.isSessionValid()){
//}else{
//Log.e("FacebookConnect", "Invalid facebook session while trying to fetch user data");
//}*/
}catch(FacebookError fbe){
Log.e("FacebookConnect", "onActivityResult FacebookError " + fbe.toString());
}catch (Exception e){
Log.e("FacebookConnect", "onActivityResult Exception " + e.toString());
}
}
}

Related

Facebook wall post with text and image

I've been stuck for days looking for a simple tutorial on making a facebook wall post with an icon or image and some text using the graph API. I've tried countless tutorials and they all seem very complicated and I can't get them to work. Even the samples that come with the SDK do not create sessions.
I have been sucessful in setting up the SDK and getting my APP_ID all that is left is the Java code for a custom button to share my app on the users wall.
You can post image on Facebook in two different ways. If you want to post a picture from a URL, you can post it as below:
Bundle parameters = new Bundle();
parameters.putString("description","your description/message");
parameters.putString("link", "your link");
parameters.putString("name", "Name of your application/ any name you want to post");
// parameters.putString("caption", " caption if any!");
parameters.putString("picture", "Link to your image");
try
{
facebook.request("me");
response = facebook.request("me/feed", parameters, "POST");
Log.d("Tests", "got response: " + response);
}
catch (Exception e)
{
e.printStackTrace();
}
or if you want to post an image from SD card, you can create a Bitmap from the image you want to post and then convert it into ByteArray and post it as below:
Bundle parameters = new Bundle();
Log.e("byte array", ""+mByteArray);
parameters.putString("message", "your message");
parameters.putByteArray("picture", mByteArray);
try
{
facebook.request("me");
response = facebook.request("me/photos", parameters, "POST");
Log.d("Tests", "got response: " + response);
}
catch (Exception e)
{
e.printStackTrace();
}
P.S. The first method is to post image on user's Facebook wall, and the latter is for uploading picture with message in user's photo album on Facebook, which will also be posted as an update!
you can post your image with text from your application in a very simply way.
Call this method while clicking on the button widget say btnImagePostToWall like...
btnImagePostToWall.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
postImageToWall();
}
});
Get Profile information by making request to Facebook Graph API....
public void postImageToWall() {
facebook.authorize(
this,
new String[] { "user_photos,publish_checkins,publish_actions,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) {
postImageonWall();
}
#Override
public void onCancel() {
// TODO Auto-generated method stub
}
});
}
private void postImageonWall() {
byte[] data = null;
Bitmap bi = BitmapFactory.decodeResource(getResources(),
R.drawable.ic_launcher);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bi.compress(Bitmap.CompressFormat.JPEG, 100, baos);
data = baos.toByteArray();
Bundle params = new Bundle();
params.putString(Facebook.TOKEN, facebook.getAccessToken());
params.putString("method", "photos.upload");
params.putByteArray("picture", data); // image to post
params.putString("caption", "My text on wall with Image "); // text to post
AsyncFacebookRunner mAsyncRunner = new AsyncFacebookRunner(facebook);
mAsyncRunner.request(null, params, "POST", new SampleUploadListener(),
null);
}
Just create a class SampleUploadListener which implements AsyncFacebookRunner.RequestListener...
class SampleUploadListener implements AsyncFacebookRunner.RequestListener {
#Override
public void onComplete(String response, Object state) {
}
#Override
public void onIOException(IOException e, Object state) {
}
#Override
public void onFileNotFoundException(FileNotFoundException e,
Object state) {
}
#Override
public void onMalformedURLException(MalformedURLException e,
Object state) {
}
#Override
public void onFacebookError(FacebookError e, Object state) {
}
}
Hope this will help you a bit.... :-)
here you go. you may have to do some debugging etc, but this worked for me.
FbLoginActivity class: performs authentication and posts to your wall and/or your app's wall.
usage:
Intent i = new Intent(getApplicationContext(), FbLoginActivity.class);
i.putExtra("SCORE", score);
startActivity(i);
FbLoginActivity:
import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.MalformedURLException;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.widget.Toast;
import com.facebook.android.AsyncFacebookRunner;
import com.facebook.android.AsyncFacebookRunner.RequestListener;
import com.facebook.android.DialogError;
import com.facebook.android.Facebook;
import com.facebook.android.Facebook.DialogListener;
import com.facebook.android.FacebookError;
import com.facebook.android.Util;
public class FbLoginActivity extends Activity {
private final String TAG = "FbLoginActivity";
private String token; // used to identify the fb user
private static final String FACEBOOK_APP_ID = "your_key_here";
//private String[] permissions = { "email", "friends_about_me", "friends_location"};
private String[] permissions = {"publish_stream" };
private String rankText;
public static String userName;
private AlertDialog alertDialog;
private boolean isMyWall = false, isAppWall = true;
// facebook SSO
Facebook fb = new Facebook(FACEBOOK_APP_ID);
private AsyncFacebookRunner runner = new AsyncFacebookRunner(fb);
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.register);
showFbDialog();
SessionEvents.addAuthListener(new SampleAuthListener());
}
private void accessUserData(String token) {
// get information about the currently logged in user
runner.request("me", meRequestListener);
}
private String getRankText() {
String txt = "your text to be shared here"
return txt;
}
private void postToFb() {
// post to feed
Bundle params = new Bundle();
params.putString("to", "me");
params.putString("message", "test msg");
try {
runner.request("me/feed", params, "POST", meRequestListener, null);
} catch(Throwable t) {
Log.e(TAG, "caught throwable: " + t, t);
Toast.makeText(this, "Error on login, is Facebook Installed?", Toast.LENGTH_LONG).show();
startActivity(new Intent(getApplicationContext(), MaleRankingActivity.class));
}
}
public void postImageonWall() {
byte[] data = null;
Bitmap bi = BitmapFactory.decodeFile("/sdcard/viewitems.png");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bi.compress(Bitmap.CompressFormat.JPEG, 100, baos);
data = baos.toByteArray();
Bundle params = new Bundle();
params.putString(Facebook.TOKEN, fb.getAccessToken());
params.putString("method", "photos.upload");
params.putByteArray("picture", data);
AsyncFacebookRunner mAsyncRunner = new AsyncFacebookRunner(fb);
//mAsyncRunner.request(null, params, "POST", new SampleUploadListener(), null);
}
private RequestListener meRequestListener = new RequestListener () {
//called on successful completion of the Request
public void onComplete(final String response, final Object state){
Log.d(TAG, "<onComplete> response: " + response);
try {
JSONObject fbResponse = new JSONObject(response);
// set userName
userName = fbResponse.getString("name");
Log.d(TAG, "<onComplete> fbResponse: " + fbResponse);
} catch (JSONException e) {
Log.e(TAG, "caught exception: " + e, e);
}
}
// called if there is an error
public void onFacebookError(FacebookError error, final Object state){}
public void onMalformedURLException(java.net.MalformedURLException e, Object state){}
public void onFileNotFoundException(FileNotFoundException arg0, Object arg1) {
// TODO Auto-generated method stub
}
public void onIOException(IOException arg0, Object arg1) {
// TODO Auto-generated method stub
}
};
private void authorizeAndPost() {
final Bundle params = new Bundle();
try {
// force authorization
//fb.logout(this);
/*
* Get existing access_token if any
*/
SharedPreferences mPrefs = getPreferences(MODE_PRIVATE);
String access_token = mPrefs.getString("access_token", null);
long expires = mPrefs.getLong("access_expires", 0);
if(access_token != null) {
fb.setAccessToken(access_token);
}
if(expires != 0) {
fb.setAccessExpires(expires);
}
fb.authorize(this, permissions, new DialogListener() {
public void onComplete(Bundle values) {
Log.d(TAG, "<onComplete> entry");
// get rank text
rankText = getRankText();
// set text
params.putString("message", rankText);
// post to ur wall
if (isMyWall) {
runner.request("me/feed", params, "POST", new WallPostRequestListener(), null);
}
// post to rate ur date wall
if (isAppWall) {
runner.request("259166150820823/feed", params, "POST", new WallPostRequestListener(), null);
}
// toast
CharSequence text = "Posted date to Facebook!";
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(getApplicationContext(), text, duration);
toast.show();
// start ranking activity
Intent intent = new Intent(getApplicationContext(), ShareResultActivity.class);
intent.putExtra("share_result", "You have successfully posted your date to Facebook!");
token = fb.getAccessToken();
Log.d(TAG, "<onComplete> fb access token: " + token);
//intent.putExtra("userId", token);
long token_expires = fb.getAccessExpires();
Log.d(TAG, "<onComplete> token expires: " + token_expires);
SharedPreferences prefs= PreferenceManager.getDefaultSharedPreferences(FbLoginActivity.this);
prefs.edit().putLong("access_expires", token_expires).commit();
prefs.edit().putString("access_token", token).commit();
//fb.setAccessExpires(300000); // for testing
// access user data
accessUserData(token);
//postDateToFb();
startActivity(intent);
}
public void onFacebookError(FacebookError e) {
Log.e(TAG, "fb error: " + e.getMessage(), e);
}
public void onError(DialogError e) {
Log.e(TAG, "dialog error: " + e.getMessage(), e);
}
public void onAuthFail(String error) {
Log.d("<fbExample>", "login failed: " + error);
}
public void onCancel() {
Log.d(TAG, "fb cancelled");
}
});
} catch(Throwable t) {
Log.e(TAG, "caught throwable: " + t, t);
Toast.makeText(this, "Error on login, is Facebook Installed?", Toast.LENGTH_LONG).show();
startActivity(new Intent(getApplicationContext(), LandingActivity.class));
}
}
public class WallPostRequestListener extends BaseRequestListener {
public void onComplete(final String response, final Object state) {
Log.d("Facebook-Example", "Got response: " + response);
String message = "I just rated my date a creeper!";
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;
FbLoginActivity.this.runOnUiThread(new Runnable() {
public void run() {
//mText.setText(text);
}
});
}
public void onCancel() {
Log.d(TAG, "fb cancel");
}
public void onComplete(Bundle arg0) {
Log.e(TAG, "fb complete.");
}
public void onError(DialogError arg0) {
Log.e(TAG, "fb err:" + arg0.getMessage());
}
public void onFacebookError(FacebookError arg0) {
Log.e(TAG, "fb err:" + arg0.getMessage());
}
public void onFacebookError(FacebookError arg0, Object arg1) {
Log.e(TAG, "fb err:" + arg0.getMessage());
}
public void onFileNotFoundException(FileNotFoundException arg0,
Object arg1) {
Log.e(TAG, "fb err:" + arg0.getMessage(), arg0);
}
public void onIOException(IOException arg0, Object arg1) {
Log.e(TAG, "fb err:" + arg0.getMessage(), arg0);
}
public void onMalformedURLException(MalformedURLException arg0,
Object arg1) {
Log.e(TAG, "fb err:" + arg0.getMessage(), arg0);
}
}
public class SampleAuthListener implements SessionEvents.AuthListener {
public void onAuthSucceed() {
Log.d("<fbExample>", "fb auth token: " + fb.getAccessToken());
}
public void onAuthFail(String error) {
Log.d("<fbExample>", "login failed: " + error);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
fb.authorizeCallback(requestCode, resultCode, data);
}
private void showFbDialog() {
alertDialog = new AlertDialog.Builder(this)
.setTitle("I want to:")
.setMultiChoiceItems(new String[] {"Post to my wall", "Post to app's wall" },
new boolean[]{false, true, false, true, false, false, false},
new DialogInterface.OnMultiChoiceClickListener() {
public void onClick(DialogInterface dialog, int whichButton,
boolean isChecked) {
/* User clicked on a check box do some stuff */
Log.d(TAG, "multichoice got click, whichButton: " + whichButton + ", isChecked: " + isChecked);
if (whichButton == 0 && isChecked) {
isMyWall = true;
}
if (whichButton == 1 && isChecked) {
isAppWall = true;
} else if (whichButton == 1 && !isChecked) {
isAppWall = false;
}
}
})
.setPositiveButton("Ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
/* User clicked Yes so do some stuff */
Log.d(TAG, "Ok got click");
authorizeAndPost();
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
/* User clicked No so do some stuff */
Log.d(TAG, "Cancel got click");
startActivity(new Intent(getApplicationContext(), YourActivity.class ));
}
})
.create();
alertDialog.show();
}
}

Setting text in facebook statuc from native android application

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.

Android: Facebook SDK - Share Post with description, thumbnail and title

I'm having trouble setting up a simple facebook wall post to the user's wall.
I want a facebook dialog box to pop up on clicking a button with a thumbnail, description and title.
I have tried the following code but no dialog box pops up:
shareOnFacebookBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
/*
* Get existing access_token if any
*/
mPrefs ShopDetailActivity.this.getActivity().getPreferences(Context.MODE_PRIVATE);
String access_token = mPrefs.getString("access_token", null);
long expires = mPrefs.getLong("access_expires", 0);
if(access_token != null) {
facebook.setAccessToken(access_token);
}
if(expires != 0) {
facebook.setAccessExpires(expires);
}
/*
* Only call authorize if the access_token has expired.
*/
if(!facebook.isSessionValid()) {
facebook.authorize(ShopDetailActivity.this.getActivity(),new String[] { "publish_stream" }, new DialogListener() {
#Override
public void onComplete(Bundle values) {
SharedPreferences.Editor editor = mPrefs.edit();
editor.putString("access_token", facebook.getAccessToken());
editor.putLong("access_expires", facebook.getAccessExpires());
editor.commit();
//facebook.dialog(ShopDetailActivity.this.getActivity(), "feed", new SampleDialogListener());
Bundle parameters = new Bundle();
parameters.putString("message", "message");// the message to post to the wall
facebook.dialog(context, "feed", parameters, this);
}
#Override
public void onFacebookError(FacebookError error) {}
#Override
public void onError(DialogError e) {}
#Override
public void onCancel() {}
});
}
}
});
The authorize window opens and after clicking allow I'd expect the dialog box to pop up but it just returns to the app.
What am I doing wrong?
facebook = new Facebook("your facebook id");
mAsyncRunner = new AsyncFacebookRunner(facebook);
facebook.authorize(this, new String[]
{ "publish_stream", "offline_access" }, -1,
new DialogListener()
{
public void onComplete(Bundle values)
{
Log.e("tag", "Values returned by Bundle ====> " + values.toString());
fbImageSubmit();
}
public void onFacebookError(FacebookError error)
{
}
public void onError(DialogError e)
{
}
public void onCancel()
{
}
});
//add method into your class
private void fbImageSubmit()
{
if (fb != null)
{
if (fb.isSessionValid())
{
Bundle b = new Bundle();
b.putString("picture", your image url);
b.putString("caption", title);
b
.putString(
"description",
"test");
b.putString("name", "Hi Friends, I am using the your app name app for Android!");
b.putString("link", "https://market.android.com/details?id="+this.getApplication().getPackageName().toString());
try
{
String strRet = "";
strRet = fb.request("/me/feed", b, "POST");
JSONObject json;
try
{
json = Util.parseJson(strRet);
if (!json.isNull("id"))
{
Log.i("Facebook", "Image link submitted.");
}
else
{
Log.e("Facebook", "Error: " + strRet);
}
} catch (FacebookError e)
{
Log.e("Facebook", "Error: " + e.getMessage());
}
} catch (Exception e)
{
Log.e("Facebook", "Error: " + e.getMessage());
}
}
}
}

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

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

Categories

Resources