Android: post an image on facebook - android

I'm trying to create an android app that automatically sends an image on the facebook wall of the user. I've read a lot of examples on the net (also from this site) but apparently nothing seems to work for me. This is my code:
class FacebookConnection extends AsyncTask<String, String, String> {
private Exception exception;
private Facebook facebook;
private static String APP_ID = "574586632609202"; // Replace your App ID here
Activity activity;
public FacebookConnection(Activity activity)
{
this.activity = activity;
}
private void login()
{
facebook = new Facebook(APP_ID);
facebook.authorize(activity, new String[]{ "user_photos,publish_checkins,publish_actions,publish_stream"},
new DialogListener() {
#Override
public void onComplete(Bundle values) {
}
#Override
public void onFacebookError(FacebookError error) {
}
#Override
public void onError(DialogError e) {
}
#Override
public void onCancel() {
}
});
}
protected String doInBackground(String... path) {
login();
Bundle parameters = new Bundle();
parameters.putString("message", "ciao");
Bitmap bi = BitmapFactory.decodeFile(path[0]);
AsyncFacebookRunner mAsyncRunner = new AsyncFacebookRunner(facebook);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bi.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
parameters.putByteArray("picture", byteArray);
String response = null;
try {
facebook.request("me");
response = facebook.request("me/feed", parameters, "POST");
} catch (MalformedURLException e) {
return e.getMessage();
} catch (IOException e) {
return e.getMessage();
}
if (response == null || response.equals(""))
return "No Response..";
else
return "Message has been posted to your walll!";
}
protected void onPostExecute(String mess) {
show("DONE", mess);
}
}
NB: i use that class in the main activity on button click, i pass my main activity as parameter. The method "show" just write in a message box the string passed as parameter.
It seems that the login is ok, but when i check my facebook wall, nothing has changed.
Thank you for your help!!!

SOLVED:
I've solved my problem!!! Here is the full code:
public class FacebookConnector {
Facebook facebook;
Context context;
Activity activity;
Handler mHandler;
String[] permissions;
String path;
public FacebookConnector(String appId, Activity activity, String[] permissions) {
this.facebook = new Facebook(appId);
this.activity = activity;
this.permissions=permissions;
this.mHandler = new Handler();
}
public void setImagePath(String path) {
this.path = path;
}
public void login() {
facebook.authorize(this.activity, this.permissions, Facebook.FORCE_DIALOG_AUTH, new DialogListener() {
#Override
public void onCancel() {
Toast.makeText(activity, "Canceled", Toast.LENGTH_SHORT).show();
}
#Override
public void onComplete(Bundle values) {
postImageonWall();
Toast.makeText(activity, "Image Posted on Facebook.", Toast.LENGTH_SHORT).show();
}
#Override
public void onError(DialogError error) {
Toast.makeText(activity, "Error", Toast.LENGTH_SHORT).show();
}
#Override
public void onFacebookError(FacebookError fberror) {
Toast.makeText(activity, "Facebook Error", Toast.LENGTH_SHORT).show();
}
});}
public void postImageonWall() {
byte[] data = null;
Bitmap bi = BitmapFactory.decodeFile(path);
//Bitmap bi = BitmapFactory.decodeResource(getResources(), R.drawable.icon);
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);
AsyncFacebookRunner mAsyncRunner = new AsyncFacebookRunner(facebook);
mAsyncRunner.request(null, params, "POST", new SampleUploadListener(), null);
}
public void execute() {
login();
}
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) {
}
}
}
Of course you have to call the setImagePath method before to call the execute!
Greetings
Francesco

Related

android get facebook username and id

