user2611073
user2611073

Reputation: 77

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.

Upvotes: 1

Views: 8320

Answers (3)

Ayan Bhattacharyya
Ayan Bhattacharyya

Reputation: 16

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.... :-)

Upvotes: 0

user1952459
user1952459

Reputation:

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!

Upvotes: 1

droideckar
droideckar

Reputation: 1067

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

Upvotes: 0

Related Questions