Android post picture to Facebook wall - java

I am trying to post a picture to my wall on Facebook. I have managed logging in and posting text to the wall. However, when I try posting the picture, nothing happens.
I am using the Android Facebook SDK.
Here is what I have so far:
Bundle params = new Bundle();
params.putString("method", "photos.upload");
Toast.makeText(FacebookPoster.this, "" + getIntent().getExtras().getByteArray("data").length, Toast.LENGTH_SHORT).show();
params.putByteArray("picture", getIntent().getExtras().getByteArray("data"));
AsyncFacebookRunner mAsyncRunner = new AsyncFacebookRunner(facebook);
mAsyncRunner.request(null, params, "POST", new SampleUploadListener(), null);
The Toast shows 8733, which means the byte array isn't empty
NB. Logcat output some warnings (not errors):
03-02 14:19:29.554: WARN/Bundle(1891): Attempt to cast generated internal exception:
03-02 14:19:29.554: WARN/Bundle(1891): java.lang.ClassCastException: java.lang.String
03-02 14:19:29.554: WARN/Bundle(1891): at android.os.Bundle.getByteArray(Bundle.java:1305)
03-02 14:19:29.554: WARN/Bundle(1891): at com.facebook.android.Util.openUrl(Util.java:155)
03-02 14:19:29.554: WARN/Bundle(1891): at com.facebook.android.Facebook.request(Facebook.java:559)
03-02 14:19:29.554: WARN/Bundle(1891): at com.facebook.android.AsyncFacebookRunner$2.run(AsyncFacebookRunner.java:253)
03-02 14:19:29.584: WARN/Bundle(1891): Key method expected byte[] but value was a java.lang.String. The default value <null> was returned.
(Shows several times underneath each other.)
What am I doing wrong?
SOLVED.
This is what I did to make it work:
facebook.authorize(this, new String[] { "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) {
postToWall(values.getString(Facebook.TOKEN));
}
#Override
public void onCancel() {
// TODO Auto-generated method stub
}
});
And the helper method:
private void postToWall(String accessToken) {
Bundle params = new Bundle();
params.putString(Facebook.TOKEN, accessToken);
// The byte array is the data of a picture.
params.putByteArray("picture", getIntent().getExtras().getByteArray("data"));
try {
facebook.request("me/photos", params, "POST");
} catch (FileNotFoundException fileNotFoundException) {
makeToast(fileNotFoundException.getMessage());
} catch (MalformedURLException malformedURLException) {
makeToast(malformedURLException.getMessage());
} catch (IOException ioException) {
makeToast(ioException.getMessage());
}
}

first thing is that you are not using graph api to upload the pictures... u r using the old rest api... try to use graph api, its simple...
Use following code:
Bundle param = new Bundle();
param.putString("message", "picture caption");
param.putByteArray("picture", ImageBytes);
mAsyncRunner.request("me/photos", param, "POST", new SampleUploadListener());
According to error message, it looks like its giving errors in getting bytes from intent's bundle...

btnLogin.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
facebook.authorize(FbdemoActivity.this, 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() {
}
});
}
});
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, 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 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."
} 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 onFacebookError(FacebookError e, Object state) {
}
}
try this code it will work i had used the same code and uploads the image on Facebook.

