Posting in Facebook wall using graph API not Working - android

I'm trying to post something to Facebook wall using graph API but its not working for me.
It has no error but it also not posting anything on my wall.
Here is the Codes:
public class ActivityName extends Activity{
Dialog dialog;
Facebook fb;
SharedPreferences sp;
String access_token, name, email;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.success);
String APP_ID = "MY_ID";
fb = new Facebook(APP_ID);
sp = getPreferences(MODE_PRIVATE);
access_token = sp.getString("access_token", null);
long expires = sp.getLong("access_expires", 0);
if(access_token!= null){
fb.setAccessToken(access_token);
}
if(expires != 0){
fb.setAccessExpires(expires);
}
((Button) findViewById(R.id.btn_home)).setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
openContextMenu(v);
}
});
((Button) findViewById(R.id.btn_home)).setOnCreateContextMenuListener(new View.OnCreateContextMenuListener() {
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
// TODO Auto-generated method stub
menu.setHeaderTitle("Tell the world!");
menu.add(0, 0, 0, "Facebook");
menu.add(0, 1, 0, "Twitter");
menu.add(0, 2, 0, "Skip");
}
});
}
public boolean onContextItemSelected(MenuItem item) {
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item
.getMenuInfo();
switch (item.getItemId()) {
case 1:
break;
case 0:
fb.authorize(SuccessActivity.this, new String[]{ "photo_upload,user_photos,publish_checkins,publish_actions,publish_stream"},new DialogListener() {
public void onComplete(Bundle values) {
postToWall();
}
public void onFacebookError(FacebookError error) {
}
public void onError(DialogError e) {
}
public void onCancel() {
}
});
break;
case 2:
Intent i = new Intent(getApplicationContext(),MainActivity.class);
startActivity(i);
overridePendingTransition(android.R.anim.slide_in_left, android.R.anim.slide_out_right);
break;
}
return true;
}
public void onBackPressed() {
}
#SuppressLint("SdCardPath")
public void postToWall() {
// post on user's wall.
try {
if (fb.isSessionValid()) {
byte[] data = null;
Bitmap bi = BitmapFactory.decodeFile("/sdcard/Asa.jpg");
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("message", "Test from Android AVD");
params.putByteArray("picture", data);
AsyncFacebookRunner mAsyncRunner = new AsyncFacebookRunner(fb);
mAsyncRunner.request("/me/feed", params,"POST", new SampleUploadListener(),null);
}
}catch(Exception e){
e.printStackTrace();
}
}
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) {
}
}
}
Can anyone pint what missing or wrong in this codes?
any thoughts will be highly appreciated.

Here's some code I used a little while back to do something similar:
function publishPost(session) {
var $title = $('#title').val(),
$story = $('#story').val(),
publish = {
method: 'stream.publish',
message: 'I just entered the Your Perfect Kent Day Competition.',
picture : 'http://apps.facebook.com/perfect-kent-day/',
link : 'http://apps.facebook.com/perfect-kent-day/',
name: 'Enter to win or vote for your faourite story here!',
caption: $title,
description: $story,
actions : { name : 'Apply for Kent Teach Jobs...', link : 'http://www.kent- teach.com/'}
};
FB.api('/me/feed', 'POST', publish, function(response) {
//alert('A post had just been published into the stream on your wall.');
$('#before-submit').hide();
$('#after-submit').show();
$('#loading').fadeOut();
});
};
And then I called the publishPost() function once a form on the page was submitted with AJAX. Hope this help!

Related

How to fetch url for photo from Facebook Graph API (/me/photos)