i have very strange situetion. I 'm working facebook sdk in android. i wrote login code and also can check username and user id.but this code does not working when divice hase facebook application(i uninstalled it and then worked perfect)
this is a my code
public void LoginFacebook() {
mFacebook.authorize(this, mPermissions, new LoginDialogListener());
}
private final class LoginDialogListener implements DialogListener {
public void onComplete(Bundle values) {
SessionStore.save(mFacebook, getApplicationContext());
getProfileInformation();
}
public void onCancel() {
SessionEvents.onLoginError("Action Canceled");
}
#Override
public void onFacebookError(FacebookError error) {
SessionEvents.onLoginError(error.getMessage());
}
#Override
public void onError(DialogError error) {
SessionEvents.onLoginError(error.getMessage());
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
}
#SuppressLint("SdCardPath")
public void getProfileInformation() {
mAsyncRunner.request("me", new BaseRequestListener() {
#SuppressLint("CommitPrefEdits")
#Override
public void onComplete(String response, Object state) {
final String json = response;
runOnUiThread(new Runnable() {
#Override
public void run() {
try {
JSONObject profile = new JSONObject(json);
facebook_userid = profile.getString("id");
facebook_username = profile.getString("name");
facebook_username = facebook_username.replace(
"%20", " ");
editor.putString("fb_name", facebook_username);
editor.putString("fb_id", facebook_userid);
fb_name.setText(facebook_username);
getFacebookAvatar(facebook_userid);
editor.commit();
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
#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) {
}
});
}
i have no idea what is a wrong.
if anyone knows solution please help me thanks
Enable Client Deep Linking,Single Sign On and in advance tab OAuth Login from devlopers.facebook.com
You Can Do Like This.
public static void getuserdata() throws JSONException {
String Facebook = readT("https://graph.facebook.com/me?access_token="+mFacebook.getAccessToken()+"&fields=id,username)".replace(" ","%20"));
try
{
JSONObject jsonobj = new JSONObject(Facebook);
fb_id = jsonobj.getString("id");
fb_username = fb_fname+" "+fb_lname;
Log.e("..fb_username..........", fb_username);
}
catch (JSONException e)
{
e.printStackTrace();
}
}

facebook event create in android

Following is the code that I did to create a facebook event, however this code does not work, no compile or run time errors. I have written the method and called the method on button click event.
public class createEvent extends Activity implements OnClickListener
{
private Button btnCreateEven;
private TextView txteventName;
private AsyncFacebookRunner mAsyncRunner;
private String eventID="";
private Facebook facebookatEventCreate;
private String eventName = "";
private SharedPreferences mPrefs;
private static String appId = "392736034134808";
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.create_event);
//problem - unable to start activity when setListeners() is uncommented
initialize();
setListeners();
}
private void initialize()
{
//facebook = new Facebook(APP_ID);
facebookatEventCreate = new Facebook(appId);
mAsyncRunner = new AsyncFacebookRunner(facebookatEventCreate);
btnCreateEven = (Button) findViewById(R.id.btn_createEvent);
txteventName = (TextView)findViewById(R.id.txt_eventName);
}
private void setListeners()
{
btnCreateEven.setOnClickListener(this);
}
#Override
public void onClick(View v)
{
switch (v.getId())
{
case R.id.btn_createEvent:
createEvents();
default:
break;
}
}
/**
* Creates a new event.
*
*
*
*/
private void createEvents()
{
try
{
Bundle params = new Bundle();
params.putString("name", "test test test");
params.putString("start_time", "2013-12-02T18:00:00+0530");
params.putString("end_time", "2013-12-02T20:00:00+0530");
params.putString("description", "This is test description 10/12/2012");
params.putString("location", "Mount Lavinia");
//params.putString("location_id", "");
params.putString("privacy_type", "OPEN");
params.putString("picture", "/sdcard/cmd.png");
mAsyncRunner.request("me/events", params, "POST", new RequestListener()
{
#Override
public void onMalformedURLException(MalformedURLException e, Object state)
{
}
#Override
public void onIOException(IOException e, Object state)
{
}
#Override
public void onFileNotFoundException(FileNotFoundException e, Object state)
{
}
#Override
public void onFacebookError(FacebookError e, Object state)
{
}
#Override
public void onComplete(String response, Object state)
{
try
{
JSONObject event = new JSONObject(response);
eventID = event.getString("id");
Log.d("createEvent:createEvent", "Event ID->" + eventID);
//Toast.makeText(getApplicationContext(), "New Event Created!!", Toast.LENGTH_LONG).show();
}
catch (Exception e)
{
}
}
}, null);
}
catch (Exception e)
{
}
}
}
Please tell me the reason for this, any comments are welcome!
I don't see you authenticating the user anywhere. You can read about how to do that here: Facebook Authentication for Android
If you've already authenticated the user, you need to save the auth token for when you create a new Facebook object. You can readd the access token using:
facebookatEventCreate.setAccessToken(authToken);
facebookatEventCreate.setAccessExpires(unixTime);

Encountering Facebook SDK Error

I'm creating app that has share button on Facebook and I'm getting an error:
This Page Contains the following errors:
error on line 2 at column 182: Entityref: expecting ';'
Below is a rendering of the page up to the first error.
I don't get this error when I run the app on the Emulator. I'm only getting this kind of error when I run the app on the device.
What is the possible cause of this error?
Your help is highly appreciated. Thanks!
Code below is sample code for Facebook SDK:
public class FacebookShare extends Activity
{
private String APP_ID, APP_SECRET, Name, Link, Description, Picture;
private int fbTYPE;
private Facebook facebook;
private AsyncFacebookRunner mAsyncRunner;
private Activity ctx;
private Bitmap bitmap;
SharedPreferences mPrefs;
public FacebookShare(Activity ctx)
{
APP_ID = "...obfuscated...";
facebook = new Facebook(APP_ID);
mAsyncRunner = new AsyncFacebookRunner(facebook);
this.ctx = ctx;
}
public void shareFB(int TypeOfSharing)
{
APP_ID = "...obfuscated...";
facebook = new Facebook(APP_ID);
mAsyncRunner = new AsyncFacebookRunner(facebook);
this.fbTYPE = TypeOfSharing;
loginToFacebook();
}
public void loginToFacebook()
{
Log.v("debugging", "Entered Login to facebook");
String access_token = mPrefs.getString("access_token", "");
long expires = mPrefs.getLong("access_expires", 0);
if (!access_token.equals(""))
{
facebook.setAccessToken(access_token);
Log.v("Access Token", facebook.getAccessToken());
}
if (expires != 0)
{
facebook.setAccessExpires(expires);
}
if (!facebook.isSessionValid())
{
Log.v("debugging", "Session is Invalid");
facebook.authorize(ctx, new String[]{
"email","publish_stream"
}, facebook.FORCE_DIALOG_AUTH, new DialogListener()
{
public void onCancel()
{
// Function to handle cancel event
}
public void onComplete(Bundle values)
{
// Function to handle complete event
// Edit Preferences and update facebook acess_token
SharedPreferences.Editor editor = mPrefs.edit();
editor.putString("access_token", facebook.getAccessToken());
editor.putLong("access_expires", facebook.getAccessExpires());
editor.commit();
if (fbTYPE == 1)
{
postToWall();
}
else if (fbTYPE == 0)
{
postToWall(getBitmap());
}
}
public void onError(DialogError error)
{
Log.v("debugging", error.getMessage());
}
public void onFacebookError(FacebookError fberror)
{
Log.v("debugging", fberror.getMessage());
}
});
Log.v("debugging", "Passed from authorization");
}
else
{
if (fbTYPE == 1)
{
Log.v("debugging", "Entered Post to facebook");
postToWall();
}
else if (fbTYPE == 0)
{
Log.v("debugging", "Entered Post image to facebook");
postToWall(getBitmap());
}
}
}
public void clearCredentials()
{
try
{
facebook.logout(ctx);
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
public void postToWall()
{
// post on user's wall.
Bundle params = new Bundle();
params.putString("description", getDescription());
params.putString("picture", getPicture());
params.putString("name", getName());
params.putString("link", getLink());
facebook.dialog(ctx, "feed", params, new DialogListener()
{
public void onFacebookError(FacebookError e)
{
}
public void onError(DialogError e)
{
}
public void onComplete(Bundle values)
{
Toast.makeText(ctx, "Thanks for sharing JOLENPOP", Toast.LENGTH_SHORT).show();
}
public void onCancel()
{
// Login_Activity.asyncFBLogin fblogin = null;
// fblogin.execute();
}
});
}
public void postToWall(Bitmap bmImage)
{
Log.v("debugging", "entered postToWall(bitmap)");
byte[] data = null;
Bitmap bm = Bitmap.createBitmap(bmImage);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(CompressFormat.JPEG, 100, baos);
data = baos.toByteArray();
Bundle params = new Bundle();
params.putString("method", "post");
params.putString("message", getDescription());
params.putByteArray("image", data);
try
{
String response = facebook.request("me");
response = facebook.request("me/photos", params, "POST");
if (response == null || response.equals("") || response.equals("false"))
{
Log.v("response String", response);
return;
}
else if (response.toLowerCase().contains("error"))
{
Log.v("response String", response);
return;
}
}
catch (Exception e)
{
return;
}
Toast.makeText(ctx, "Your photo has been successfuly published!", Toast.LENGTH_LONG).show();
}
public void getProfileInformation()
{
mAsyncRunner.request("me", new RequestListener()
{
public void onComplete(String response, Object state)
{
Log.d("Profile", response);
String json = response;
try
{
JSONObject profile = new JSONObject(json);
// getting name of the user
String name = profile.getString("name");
// getting email of the user
String email = profile.getString("email");
runOnUiThread(new Runnable()
{
public void run()
{
// Toast.makeText(getApplicationContext(), "Name: " + name
// + "\nEmail: " + email, Toast.LENGTH_LONG).show();
}
});
}
catch (JSONException e)
{
e.printStackTrace();
}
}
public void onIOException(IOException e, Object state)
{
}
public void onFileNotFoundException(FileNotFoundException e, Object state)
{
}
public void onMalformedURLException(MalformedURLException e, Object state)
{
}
public void onFacebookError(FacebookError e, Object state)
{
}
});
}
/**
* setters
* */
public void setFacebook(Facebook facebook)
{
this.facebook = facebook;
}
public void setAsyncRunner(AsyncFacebookRunner mAsyncRunner)
{
this.mAsyncRunner = mAsyncRunner;
}
public void setPrefs(SharedPreferences mPrefs)
{
this.mPrefs = mPrefs;
}
public void setName(String val)
{
this.Name = val;
}
public void setLink(String val)
{
this.Link = val;
}
public void setBitmap(Bitmap val)
{
this.bitmap = val;
}
public void setDescription(String val)
{
this.Description = val;
}
public void setPicture(String val)
{
this.Picture = val;
}
/**
* getters
* */
public String getAppID()
{
return this.APP_ID;
}
public String getName()
{
return this.Name;
}
public String getLink()
{
return this.Link;
}
public String getDescription()
{
return this.Description;
}
public String getPicture()
{
return this.Picture;
}
public Bitmap getBitmap()
{
return this.bitmap;
}
}
Here how I used it:
fbShare = new FacebookShare(this);
mPrefs = PreferenceManager.getDefaultSharedPreferences(this);
then;
Bitmap screenshot = this.glSurfaceView.mRenderer.screenCapture;
fbShare.setName("JOLENPOP");
fbShare.setDescription("I got a score of " + this.glSurfaceView.mRenderer.Score + " in JOLENPOP! Try to beat me!");
fbShare.setBitmap(screenshot);
fbShare.setPrefs(mPrefs);
fbShare.shareFB(0);

Android facebook sdk Profile feed

I am Facebook sdk newbie , i need to create a apps
I know how to post to wall, check in , get friend ,
But i don't know how to get Profile feed (Wall) and friend feed
Need to use Graph API ??
But i don't understand Graph API how to use
With Facebook popup:
public void share(String day, String points)
{
Bundle params = new Bundle();
params.putString("name", XXXXXXXX);
params.putString("caption", XXXXXXXX);
params.putString("link", XXXXXXXX);
params.putString("description",XXXXXXXX);
facebook.dialog(this, "stream.publish",params , new WallPostDialogListener());
}
class WallPostDialogListener implements DialogListener
{
public void onComplete(Bundle values)
{
if(data.facebook == true)
{
Log.e("SHARE",values.toString());
if(values.getString("post_id")!=null)
{
}
}
}
public void onFacebookError(FacebookError e)
{
Log.d("PostToWall","Facebook Error");
}
public void onError(DialogError e)
{
Log.d("PostToWall","Dialog error");
}
public void onCancel()
{
Log.d("PostToWall","Cancel");
}
}
and without the Facebook dialog:
Bundle parameters = new Bundle();
parameters.putString("name", XXXXXXXX);
parameters.putString("message", XXXXXXXX);
parameters.putString("link", XXXXXXXX);
response = facebook("me/feed", parameters, "POST");
Try: https://developers.facebook.com/docs/reference/api/
For example:
(I don't know if this works)
Bundle parameters = new Bundle();
response = facebook("me/feed", parameters, "GET");
JSONObject feeds = new JSONObject();
try
{
feeds = new JSONObject(response);
}
catch(JSONException e)
{}
or:
AsyncFacebookRunner mAsyncRunner = new AsyncFacebookRunner(facebook);
mAsyncRunner.request("me/feed", new FeedsRequestListener());
private class FeedsRequestListener implements RequestListener
{
#Override
public void onComplete(String response, Object state)
{
try
{
JSONObject json = Util.parseJson(response);
}
catch (JSONException e)
{
Log.e("OnComplete","JSONException");
}
catch (FacebookError e)
{
Log.e("OnComplete","FacebookError");
}
}
#Override
public void onIOException(IOException e, Object state)
{
Log.e("FeedsRequest","onIOException " + e.toString());
}
#Override
public void onFileNotFoundException(FileNotFoundException e,Object state)
{
Log.e("FeedsRequest","onFileNotFoundException " + e.toString());
}
#Override
public void onMalformedURLException(MalformedURLException e,Object state)
{
Log.e("FeedsRequest","onMalformedURLException " + e.toString());
}
#Override
public void onFacebookError(FacebookError e, Object state)
{
Log.e("FeedsRequest","onFacebookError " + e.toString());
}
}

Not able to login for posting image on my Facebook wall

I am using following code to post image on Facebook wall.
it's working fine.
Problem is --> if the device having Facebook Application i am not able to post image on wall.
-->The device does't having Facebook App. it's working without any problems.
please help me where is the problem.
this is the code i am using here.
public class ShareOnFacebook extends Activity {
private static final String APP_ID = "269876589726953";
private static final String[] PERMISSIONS = new String[] {"publish_stream"};
private static final String TOKEN = "access_token";
private static final String EXPIRES = "expires_in";
private static final String KEY = "facebook-credentials";
private Facebook facebook;
private String messageToPost;
private Bitmap mBitmap;
public boolean saveCredentials(Facebook facebook) {
Editor editor = getApplicationContext().getSharedPreferences(KEY, Context.MODE_PRIVATE).edit();
editor.putString(TOKEN, facebook.getAccessToken());
editor.putLong(EXPIRES, facebook.getAccessExpires());
return editor.commit();
}
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();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mBitmap = CropImage.getBitmapCrop();
facebook = new Facebook(APP_ID);
restoreCredentials(facebook);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.share);
String facebookMessage = getIntent().getStringExtra("facebookMessage");
if (facebookMessage == null){
facebookMessage = "Test wall post";
}
messageToPost = facebookMessage;
}
public void doNotShare(View button){
finish();
}
public void share(View button){
if (! facebook.isSessionValid()) {
loginAndPostToWall();
}
else {
postToWall(messageToPost);
}
}
public void loginAndPostToWall(){
facebook.authorize(this, PERMISSIONS, new LoginDialogListener());
}
public void postToWall(String message) {
// posting image on FB wall
byte[] data = null;
Bitmap bi = mBitmap;
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);
AsyncFacebookRunner mAsyncRunner = new AsyncFacebookRunner(facebook);
mAsyncRunner.request(null, params, "POST", new PhotoUploadListener(), null);
finish();
}
public class PhotoUploadListener extends com.facebook.android.BaseRequestListener {
public void onComplete(final String response, final Object state) {
//dialog.dismiss();
//showToast("Image shared on your facebook wall!");
}
public void onFacebookError(FacebookError error) {
//dialog.dismiss();
Toast.makeText(getApplicationContext(), "Facebook Error: " + error.getMessage(),Toast.LENGTH_LONG).show();
}
}
class LoginDialogListener implements DialogListener {
public void onComplete(Bundle values) {
saveCredentials(facebook);
if (messageToPost != null){
postToWall(messageToPost);
}
}
public void onFacebookError(FacebookError error) {
showToast("Authentication with Facebook failed!");
finish();
}
public void onError(DialogError error) {
showToast("Authentication with Facebook failed!");
finish();
}
public void onCancel() {
showToast("Authentication with Facebook cancelled!");
finish();
}
}
private void showToast(String message){
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
}
}
I am not sure why you have used null here. As far as I know, instead of this,
mAsyncRunner.request(null, params, "POST", new PhotoUploadListener(), null);
it should be something like this,
mAsyncRunner.request("me/photos", params, "POST", new PhotoUploadListener(), null);
And still if your problem exists because of an existing Facebook app in the device, then you might have make the login compulsory.
In this piece of your code,
public void loginAndPostToWall(){
facebook.authorize(this, PERMISSIONS, new LoginDialogListener());
}
do this change,
public void loginAndPostToWall(){
facebook.authorize(this, PERMISSIONS, Facebook.FORCE_DIALOG_AUTH, new LoginDialogListener());
}
It should do the trick.
Small Changes in the code (facebook package)
Look into authorize function in facebook.java file. try to comment out the singlesignon and use startdialog() only.Hope it helps.

Categories

Resources