Here is the working code sample. Pass image path and message.
public static void postImageonWall(String FilePath,String msg ) {
try {
Bitmap bi = BitmapFactory.decodeFile(FilePath);
AsyncFacebookRunner mAsyncRunner = new AsyncFacebookRunner(facebook);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bi.compress(Bitmap.CompressFormat.PNG, 100, stream); // where bm is bitmap from Sdcard
byte[] byteArray = stream.toByteArray();
Bundle param = new Bundle();
param = new Bundle();
param.putString("message", msg);
param.putString("filename", "Dessert Dash");
param.putByteArray("image", byteArray);
param.putString("caption", "Dessert Dash in Android Market Now");
mAsyncRunner.request("me/photos", param, "POST", fbrq, null);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

private String postwall(String uid)
{
String response = "";
try
{
String DIRECTORY_PATH = "/sdcard/159.jpg";
Bundle params = new Bundle();
Bitmap bitmap = BitmapFactory.decodeFile(DIRECTORY_PATH);
byte[] data = null;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
data = baos.toByteArray();
params.putString("app_id", uid);
params.putString("message", "picture caption");
params.putByteArray("picture", data);
mFacebook.authorize(this, PERMISSIONS, new LoginDialogListener());
mAsyncRunner.request("me/photos", params, "POST", new WallPostRequestListener());
mAsyncRunner.request(response, new WallPostRequestListener());
Log.e("post result", response);
}
catch (Exception e)
{
e.printStackTrace();
}
return response;
}
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;
}
}

I'm sure Facebook will fix this eventually, but for the time being these examples (posted by other users) are very misleading because they do NOT in fact post to the user's wall (in the regular sense). Instead they are added to the user's photo gallery, and then happen to end up on the wall, but not in the same way in which normal posts work... there is no title and no caption and if you add another photo it ends up side by side with the first (rather than as a separate entry). So, when you use the api command me/feed it just fails in a spectacular way where it actually adds a post to the wall but it's an empty post from the application (it even disregards the title and caption).
Hopefully Facebook will fix this sometime in the near term.

Posting the image and Text to Facebook wall from code, Once you logged in using facebook credentials.
note : This is applicable only after logging in to your app using facebook credentials
sharePhotoToFacebook(); //function called from any UI event
private void sharePhotoToFacebook(){
Bitmap bitmap=null;
String path = Environment.getExternalStorageDirectory().getAbsolutePath()+"/Download/";
try {
File file = new File(path, "image9.jpg");
bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
}
catch (Exception e){
Log.e("Error" , " Error in loading file");
}
SharePhoto photo = new SharePhoto.Builder()
.setBitmap(bitmap)
.setCaption("A post from Android code")
.build();
SharePhotoContent content = new SharePhotoContent.Builder()
.addPhoto(photo)
.build();
ShareApi.share(content, null);
Toast.makeText(LoginSuccessActivity.this, "Image posted successfully", Toast.LENGTH_LONG).show();
}

Related

Android Picasso: Method call should happen from the main thread

I am trying to get info from a server, including photos. I have created a class called ServerManager, which allows me to download the desired information. However, I cannot download images with Picasso because I get a java.lang.IllegalStateException: Method call should happen from the main thread..
This is what I am doing in ServerManager:
// Check if the photo is already downloaded
if (!checkInternalPhoto(member)) {
final String outputURL = context.getFilesDir().getAbsolutePath() + "/" + member.photoPath;
String photoURL = rootURL + "photos/" + member.photoPath;
Picasso.with(context)
.load(photoURL)
.into(new Target() {
#Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
File file = new File(outputURL);
try {
file.createNewFile();
FileOutputStream outputStream = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG,100,outputStream);
outputStream.flush();
outputStream.close();
} catch (IOException e) {
Log.e("IOException",e.getLocalizedMessage());
}
}
#Override
public void onBitmapFailed(Drawable errorDrawable) {
}
#Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
}
});
}
What can I do?
Edit: I tried to use the code in my MainActivity and I am getting the same error message...
public void downloadPhotos(List<Member> memberList){
String rootInURL = serverManager.getRootURL();
String rootOutURL = serverManager.getOutputURL();
for(int i = 0; i < memberList.size(); i++){
if(!serverManager.checkInternalPhoto(memberList.get(i))){
final String outputURL = rootOutURL + memberList.get(i).photoPath;
String photoURL = rootInURL + "photos/" + memberList.get(i).photoPath;
Picasso.with(this)
.load(photoURL)
.into(new Target() {
#Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
File file = new File(outputURL);
try{
file.createNewFile();
FileOutputStream outputStream = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG,100,outputStream);
outputStream.flush();
outputStream.close();
Toast.makeText(context, "YEpa: " ,Toast.LENGTH_LONG).show();
} catch (IOException e){
Toast.makeText(context, "Error: " + e.toString(),Toast.LENGTH_LONG).show();
}
}
#Override
public void onBitmapFailed(Drawable errorDrawable) {
}
#Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
}
});
}
}
}
Try this and your error should disappear. This problem always happens when you use it in Unit Android test
kotlin code
Handler(Looper.getMainLooper()).post {
}
java code
new Handler(Looper.getMainLooper()).post(() -> {
});
You can't update an ui element from a different thread than the one which created that ui element. On Android that almost always means the main thread.
What you need to do is send back the photoUrl String to your activity or fragment on the main thread. The traditional way of doing it is by using a Handler. You can read about this more here: https://developer.android.com/training/multiple-threads/communicate-ui.html