Using Facebook Graph API, I can query the list of photos uploaded by user (/me/photos/?type=uploaded)
However, this only returns a list of ids. I assume this list is the id for the photo, but how can I use this id to fetch the url?
You need to add the link field to the request - eg ask for /me/photos?fields=link&type=uploaded
Try using this link:
https://graph.facebook.com/ fbid /picture?type=large
Please create a URL like this-
https://graph.facebook.com/USER_FB_ID/picture?type=large
REPLACE USER_FB_ID with fb id which you are receiving onSuccess
EDIT
Working code to fetch the list of photos with source URL .
System.out.println("Logged in with fb");
Bundle params = new Bundle();
_accesToken = _sPrefsFB.getString("access_token", "");
System.out.println("_accesToken Bundle : " + _accessToken);
params.putString("access_token", _accessToken);
_imagesList.clear();
mAsyncRunner.request("/me/albums" ,params,"GET", new RequestListener() {
#Override
public void onComplete(String response, Object state) {
// Log.d("Photos Album ", response);
//need to set album adapter
if (response!=null&&!response.equalsIgnoreCase("")) {
// System.out.println("Response of fb album : " +response);
try {
JSONObject _jObjectMain = new JSONObject(response);
JSONArray _jArrayMain = _jObjectMain.getJSONArray("data");
System.out.println("Size of Album list fb : " + _jArrayMain.length());
if (_jArrayMain.length()>0) {
_albumListFB.clear();
for (int i = 0; i < _jArrayMain.length(); i++) {
JSONObject _jObjectSub = _jArrayMain.getJSONObject(i);
FaceBookAlbumBean _bean = new FaceBookAlbumBean();
if (_jObjectSub.has("id")) {
String _albumID = _jObjectSub.getString("id");
_bean.set_albumID(_albumID);
}
if (_jObjectSub.has("name")) {
String _albumName = _jObjectSub.getString("name");
_bean.set_albumName(_albumName);
}
_albumListFB.add(_bean);
}
//need to call fb images ws
Bundle params = new Bundle();
_accesToken = _sPrefsFB.getString("access_token", "");
System.out.println("_accesToken Bundle : " + _accessToken);
params.putString("access_token", _accessToken);
for (int i = 0; i < _albumListFB.size(); i++) {
String _albumID = _albumListFB.get(i).get_albumID();
mAsyncRunner.request("/"+_albumID+"/photos" ,params,"GET", new RequestListener() {
#Override
public void onComplete(String response, Object state) {
Log.d("PHotos from album", response);
if (response!=null&&!response.equalsIgnoreCase("")) {
try {
JSONObject _jObjectMain = new JSONObject(response);
if (_jObjectMain.has("data")) {
JSONArray _jArrayMain = _jObjectMain.getJSONArray("data");
if (_jArrayMain.length()>0) {
for (int i = 0; i < _jArrayMain.length(); i++) {
JSONObject _jObjectSub = _jArrayMain.getJSONObject(i);
CameraRollBean _bean = new CameraRollBean();
if (_jObjectSub.has("images")) {
JSONArray _jArraySub = _jObjectSub.getJSONArray("images");
if (_jArraySub.length()>0) {
System.out
.println("Image Array length : " + _jArraySub.length()) ;
JSONObject _jObjectSub1 = _jArraySub.getJSONObject(_jArraySub.length()-1);
if (_jObjectSub1.has("source")) {
String _source = _jObjectSub1.getString("source");
/*System.out
.println("Source Image : " +_source);*/
_bean.setFilePath(_source);
}
}
}
_imagesList.add(_bean);
}
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("_imagesList Size : " +_imagesList.size());
}
#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) {
}
},null);
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
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) {
}
},null);
// }

Image is not attached in quickblox for android

I have made a demo for sending image to private chat using QuickBlox, I am struggling to attach an image with the chat message, I have gone through its document and have used the below Links, with no luck
Attach an image
My code is as below:
chatMessage = new QBChatMessage();
sendButton = (Button) findViewById(R.id.chatSendButton);
sendButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String messageText = messageEditText.getText().toString();
if (TextUtils.isEmpty(messageText)) {
return;
}
// Send chat message
//
// send a message
// ...
int fileId = R.raw.ic_launcher;
InputStream is = ChatActivity.this.getResources()
.openRawResource(fileId);
File file = FileHelper.getFileInputStream(is,
"sample_file.png", "myFile");
Boolean fileIsPublic = true;
QBContent.uploadFileTask(file, fileIsPublic, messageText,
new QBEntityCallbackImpl<QBFile>() {
#Override
public void onSuccess(QBFile qbFile, Bundle params) {
String publicUrl = qbFile.getPublicUrl();
System.out
.println("==========image uploaded success++++++++"
+ publicUrl);
id = qbFile.getId();
System.out
.println("===================image id+++++++++++"
+ id + "");
}
#Override
public void onError(List<String> errors) {
System.out
.println("==========image uploaded Errors++++++++"
+ errors.toString());
}
}, new QBProgressCallback() {
#Override
public void onProgressUpdate(int progress) {
}
});
QBAttachment atach = new QBAttachment("image");
atach.setId(id+"");
ArrayList<QBAttachment> aryatch = new ArrayList<QBAttachment>();
aryatch.add(atach);
chatMessage.setAttachments(aryatch);
chatMessage.setBody(messageText);
chatMessage.setProperty(PROPERTY_SAVE_TO_HISTORY, "1");
chatMessage.setDateSent(new Date().getTime() / 1000);
try {
chat.sendMessage(chatMessage);
} catch (XMPPException e) {
Log.e(TAG, "failed to send a message", e);
} catch (SmackException sme) {
Log.e(TAG, "failed to send a message", sme);
}
messageEditText.setText("");
if (dialog.getType() == QBDialogType.PRIVATE) {
showMessage(chatMessage);
}
}
});
Well it clear where the mistake is
your id is null here
atach.setId(id+"");
because it will != nil only in onSuccess block of uploadFileTask
So the right way is to forward all attachments logic inside onSuccess block of uploadFileTask
Because these QuickBlox request are asynchronous

Android: how to get spinner value and check the condition

In my app i have a spinner with two items ..i have to choose the item an do action accordingly
dialogButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
String Comment = edittext.getText().toString();
String choose = spinner.getSelectedItem()
.toString();
if (Comment != null && Comment.equalsIgnoreCase("")){
post(Comment,choose);
getActivity().finish();
}else{
showToast("Please enter you comment!");
}
}
});
dialog.show();
dialog.getWindow().setAttributes(lp);
} catch (Exception e) {
e.printStackTrace();
getActivity().finish();
}
}
private void post(String comments, String choose) throws Exception{
StringBuffer finalMessage = new StringBuffer("\nRecomends " + Data.getfName());
if(Data.getAddress() != null && !Data.getAddress().isEmpty()){
finalMessage.append("\n" + Data.getAddress());
}
-----------------> if(spinner.getSelectedItem().toString().equals("Post to personal directory & FB")){
Bundle params = new Bundle();
params.putString("message",finalMessage.toString() );
publishStory(params,comments);
}else {
try {
new FBUtils(activity).sharePlaces(attractionData, comments, null);
} catch (Exception e) {
Log.e(TAG,"sharePlaces error ",e);
}
}
}
private void publishStory(Bundle postParams,final String comments,final String choose) {
Session session = Session.getActiveSession();
if (session != null){
List<String> permissions = session.getPermissions();
if (!isSubsetOf(PERMISSIONS, permissions)) {
Session.NewPermissionsRequest newPermissionsRequest = new Session
.NewPermissionsRequest(this, PERMISSIONS);
session.requestNewPublishPermissions(newPermissionsRequest);
}
Request.Callback callbackRequest= new Request.Callback() {
public void onCompleted(Response response) {
if (response == null || response.equals("")
|| response.equals("false")) {
showToast("Blank response.");
} else
new fbUtils(activity).share(Data, comments, response.getError(),choose);
} catch (Exception e) {
Log.e(TAG,"sharePlaces error ",e);
}
}
};
Request request = new Request(session, Constants.fb.fbId + "/comments", postParams,
HttpMethod.POST, callbackRequest);
RequestAsyncTask task = new RequestAsyncTask(request);
task.execute();
}
the issue is the post() is not executing when clicking the dailogbutton its going into else part, i want to execute the if condition in post() method, Any help is appreciated
As you are getting the value from the spinner. The value may not be updated one .
You should use item-selected listeners.
String result="";
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent,
View view, int pos, long id) {
Toast.makeText(parent.getContext()), "The planet is " +
parent.getItemAtPosition(pos).toString(), Toast.LENGTH_LONG).show();
// Your variable should update here
result = parent.getItemAtPosition(pos).toString();
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
// your code here
}
});
Now use that value in onPost method as:
private void post(String comments, String choose) throws Exception{
StringBuffer finalMessage = new StringBuffer("\nRecomends " + Data.getfName());
if(Data.getAddress() != null && !Data.getAddress().isEmpty()){
finalMessage.append("\n" + Data.getAddress());
}
Log.v("TEST",spinner.getSelectedItem().toString());
-----------------> if(result.equals("Post to personal directory & FB")){
Bundle params = new Bundle();
params.putString("message",finalMessage.toString() );
publishStory(params,comments);
}else {
try {
new FBUtils(activity).sharePlaces(attractionData, comments, null);
} catch (Exception e) {
Log.e(TAG,"sharePlaces error ",e);
}
}
}
Try like this:
private Spinner status;
status = (Spinner) findViewById(R.id.status);
final ArrayList<Simplestatus> statusList = new ArrayList<Simplestatus>();
Simplestatus tempstatus = new Simplestatus();
tempstatus.setSimpleStatusName("ZERO");
tempstatus.setSimpleStatusValue("0");
Simplestatus tempstatus1 = new Simplestatus();
tempstatus1.setSimpleStatusName("ONE");
tempstatus1.setSimpleStatusValue("1");
statusList.add(tempstatus);
statusList.add(tempstatus1);
SpinnerAdapter stateAdaptor = new SpinnerAdapter(SettingActivity.this,statusList);
// stateList.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
status.setAdapter(stateAdaptor);
status.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> arg0, View arg1,int position, long arg3) {
changeStatus(statusList.get(position));
selected = statusList.get(position).getsimpleStatusName();
System.out.println("selected"+selected);
}
public void onNothingSelected(AdapterView<?> arg0) {
}
});
public class Simplestatus
{
private String simpleStatusName;
private String simpleStatusValue;
public String getSimpleStatusName()
{
return simpleStatusName;
}
public void setSimpleStatusName(String simpleStatusName)
{
this.simpleStatusName = simpleStatusName;
}
public String getsimpleStatusValue()
{
return simpleStatusValue;
}
public void setsimpleStatusValue(String simpleStatusValue)
{
this.simpleStatusValue = simpleStatusValue;
}
}

