How can i post message along with Picture using Facebook SDK 3.0 on Android,
The link -> can post small pic with link and all other information.
http://developers.facebook.com/docs/howtos/androidsdk/3.0/feed-dialog/
What i want, is only to post Pic on wall with message, not a link with description ?, i need to post it with message on custom button click.
private void publishStory() {
Session session = Session.getActiveSession();
if (session != null){
List<String> permissions = session.getPermissions();
if (!isSubsetOf(PERMISSIONS, permissions)) {
pendingPublishReauthorization = true;
Session.NewPermissionsRequest newPermissionsRequest = new Session
.NewPermissionsRequest(this, PERMISSIONS);
session.requestNewPublishPermissions(newPermissionsRequest);
return;
}
FileInputStream fis = null;
try {
fis = new FileInputStream(imagepath);
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
Bitmap b = BitmapFactory.decodeStream(fis);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
b.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte[] byteArray = stream.toByteArray();
Bundle postParams = new Bundle();
postParams.putString("message", "Facebook SDK for Android ");
postParams.putByteArray("source",byteArray);
Request.Callback callback= new Request.Callback() {
public void onCompleted(Response response) {
JSONObject graphResponse = response.getGraphObject().getInnerJSONObject();
String postId = null;
try {
postId = graphResponse.getString("id");
} catch (JSONException e) {
Log.i("JSON error ","JSON error "+ e.getMessage());
}
FacebookRequestError error = response.getError();
if (error != null) {
Toast.makeText(getApplicationContext(),error.getErrorMessage(),Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), postId,Toast.LENGTH_LONG).show();
}
}
};
Request request = new Request(session, "me/feed", postParams,HttpMethod.POST, callback);
RequestAsyncTask task = new RequestAsyncTask(request);
task.execute();
}
}
You can use newUploadPhotoRequest() method of the Facebook Request class. Please refer the accepted answer at Post pic on wall with message with Android Facebook SDK 3.0
Related
I am trying to post a photo from an url to the facebook. So, I have a method that converts the image located in the provided url to a bitmap, after that I want to publish the image to the facebook photos of the user. This is my code:
Method that converts image located in a URL to a Bitmap image:
public Bitmap downloadImage(String url) {
Bitmap bm = null;
try {
URL aURL = new URL(url);
URLConnection conn = aURL.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
bm = BitmapFactory.decodeStream(bis);
bis.close();
is.close();
} catch (IOException e) {
Log.e("Hub","Error getting the image from server : " + e.getMessage().toString());
}
return bm;
}
This is where I try to post the image in the facebook:
private void postToFacebook(byte[] data) {
Session session = Session.getActiveSession();
if (session != null) {
Bundle postParams = new Bundle();
postParams.putString("caption", "Teste caption");
postParams.putByteArray("picture", data);
Request.Callback callback = new Request.Callback() {
public void onCompleted(Response response) {
JSONObject graphResponse = response.getGraphObject().getInnerJSONObject();
String postId = null;
try {
postId = graphResponse.getString("id");
} catch (JSONException e) {
Log.i("", "JSON error "+ e.getMessage());
}
FacebookRequestError error = response.getError();
if (error != null) {
Toast.makeText(getContext(), error.getErrorMessage(), Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getContext(), postId, Toast.LENGTH_LONG).show();
}
}
};
Request request = new Request(session, "me/photos", postParams, HttpMethod.POST, callback);
RequestAsyncTask task = new RequestAsyncTask(request);
task.execute();
} else {
Toast.makeText(getContext(), "Not logged", Toast.LENGTH_SHORT).show();
}
But at this line: response.getGraphObject(), I am getting the null pointer exception. I've tried to execute in a background thread, like this:
class ConvertImageTask extends AsyncTask<URL, Integer, byte[]> {
AsyncTask<Params,Progress,Result>
#Override
protected void onPreExecute() {
super.onPreExecute(); // do nothing here
}
#Override
protected byte[] doInBackground(URL... params) {
byte[] data;
Bitmap bi = downloadImage(getPhotoUrl());
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bi.compress(Bitmap.CompressFormat.PNG, 100, baos);
data = baos.toByteArray();
return data;
}
#Override
protected void onPostExecute(byte[] result) {
postToFacebook(result);
}
But the error continues.
How can I fix this?
Thank you!
The pages I've gone through show the "picture" parameter is a URL, not data you can upload from your computer.
To upload a photo I am using:
Request request = Request.newUploadPhotoRequest(Session.getActiveSession(),
BitmapFactory.decodeStream(this.getAssets().open("YourFile.png")),
new Request.Callback(){
#Override
public void onCompleted(Response response) {
FacebookRequestError error = response.getError();
if(error != null){
Log.i(this.getClass().getName(),"Error publishing.");
}else{
JSONObject graphResponse = response.getGraphObject().getInnerJSONObject();
String postId = null;
try {
postId = graphResponse.getString("id");
} catch (JSONException e) {
Log.i("Facebook error", "JSON error " + e.getMessage());
}
//Logged in Succesfully!
}
}
});
Bundle params = request.getParameters();
params.putString("name", "The title for the photo.");
request.setParameters(params);
request.executeAsync();
I am passing a png I have in my assets folder, but you can adapt that part to what you need. Looking at your code it should be straight forward.
private void postToWall(String msg) {
Bundle parameters = new Bundle();
// parameters.putString("method", "stream.publish");
JSONObject attachment = new JSONObject();
try {
byte[] data = null;
Bitmap bi = BitmapFactory.decodeResource(getResources(),
R.drawable.bluerib);
// Bitmap bi =
// BitmapFactory.decodeFile("http://demos.com/LangGuage/medal_1.png");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bi.compress(Bitmap.CompressFormat.JPEG, 30, baos);
data = baos.toByteArray();
// Bundle params = new Bundle();
// params.putByteArray("picture", data);
attachment.put("type", "image");
// attachment.put("picture", data);
attachment.put("name", "LangGuage");
attachment.put("message", msg);
attachment.put("src", "http://demos.com/LangGuage/medal_1.png");
attachment.put("href", "http://www.abc.com");
// attachment.put("href",
// "http://hwsdemos.com/LangGuage/medal_1.png");
parameters.putString(Facebook.TOKEN, facebook.getAccessToken());
parameters.putString("attachment", attachment.toString());
String response = facebook.request("me/photos", parameters, "POST");
System.out.println("----responce" + response);
if (response.contains("Duplicate status message")) {
progressHandler.sendEmptyMessage(1);
resp = 1;
} else if (response == null || response.equals("")
|| response.equals("false") || response.contains("error")) {
Log.d("error", "error response");
} else {
progressHandler.sendEmptyMessage(0);
resp = 0;
}
} catch (Exception e) {
Log.e(TAG, "Posting fail");
e.printStackTrace();
// finish();
}
}
My app is supporting single sign-in for facebook. I don't want to use dialogs.
Whenever I try to post an image and message together in a attachment I catch:
{"error":{"message":"(#324) Requires upload file","type":"OAuthException","code":324}}
See the docs for a photos graph POST request here https://developers.facebook.com/docs/reference/api/user/#photos
Your image data should go into the "source" field, and the only other available fields are "message", "place' and "no_story". The "src", "name", "href" are not valid fields.
I am making a photo gallery app in which I try to load images from asset folder. I'm successful in doing this.
Now I want to share the image(single not multiple) via email, facebook and twitter.
This is where my problem starts.
I'm able to post a plain message via my app but I'm unable to post my image or attach my image with it.
I don't know how to do this. I tried many tutorials but to no help.
You have to upload image first somewhere on the internet, so the Facebook can download it.
here you go it works for me:
final Session session = Session.getActiveSession();
if (session != null){
// check publish permissions here
// if there is no permission request it and return;
//else if there is permission
logMessage("Has permission go on");
final Bundle postParams = new Bundle();
if(File("yourImagePath").exists())
{
byte[] data = null;
File screenShotFile = new File("yourImagePath");
logMessage("getting screenShot here");
FileInputStream fis = new FileInputStream(screenShotFile);
Bitmap bitmap = BitmapFactory.decodeStream(fis);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
data = baos.toByteArray();
postParams.putByteArray("picture", data);
logMessage("added pic as byte array to params");
}
postParams.putString("name", "Post name");
postParams.putString("caption", "caption");
postParams.putString("description", "desc");
postParams.putString("link", "http://www....");
final Request.Callback callback= new Request.Callback() {
public void onCompleted(Response response)
{
FacebookRequestError error;
try {
error = response.getError();
if (error != null)
{
makeToast(error.getErrorMessage());
logMessage(error.getErrorMessage());
}
else
{
// no errors so delete image here
if(screenShotFile != null)
{
screenShotFile.delete();
logMessage("deleted");
screenShotFile = null;
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
logMessage(response.toString());
}
};
Request request = new Request(session, "me/photos", postParams,
HttpMethod.POST, callback);
RequestAsyncTask task = new RequestAsyncTask(request);
task.execute();
logMessage("made feed request check");
}
Here is the code for uploading picture into my facebook :
Bundle parameters = new Bundle();
parameters.putString("message", msg);
byte[] imgData = getImage("http://bandungraos.in/wp-content/resto/1/gallery/kepiting1.jpg");
parameters.putByteArray("picture", imgData);
if (imgData != null) {
try {
String response = facebook.request("me/photos", parameters,"POST");
System.out.println(response);
} catch (IOException e) {
e.printStackTrace();
}
}
.....
private byte[] getImage(String url) {
try {
URL imgUrl = new URL(url);
HttpURLConnection cn = (HttpURLConnection) imgUrl.openConnection();
cn.setDoInput(true);
cn.connect();
int length = cn.getContentLength();
byte[] imgData = new byte[length];
InputStream is = cn.getInputStream();
is.read(imgData);
return imgData;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
I checked that either access token or imgData is not null
There is no error but I can't find the image in my facebook.
Thanks in advance
According to the User object documentation about the Photos connection the image parameter is named "source" and not "picture", have you tried:
Bundle parameters = new Bundle();
parameters.putString("message", msg);
parameters.putByteArray("source", getImage("..."));
I had the same problem and i used this code `
private void upload_FB(Bitmap photo2) {
// TODO Auto-generated method stub
Calendar c = Calendar.getInstance();
String name = c.getTime().toString();
AsyncFacebookRunner fruner = new AsyncFacebookRunner(facebook);
Log.d("adr", mCurrentPhotoPath);
if(photo2!=null && mCurrentPhotoPath!=null){
ByteArrayOutputStream baos = new ByteArrayOutputStream();
photo2.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] bMapArray = baos.toByteArray();
Bundle params = new Bundle();
params.putByteArray("photo",bMapArray);
params.putString("caption", name);
fruner.request("me/photos",params,"POST",new PhotoUploadListener(),null);
}else
Toast.makeText(ctx, "ERROR", Toast.LENGTH_LONG).show();
}
don't forget to add premision photo_upload
`
I wonder if someone know how to upload a video on my wall on facebook using android sdk
I searched a lot but no code works for me.
I tried the facebook android sdk example which called "Hackbook" for uploading an image but I didn't found any detailed tutorial about uploading videos using Android Sdk!
So if some one know how to do that by a snippet of code or something like that, it will be very nice.
Thanks guys.
byte[] data = null;
String dataPath = "/mnt/sdcard/KaraokeVideos/myvideo.3gp";
String dataMsg = "Your video description here.";
Bundle param;
facebook = new Facebook(FB_APP_ID);
AsyncFacebookRunner mAsyncRunner = new AsyncFacebookRunner(facebook);
InputStream is = null;
try {
is = new FileInputStream(dataPath);
data = readBytes(is);
param = new Bundle();
param.putString("message", dataMsg);
param.putByteArray("video", data);
mAsyncRunner.request("me/videos", param, "POST", new fbRequestListener(), null);
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
private void uploadVideo() {
try {
AccessToken accessToken = AccessToken.getCurrentAccessToken();
String title = "My titles";
String description = "My description";
JSONObject jsonObject = new JSONObject();
jsonObject.put("value", "EVERYONE");
byte[] data = readBytes(reversedPath);
GraphRequest request = GraphRequest.newPostRequest(accessToken, "me/videos", null, this);
Bundle params = request.getParameters();
params.putByteArray("video.mov", data);
params.putString("title", title);
params.putString("privacy", jsonObject.toString());
params.putString("description", description);
params.putInt("file_size", data.length);
request.setParameters(params);
request.executeAsync();
progressBarHorizonatl.setVisibility(View.VISIBLE);
} catch (JSONException | IOException e) {
e.printStackTrace();}
}}
public byte[] readBytes(String dataPath) throws IOException {
InputStream inputStream = new FileInputStream(dataPath);
ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len;
while ((len = inputStream.read(buffer)) != -1) {
byteBuffer.write(buffer, 0, len);
}
return byteBuffer.toByteArray();
}