Retrieving Facebook Profile Picture

My graphrequest seems to work fine, I have no issue retrieving the User who logs ins Name nor do I have any problem getting their ID. I am trying to store their profile picture for use within my app (By downloading it as a bitmap) but cant seem to succesfully download it. Could someone tell me what I am doing wrong?
//Run the first time we log into Facebook
//connects everything here
private void firstTimeFBlogin() {
GraphRequest request = GraphRequest.newMeRequest(
AccessToken.getCurrentAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(
JSONObject object,
GraphResponse response) {
Log.i("joe", "Heyyyyo");
try {
String userName = response.getJSONObject().getString("name");
String userID = response.getJSONObject().getString("id");
//String hi2 = response.getJSONObject().getString("first_name");
//String hi3 = response.getJSONObject().getString("gender");
final JSONObject mPicture = object.getJSONObject("picture");
final JSONObject mPictureData = mPicture.getJSONObject("data");
final String mImageUrl = mPictureData.getString("url");
Log.i("joe", "User's Facebook Name: " + userName);
Log.i("joe", ParseUser.getCurrentUser().getUsername());
Log.i("joe", mImageUrl);
Log.i("joe", userID);
ParseUser.getCurrentUser().put("name", userName);
ParseUser.getCurrentUser().put("iUrl", mImageUrl);
ParseUser.getCurrentUser().put("fbID", userID);
ParseUser.getCurrentUser().saveInBackground();
profilePictureRetriever(userID);
} catch (JSONException e) {
Log.i("joe", "Couldn't Succesfully retrieve the stuff...");
e.printStackTrace();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,link,picture");
request.setParameters(parameters);
request.executeAsync();
}
public void profilePictureRetriever(String id) {
Log.i("joe", "Profile Picture Checker");
//Bitmap bitmap = getFacebookProfilePicture(id);
//this is here for test purposes
//tried just maually putting the url in..
Bitmap bm = DownloadImageBitmap("https://graph.facebook.com/849993771766163/picture?type=square");
}
public static Bitmap DownloadImageBitmap(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("IMAGE", "Error getting bitmap", e);
}
return bm;
}
}
Is there another/better way to be doing this?
Thanks so much!
I have done something like this:
First you need to call GraphRequest API for getting all the details of user in which API also gives URL of current Profile Picture.
Bundle params = new Bundle();
params.putString("fields", "id,email,gender,cover,picture.type(large)");
new GraphRequest(token, "me", params, HttpMethod.GET,
new GraphRequest.Callback() {
#Override
public void onCompleted(GraphResponse response) {
if (response != null) {
try {
JSONObject data = response.getJSONObject();
if (data.has("picture")) {
String profilePicUrl = data.getJSONObject("picture").getJSONObject("data").getString("url");
Bitmap profilePic = getFacebookProfilePicture(profilePicUrl);
// set profilePic bitmap to imageview
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}).executeAsync();
You can use this method which returns current Profile picture of User from URL which we get from above GraphRequest API.
public static Bitmap getFacebookProfilePicture(String url){
Bitmap bitmap = BitmapFactory.decodeStream(url.openConnection().getInputStream());
return bitmap;
}
I hope it helps!
Update
Pass required parameter in bundle, as id,name,email,gender, birthday,picture is passed in below code.
LoginManager.getInstance().registerCallback(callbackManager,
new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
// App code
GraphRequest request = GraphRequest.newMeRequest(
loginResult.getAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(
JSONObject object,
GraphResponse response) {
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,email,gender, birthday,picture");
request.setParameters(parameters);
request.executeAsync();
}
#Override
public void onCancel() {
Log.e(TAG, "Cancel");
}
#Override
public void onError(FacebookException exception) {
Log.e(TAG, "Error");
Log.e(TAG, exception.toString());
}
});
Old Answer
get it by calling
graph.facebook.com/<FB UserId>/picture?type=large
following code is put after login success.
GraphRequest request = GraphRequest.newMeRequest(loginResult.getAccessToken(),new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object,GraphResponse response) {
Log.d("info",object.toString()+"");
String id = object.getString("id");
String profilePic ="http://graph.facebook.com/"+id+"/picture";
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,first_name,last_name,age_range,gender,locale,timezone,updated_time,verified,email");
request.setParameters(parameters);
request.executeAsync();

How do I make java wait for boolean to run funciton

I'm sure this is pretty simple but I can't figure out and it sucks I'm up on suck on (what should be) an easy step.
ok. I have a method that runs one function that give a response. this method actually handles the uploading of the file so o it takes a second to give a response. I need this response in the following method. sendPicMsg needs to complete and then forward it's response to sendMessage. Please help.
b1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if(!uploadMsgPic.equalsIgnoreCase("")){
Log.v("response","Pic in storage");
sendPicMsg();
sendMessage();
}else{
sendMessage();
}
1st Method
public void sendPicMsg(){
Log.v("response", "sendPicMsg Loaded");
if(!uploadMsgPic.equalsIgnoreCase("")){
final SharedPreferences preferences = this.getActivity().getSharedPreferences("MyPreferences", getActivity().MODE_PRIVATE);
AsyncHttpClient client3 = new AsyncHttpClient();
RequestParams params3 = new RequestParams();
File file = new File(uploadMsgPic);
try {
File f = new File(uploadMsgPic.replace(".", "1."));
f.createNewFile();
//Convert bitmap to byte array
Bitmap bitmap = decodeFile(file,400);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.PNG, 0 /*ignored for PNG*/, bos);
byte[] bitmapdata = bos.toByteArray();
//write the bytes in file
FileOutputStream fos = new FileOutputStream(f);
fos.write(bitmapdata);
params3.put("file", f);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
params3.put("email", preferences.getString("loggedin_user", ""));
params3.put("webversion", "1");
client3.post("http://*******.com/apiweb/******upload.php",params3, new AsyncHttpResponseHandler() {
#Override
public void onSuccess(String response) {
Log.v("response", "Upload Complete");
refreshChat();
//responseString = response;
Log.v("response","msgPic has been uploaded"+response);
//parseChatMessages(response);
response=picurl;
uploadMsgPic = "";
if(picurl!=null){
Log.v("response","picurl is set");
}
if(picurl==null){
Log.v("response", "picurl no ready");
};
}
});
sendMessage();
}
}
2nd Method
public void sendMessage(){
final SharedPreferences preferences = this.getActivity().getSharedPreferences("MyPreferences", getActivity().MODE_PRIVATE);
if(preferences.getString("Username", "").length()<=0){
editText1.setText("");
Toast.makeText(this.getActivity(), "Please Login to send messages.", 2);
return;
}
AsyncHttpClient client = new AsyncHttpClient();
RequestParams params = new RequestParams();
if(type.equalsIgnoreCase("3")){
params.put("toid",user);
params.put("action", "sendprivate");
}else{
params.put("room", preferences.getString("selected_room", "Adult Lobby"));
params.put("action", "insert");
}
Log.v("response", "Sending message "+editText1.getText().toString());
params.put("message",editText1.getText().toString() );
params.put("media", picurl);
params.put("email", preferences.getString("loggedin_user", ""));
params.put("webversion", "1");
client.post("http://peekatu.com/apiweb/*********.php",params, new AsyncHttpResponseHandler() {
#Override
public void onSuccess(String response) {
refreshChat();
//responseString = response;
Log.v("response", response);
//parseChatMessages(response);
if(picurl!=null)
Log.v("response", picurl);
}
});
editText1.setText("");
lv.setSelection(adapter.getCount() - 1);
}
From what I understand, you need serial execution of background tasks.
What I do in the case is use a class that extends AsyncTask, takes some sort of listener in its constructor and calls the listener's callback in onPostExecute.
A quick example:
class ExampleTask<T,S,U> extends AsyncTask<T,S,U>
{
public interface ExampleListener
{
public void onTaskCompleted(boolean success);
}
private ExampleListener mListener;
public ExampleTask(ExampleListener listener)
{
mListener = listener;
}
...
#Override
protected void onPostExecute(U result)
{
...
if (mListener != null)
{
mListener.onTaskCompleted(yourBooleanResult);
}
}
}
Just pass a new ExampleListener implementation that calls the second method.
Here's an implementation of the listener:
ExampleListener sendMessageListener = new ExampleListener()
{
public void onTaskCompleted(boolean success)
{
if(success)
sendMessage();
}
}
Don't mix this IO and RPC intensive with your client thread. When your button is clicked, start another thread which handles the communication.
In that thread (potentially a separate class) you send the picture and wait for response; at the same time mark your button to be disabled to avoid clicking again. Then when you receive response, send the message again. Afterwards, raise an event back to the GUI thread, enable the button and display the message.
An easy way to solve this; call your method sendMessage() after the sendPicMsg() in the "onSuccess()" method

How to convert video file(.mp4) format into binary format in android?

I want to upload a video in web server. I got the service which to i want to pass a file in binary format how can i do this ?
I have tried to convert the video file into binary format with the help of base64..?
public class binaryformat extends Activity {
private String strAttachmentCoded;
Button b1;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
b1=(Button)findViewById(R.id.button1);
b1.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
// TODO Auto-generated method stub
File file = new File("/mnt/sdcard/C:/Program Files (x86)/Wowza Media Systems/Wowza Media Server 3.1.2/content/sample.mp4");
FileInputStream objFileIS = null;
try
{
objFileIS = new FileInputStream(file);
}
catch (FileNotFoundException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
ByteArrayOutputStream objByteArrayOS = new ByteArrayOutputStream();
byte[] byteBufferString = new byte[1024];
try
{
for (int readNum; (readNum = objFileIS.read(byteBufferString)) != -1;)
{
objByteArrayOS.write(byteBufferString, 0, readNum);
System.out.println("read " + readNum + " bytes,");
}
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
byte[] byteBinaryData = Base64.encode((objByteArrayOS.toByteArray()), Base64.DEFAULT);
strAttachmentCoded = new String(byteBinaryData);
}
});
}
}
I have experienced in my 3 application that it is good if use XML to send the IMAGE or VIDEO over server.
Sending IMAGE or VIDEO in the form of base64 String in the XML is best if you want to upload a IMAGE or VIDEO in ANDROID.
public static String uploadMultiplePhoto(String url, String xmlString) {
String responseString = "";
try {
//instantiates httpclient to make request
DefaultHttpClient httpclient = new DefaultHttpClient();
//url with the post data
HttpPost request = new HttpPost(url);
//convert parameters into JSON object
//JSONObject holder = new JSONObject(jsonObjString);
//passes the results to a string builder/entity
StringEntity se = new StringEntity(xmlString);
//sets the post request as the resulting string
request.setEntity(se);
//sets a request header so the page receving the request
//will know what to do with it
request.setHeader("Accept", "application/xml");
/*request.setHeader("Content-type", "application/xml");*/
//Handles what is returned from the page
ResponseHandler<String> responseHandler = new BasicResponseHandler();
responseString = httpclient.execute(request, responseHandler);
} catch (Exception exception) {
exception.printStackTrace();
}
return responseString;
}

Android Facebook Graph API

Has anyone got an example of how to use the Android Graph API?
I am stuck with the basics, like posting text to the wall on Facebook.
I'm using the Facebook SDK for Android. Here is what I have so far:
Bundle params = new Bundle();
params.putString("message", "picture caption");
AsyncFacebookRunner mAsyncRunner = new AsyncFacebookRunner(facebook);
mAsyncRunner.request("me/feed", params, "POST", new RequestListener() {
#Override
public void onMalformedURLException(MalformedURLException e, Object state) {
// TODO Auto-generated method stub
}
#Override
public void onIOException(IOException e, Object state) {
// TODO Auto-generated method stub
}
#Override
public void onFileNotFoundException(FileNotFoundException e, Object state) {
// TODO Auto-generated method stub
}
#Override
public void onFacebookError(FacebookError e, Object state) {
// TODO Auto-generated method stub
}
#Override
public void onComplete(String response, Object state) {
// TODO Auto-generated method stub
}
}, "foo");
Nothing happens, and my Logcat says:
03-02 22:10:02.973: WARN/Bundle(1930): Key message expected byte[] but value was a java.lang.String. The default value <null> was returned.
03-02 22:10:02.983: WARN/Bundle(1930): Attempt to cast generated internal exception:
03-02 22:10:02.983: WARN/Bundle(1930): java.lang.ClassCastException: java.lang.String
03-02 22:10:02.983: WARN/Bundle(1930): at android.os.Bundle.getByteArray(Bundle.java:1305)
03-02 22:10:02.983: WARN/Bundle(1930): at com.facebook.android.Util.encodePostBody(Util.java:63)
03-02 22:10:02.983: WARN/Bundle(1930): at com.facebook.android.Util.openUrl(Util.java:182)
03-02 22:10:02.983: WARN/Bundle(1930): at com.facebook.android.Facebook.request(Facebook.java:559)
03-02 22:10:02.983: WARN/Bundle(1930): at com.facebook.android.AsyncFacebookRunner$2.run(AsyncFacebookRunner.java:253)
try this
Bundle params = new Bundle();
params.putString(Facebook.TOKEN, token);
params.putString("message", "graph api");
mAsyncRunner.request("/me/feed", params,"POST", new SampleUploadListener(),null);
you can get access token by using
token = mFacebook.getAccessToken();
You can do this like :--
give description in bundle message and if u want to share some image from server u can provide link as i given below
Bundle params = new Bundle();
params.putString("message", "description");
params.putString("link","your image url" );
new GraphRequest( AccessToken.getCurrentAccessToken(),
"me/feed",
params,
HttpMethod.POST,
new GraphRequest.Callback() {
#Override
public void onCompleted(GraphResponse response) {
Log.d(TAG, "" + response.toString());
try {
JSONObject jsonObject = new JSONObject(response.getRawResponse());
if (jsonObject != null) {
String postId = jsonObject.getString("id");
if (postId != null && !postId.equalsIgnoreCase("")) {
hideProgressDialog();
Log.d("postId", "" + postId);
} else {
hideProgressDialog();
Utils.showToast(getActivity(), getResources().getString(R.string.txt_try_again));
}
} else {
hideProgressDialog();
Utils.showToast(getActivity(), getResources().getString(R.string.txt_try_again));
}
} catch (JSONException e) {
hideProgressDialog();
e.printStackTrace();
} catch (Throwable e) {
hideProgressDialog();
e.printStackTrace();
}
}
}).executeAsync();

Categories