error code 3 unknown method in android facebook app during post message on wall

Hello I am trying to post a message on wall, using this code.
Bundle params = new Bundle();
params.putString(Facebook.TOKEN, facebook.getAccessToken());
params.putString("message", "Facebook Dialogs are easy!");
AsyncFacebookRunner mAsyncRunner = new AsyncFacebookRunner(facebook);
mAsyncRunner.request(null, params, "POST", new SampleUploadListener(),null);
But i am getting this error.
Response: {"error_code":3,"error_msg":"Unknown method","request_args":[{"key":"message","value":"Facebook Dialogs are easy!"},{"key":"method","value":"POST"},{"key":"access_token","value":"AAAFby43GVwgBAJctMak5Y6IOaMylCWOFAXfXvsbMrckgZCi5wBZBSFWu02J1OY9ZB9aFLnwghHE72DgKe0YKIqctc5K54uyrA5mO5X2vQZDZD"},{"key":"format","value":"json"}]}
Thanks bro..i tried this but still doesnt works
AsyncFacebookRunner mAsyncRunner = new AsyncFacebookRunner(facebook);
mAsyncRunner.request("Message Test", new SampleUploadListener());
Here again i am getting error...
GET URL: https://graph.facebook.com/Message Test?access_token=AAAFby43GVwgBAJctMak5Y6IOaMylCWOFAXfXvsbMrckgZCi5wBZBSFWu02J1OY9ZB9aFLnwghHE72DgKe0YKIqctc5K54uyrA5mO5X2vQZDZD&format=json 02-13 16:42:36.027: V/webview(13218): ZoomScale 3 mPreserveZoom: false 02-13 16:42:37.085: D/Facebook-Example(13218): Response: 400 Bad RequestMethod Not ImplementedInvalid method in request
02-13 16:42:37.085: W/Facebook-Example(13218): JSON Error in response
see following coding
public class UpdateStatusResultDialog extends Dialog { private Bundle values;
private TextView mOutput, mUsefulTip;
private Button mViewPostButton, mDeletePostButton;
private Activity activity;
private Handler mHandler;
public UpdateStatusResultDialog(Activity activity, String title, Bundle values) {
super(activity);
this.activity = activity;
this.values = values;
setTitle(title);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mHandler = new Handler();
setContentView(R.layout.update_post_response);
LayoutParams params = getWindow().getAttributes();
params.width = LayoutParams.FILL_PARENT;
params.height = LayoutParams.FILL_PARENT;
getWindow().setAttributes((android.view.WindowManager.LayoutParams) params);
mOutput = (TextView) findViewById(R.id.apiOutput);
mOutput.setText(values.toString());
mUsefulTip = (TextView) findViewById(R.id.usefulTip);
mUsefulTip.setMovementMethod(LinkMovementMethod.getInstance());
mViewPostButton = (Button) findViewById(R.id.view_post_button);
mDeletePostButton = (Button) findViewById(R.id.delete_post_button);
final String postId = values.getString("post_id");
mViewPostButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
/*
* Source tag: view_post_tag
*/
Utility.mAsyncRunner.request(postId, new WallPostRequestListener());
}
});
mDeletePostButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
/*
* Source tag: delete_post_tag
*/
Utility.mAsyncRunner.request(postId, new Bundle(), "DELETE",
new WallPostDeleteListener(), null);
}
});
}
public class WallPostRequestListener extends BaseRequestListener {
#Override
public void onComplete(final String response, final Object state) {
try {
JSONObject json = new JSONObject(response);
setText(json.toString(2));
} catch (JSONException e) {
setText(activity.getString(R.string.exception) + e.getMessage());
}
}
public void onFacebookError(FacebookError error) {
setText(activity.getString(R.string.facebook_error) + error.getMessage());
}
}
public class WallPostDeleteListener extends BaseRequestListener {
#Override
public void onComplete(final String response, final Object state) {
if (response.equals("true")) {
String message = "Wall Post deleted" + "\n";
message += "Api Response: " + response;
setText(message);
} else {
setText("wall post could not be deleted");
}
}
public void onFacebookError(FacebookError error) {
setText(activity.getString(R.string.facebook_error) + error.getMessage());
}
}
public void setText(final String txt) {
mHandler.post(new Runnable() {
#Override
public void run() {
mOutput.setText(txt);
}
});
}
}

Android Post Image to Facebook

I have this code running in my app and it is trying to post text and an image to a users wall. At the moment it is only posting the text. I think I have missed something simple, but would appreciate another pair of eyes check everything or another sample.
Any help is greatly appreciated.
Bundle bundle = new Bundle();
bundle.putString("message", "test update"); //'message' tells facebook that you're updating your status
bundle.putString(Facebook.TOKEN,accessToken);
bundle.putString("attachment", "{\"name\":\"My Test Image\","
+"\"href\":\""+"http://www.google.com"+"\","
+"\"media\":[{\"type\":\"image\",\"src\":\""+"http://www.google.com/logos/mucha10-hp.jpg"+"\",\"href\":\""+"http://www.google.com"+"\"}]"
+"}");
+"}");
//tells facebook that you're performing this action on the authenticated users wall, thus
// it becomes an update. POST tells that the method being used is POST
String response = facebook.request("me/feed",bundle,"POST");
Hope this will be work for you
Create class for facebook varible utility
import android.app.Application;
import com.facebook.android.AsyncFacebookRunner;
import com.facebook.android.Facebook;
public class Utility extends Application{
public static Facebook mFacebook;
public static AsyncFacebookRunner mAsyncRunner;
public static String userUID;
public static final String ICON_URL = "http://i.imgur.com/6G1b7.png";
}
Now mathod used to post image to facebook wall
public void postOnFacebookPicture(final Bitmap bitmap) {
String access_token = mPrefs.getString("access_token", null);
long expires = mPrefs.getLong("access_expires", 0);
if (access_token != null) {
Utility.mFacebook.setAccessToken(access_token);
}
if (expires != 0) {
Utility.mFacebook.setAccessExpires(expires);
}
if (!Utility.mFacebook.isSessionValid()) {
showErrorDialog(
"Facebook Account is not configure,Setting Facebook Account?",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
try {
// Move to setting the facebook account
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
} else {
new Thread() {
#Override
public void run() {
int what = 0;
try {
String accessToken = mPrefs.getString("access_token",
null);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.PNG, 0, bos);
byte[] pictureData = bos.toByteArray();
Bundle bundle = new Bundle();
bundle.putByteArray("facebookPictureData", pictureData);
bundle.putString(Facebook.TOKEN, accessToken);
Utility.mFacebook.request("me/photos", bundle, "POST");
} catch (Exception e) {
what = 1;
}
mHandler.sendMessage(mHandler.obtainMessage(what));
}
}.start();
}
}
For Posting Text and Image in Facebook wall, check this link:
You can insert Image using Media attachment.

Categories

Resources