Adding content to facebook feed from Android app - android

I made a little example for posting messages to facebook feed via Android app.
It works great but i just want to add more content to the post like the facebook page's icon, a link and more stuff..
How can i add these parameters to my facebook dialog to post them as well?
public class MainActivity extends Activity
{
Facebook facebook = new Facebook("Here i got my app id.");
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Posting my message, maybe here i could add paramterers like icon and a link etc..?
facebook.dialog(MainActivity.this, "feed", new PostDialogListener());
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
facebook.authorizeCallback(requestCode, resultCode, data);
}
public abstract class BaseDialogListener implements DialogListener {
#Override
public void onFacebookError(FacebookError e) {
e.printStackTrace();
}
#Override
public void onError(DialogError e) {
e.printStackTrace();
}
#Override
public void onCancel() {
}
}
public class PostDialogListener extends BaseDialogListener {
#Override
public void onComplete(Bundle values) {
final String postId = values.getString("post_id");
if (postId != null) {
ki("Message posted on the wall.");
} else {
ki("No message posted on the wall.");
}
}
}
}

private void publishPhoto(String imageURL) {
Log.d("FACEBOOK", "Post to Facebook!");
try {
JSONObject attachment = new JSONObject();
attachment.put("message", Utils.s(R.string.fb_message));
attachment.put("name", Utils.s(R.string.fb_name));
attachment.put("href", Utils.s(R.string.url_dotzmag));
attachment.put("description", Utils.s(R.string.fb_description));
JSONObject media = new JSONObject();
media.put("type", "image");
media.put("src", imageURL);
media.put("href", Utils.s(R.string.url_dotzmag));
attachment.put("media", new JSONArray().put(media));
JSONObject properties = new JSONObject();
JSONObject prop1 = new JSONObject();
prop1.put("text", "Dotz App on Android Market");
prop1.put("href", Utils.s(R.string.url_android_market));
properties.put("Get the App for free", prop1);
JSONObject prop2 = new JSONObject();
prop2.put("text", "Dotz Tuning on Facebook");
prop2.put("href", Utils.s(R.string.url_facebook_fanpage));
properties.put("Visit our fanpage", prop2);
attachment.put("properties", properties);
Log.d("FACEBOOK", attachment.toString());
Bundle params = new Bundle();
params.putString("attachment", attachment.toString());
mFacebook.dialog(mActivity, "stream.publish", params, new PostPhotoDialogListener());
//mAsyncRunner.request("me/feed", params, "POST", new WallPostRequestListener(), null);
} catch (JSONException e) {
Log.e("FACEBOOK", e.getLocalizedMessage(), e);
}
}
public class PostPhotoDialogListener extends BaseDialogListener {
public void onComplete(Bundle values) {
final String postId = values.getString("post_id");
if (postId != null) {
Log.d("FACEBOOK", "Dialog Success! post_id=" + postId);
Toast.makeText(mActivity, "Successfully shared on Facebook!", Toast.LENGTH_LONG).show();
/*
mAsyncRunner.request(postId, new WallPostRequestListener());
mDeleteButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mAsyncRunner.request(postId, new Bundle(), "DELETE",
new WallPostDeleteListener(), null);
}
});
*/
} else {
Log.d("FACEBOOK", "No wall post made");
}
}
}

Related

Facebook Integration Android: onCompleted(GraphJSONObjectCallback) block not executing

I am trying to build an app which fetches all photos from facebook profile and this code is in the UserProfileActivity. But the intent which starts this activity is inside GraphRequest onCompleted block. This block is never getting executed as I saw while debugging. I tried a lot to understand it and saw various posts and everywhere the code is like this.
public class MainActivity extends AppCompatActivity implements FacebookCallback<LoginResult>{
private LoginButton buttonLoginFacebook;
private TextView textViewMessage;
private CallbackManager callbackManager;
private String TAG = "MainActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getApplicationContext());
callbackManager = CallbackManager.Factory.create();
setContentView(R.layout.activity_main);
buttonLoginFacebook = (LoginButton)findViewById(R.id.buttonLoginFacebook);
buttonLoginFacebook.setReadPermissions(Arrays.asList("public_profile, user_photos, user_posts"));
textViewMessage = (TextView)findViewById(R.id.textViewMessage);
buttonLoginFacebook.registerCallback(callbackManager,this);
}
#Override
public void onSuccess(LoginResult loginResult) {
GraphRequest request = GraphRequest.newMeRequest(loginResult.getAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
Log.e(TAG,object.toString());
Log.e(TAG,response.toString());
try{
String userId = object.getString("id");
URL profilePicture = new URL("https://graph.facebook.com/" + userId + "/picture?width=500&height=500");
String fullName="";
if(object.has("first_name"))
fullName += object.getString("first_name");
if(object.has("last_name"))
fullName += " " + object.getString("last_name");
Intent intent = new Intent(MainActivity.this,UserProfileActivity.class);
intent.putExtra("name",fullName);
intent.putExtra("imageUrl",profilePicture.toString());
startActivity(intent);
finish();
} catch (JSONException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id, first_name, last_name");
request.setParameters(parameters);
request.executeAsync();
}
#Override
public void onCancel() {
textViewMessage.setText("Login attempt cancelled");
}
#Override
public void onError(FacebookException error) {
textViewMessage.setText("Login attempt failed");
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
}
}
The code is never getting inside the onCompleted block. Thus the intent for UserProfileActivity is never getting executed. I am a little new to Facebook Sdk so any help would be appreciated.
its working for me
LoginManager.getInstance().registerCallback(mCallbackManager,
new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult success) {
// TODO Auto-generated method stub
Log.d("facebookLogin", "successful"
+ success.getRecentlyGrantedPermissions()
.toString() + " " + success.toString());
AccessToken token = success.getAccessToken();
if (token == null) {
Log.e("FBaccessToken", "null");
} else {
Log.d("FBAccesstoken", token.toString());
getFBMeData(token);
}
}
#Override
public void onError(FacebookException e) {
if (e instanceof FacebookException) {
if (AccessToken.getCurrentAccessToken() != null) {
LoginManager.getInstance().logOut();
}
}
}
#Override
public void onCancel() {
// TODO Auto-generated method stub
Log.d("facebookLogin", "canceled by user");
}
});
}
public void getFBMeData(AccessToken atoken) {
Profile.fetchProfileForCurrentAccessToken();
GraphRequest request = GraphRequest.newMeRequest(
AccessToken.getCurrentAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object,
GraphResponse response) {
// TODO Auto-generated method stub
if (object != null) {
Log.d("FBGraphJSONObject", object.toString());
if(Profile.getCurrentProfile()!=null) {
FBdata.put("fbid", Profile.getCurrentProfile()
.getId());
FBdata.put("fname", Profile.getCurrentProfile()
.getFirstName());
FBdata.put("lname", Profile.getCurrentProfile()
.getLastName());
String gender = object.optString("gender");
String dob = object.optString("birthday");
String locationName = "";
JSONObject location = object
.optJSONObject("location");
if (location != null) {
locationName = location.optString("name");
}
String pictureUrl = "", email = "";
JSONObject picture = object
.optJSONObject("picture");
JSONObject data = picture.optJSONObject("data");
try {
email = URLDecoder.decode(
object.optString("email"), "UTF-8");
if (picture != null) {
pictureUrl = URLDecoder.decode(
data.optString("url"), "UTF-8");
}
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
FBdata.put("photo", pictureUrl);
FBdata.put("address", locationName);
FBdata.put("dob", dob);
FBdata.put("gender", gender);
FBdata.put("email", email);
}
}
});
Bundle params = new Bundle();
params.putString("fields", "gender,email,birthday,location,picture");
request.setParameters(params);
request.executeAsync();
}
I had the same problem, The Issue was android.os.NetworkOnMainThreadException,So Make Sure You Call Network Request in a Separate Thread.

how to get public Facebook page data (app) of particular login into my android application?

Am working for facebook public page post. My Customers will login with facebook (inside my application) to link their public pages to my application. With this login is it possible to get customers public pages list created by them in facebook?
As of now i can able to get the user details but not the pages AND events.
Here is my answer to my own question after a long research its worked fine with public pages as response from activity result.
public class AdminFbLogin extends Activity {
private ProgressDialog pDialog;
private String userName ="", accessToken = "";
private JSONArray fbPages = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
facebookLogout();
pDialog = new ProgressDialog(this);
pDialog.setMessage("loading");
pDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
pDialog.setCanceledOnTouchOutside(false);
try{
Session.openActiveSession(AdminFbLogin.this, true, new Session.StatusCallback() {
// callback when session changes state
#SuppressWarnings("deprecation")
#Override
public void call(Session session, SessionState state, Exception exception) {
if (session.isOpened()) {
// make request to the /me API
Request.executeMeRequestAsync(session, new Request.GraphUserCallback() {
// callback after Graph API response with user
// object
#Override
public void onCompleted(GraphUser user, Response response) {
if (user != null) {
userName = user.getName();
if(fbPages != null ) {
returnAccessToken();
}
}
}
});
}
}
});
} catch(Exception e){
Toast.makeText(AdminFbLogin.this, "Please check your internet connection. ", Toast.LENGTH_LONG).show();
pDialog.dismiss();
Log.e("AdminFBLogin Error",e.getLocalizedMessage(),e);
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Session.getActiveSession().onActivityResult(this, requestCode, resultCode, data);
accessToken = Session.getActiveSession().getAccessToken();
final Session session = Session.getActiveSession();
if (session.isOpened()) {
new Request(session, "/me/accounts", null, HttpMethod.GET, new Request.Callback() {
public void onCompleted(Response response) {
try{
GraphObject go = response.getGraphObject();
fbPages = (JSONArray) go.getProperty("data");
Log.d("User Response :", response.toString());
if(!userName.equals("")) {
returnAccessToken();
}
} catch(Exception e){
Log.e("JSOn Exception", e.getLocalizedMessage(),e);
}
}
}
).executeAsync();
}
}
private void returnAccessToken(){
Intent data = new Intent();
data.putExtra("accessToken", accessToken);
data.putExtra("fbPages", fbPages.toString());
data.putExtra("userName", userName);
setResult(RESULT_OK, data);
facebookLogout();
finish();
}
}
You should probably have a look at the SDK and the tutorials:
https://developers.facebook.com/docs/android/sample-apps

Setting text in facebook statuc from native android application

I am trying to set text in facebook status from my app, but its not copying in the status dialog box of facebook post dialog box. Dialog box is opening correctly for fb, but message is not copied in the status box. Thanks
My code is :
facebook = new Facebook("my_app_id");
Bundle parameters = new Bundle();
parameters.putString("message", "HI there");
facebook.dialog(this, "feed", parameters,
new PostDialogListener());
PostDialogListener class
public class PostDialogListener implements DialogListener {
#Override
public void onFacebookError(FacebookError e) {
e.printStackTrace();
}
#Override
public void onComplete(Bundle values) {
final String postId = values.getString("post_id");
if (postId != null) {
} else {
}
}
#Override
public void onError(DialogError e) {
e.printStackTrace();
}
#Override
public void onCancel() {
}
}
Try this code and see if it does the job for you. For me it works perfectly because i want to post a custom message.
new Thread(){
public void run(){
Looper.prepare();
Bundle parameters = new Bundle();
parameters.putString("message", "your_message_here");
parameters.putString("caption", "your_caption");
try {
mFacebook.request("me");
String response = mFacebook.request("me/feed", parameters, "POST");
Log.d("Tests", "got response: " + response);
if (response == null || response.equals("")
|| response.equals("false") || response.startsWith("{\"error\"")) {
mActivity.runOnUiThread(failRunnable);
} else {
mActivity.runOnUiThread(successRunnable);
}
} catch (Exception e) {
showToast("Failed to post to wall!");
e.printStackTrace();
}
}
}.start();
mFacebook is my Facebook Object.

Predefined text directly posted on facebook wall

i am using facebook android sdk provided for facebook i m using their examples-simple provided by them and its working very finely , now on login in fb show a form from fb to post on wall on button click .
but I want to set text directly from code and on button click it directly post the text set by me on fb without calling the wall post form to enter the text and share .
this is my project image conatning all fb related files that i m using and beloow is mu step wise o/p of this project
1.login
after clcik show share form
but after wall post i want to directly upload my post on fb how can i do this and what to change i am not getting any idea i tried but cannot set my predefined text ,how cani directly post on wall without calling the form to share
i have downloaded sdk fron gitstore from this link https://github.com/facebook/facebook-android-sdk/ pls help me thanks in advance
this is my example.java code
mUploadButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Bundle params = new Bundle();
params.putString("method", "photos.upload");
URL uploadFileUrl = null;
try {
uploadFileUrl = new URL(
"http://www.facebook.com/images/devsite/iphone_connect_btn.jpg");
} catch (MalformedURLException e) {
e.printStackTrace();
}
try {
HttpURLConnection conn= (HttpURLConnection)uploadFileUrl.openConnection();
conn.setDoInput(true);
conn.connect();
int length = conn.getContentLength();
byte[] imgData =new byte[length];
InputStream is = conn.getInputStream();
is.read(imgData);
params.putByteArray("picture", imgData);
} catch (IOException e) {
e.printStackTrace();
}
mAsyncRunner.request(null, params, "POST",
new SampleUploadListener(), null);
}
});
mUploadButton.setVisibility(mFacebook.isSessionValid() ?
View.VISIBLE :
View.INVISIBLE);
mPostButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mFacebook.dialog(Example.this, "feed",
new SampleDialogListener());
}
});
mPostButton.setVisibility(mFacebook.isSessionValid() ?
View.VISIBLE :
View.INVISIBLE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode,
Intent data) {
mFacebook.authorizeCallback(requestCode, resultCode, data);
}
public class SampleAuthListener implements AuthListener {
public void onAuthSucceed() {
mText.setText("You have logged in! ");
mRequestButton.setVisibility(View.VISIBLE);
mUploadButton.setVisibility(View.VISIBLE);
mPostButton.setVisibility(View.VISIBLE);
}
public void onAuthFail(String error) {
mText.setText("Login Failed: " + error);
}
}
public class SampleLogoutListener implements LogoutListener {
public void onLogoutBegin() {
mText.setText("Logging out...");
}
public void onLogoutFinish() {
mText.setText("You have logged out! ");
mRequestButton.setVisibility(View.INVISIBLE);
mUploadButton.setVisibility(View.INVISIBLE);
mPostButton.setVisibility(View.INVISIBLE);
}
}
public class SampleRequestListener 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 name = json.getString("name");
// 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."
Example.this.runOnUiThread(new Runnable() {
public void run() {
mText.setText("Hello there, " + name + "!");
}
});
} catch (JSONException e) {
Log.w("Facebook-Example", "JSON Error in response");
} catch (FacebookError e) {
Log.w("Facebook-Example", "Facebook Error: " + e.getMessage());
}
}
}
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."
Example.this.runOnUiThread(new Runnable() {
public void run() {
mText.setText("Hello there, photo has been uploaded at \n" + src);
}
});
} catch (JSONException e) {
Log.w("Facebook-Example", "JSON Error in response");
} catch (FacebookError e) {
Log.w("Facebook-Example", "Facebook Error: " + e.getMessage());
}
}
}
public class WallPostRequestListener extends BaseRequestListener {
public void onComplete(final String response, final Object state) {
Log.d("Facebook-Example", "Got response: " + response);
String message = "<empty>";
try {
JSONObject json = Util.parseJson(response);
message = json.getString("lithe Technologies");
} 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 + "helloooo lithe";
Example.this.runOnUiThread(new Runnable() {
public void run() {
mText.setText(text);
}
});
}
}
public class WallPostDeleteListener extends BaseRequestListener {
public void onComplete(final String response, final Object state) {
if (response.equals("true")) {
Log.d("Facebook-Example", "Successfully deleted wall post");
Example.this.runOnUiThread(new Runnable() {
public void run() {
mDeleteButton.setVisibility(View.INVISIBLE);
mText.setText("Deleted Wall Post");
}
});
} else {
Log.d("Facebook-Example", "Could not delete wall post");
}
}
}
public class SampleDialogListener extends BaseDialogListener {
public void onComplete(Bundle values) {
final String postId = values.getString("post_id");
if (postId != null) {
Log.d("Facebook-Example", "Dialog Success! post_id=" + postId);
mAsyncRunner.request(postId, new WallPostRequestListener());
mDeleteButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mAsyncRunner.request(postId, new Bundle(), "DELETE",
new WallPostDeleteListener(), null);
}
});
mDeleteButton.setVisibility(View.VISIBLE);
} else {
Log.d("Facebook-Example", "No wall post made");
}
}
}
}
Write below two functions into your Activity.
public void postToWall() {
String message="Good Morning to All";
Bundle parameters = new Bundle();
parameters.putString("message", message);
parameters.putString("description", "topic share");
try {
facebook.request("me");
String response = facebook.request("me/feed", parameters, "POST");
Log.d("Tests", "got response: " + response);
if (response == null || response.equals("") || response.equals("false")) {
showToast("Blank response.");
} else {
showToast("Message posted to your facebook wall!");
}
} catch (Exception e) {
showToast("Failed to post to wall!");
e.printStackTrace();
}
}
2)
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();
}
3)
public void loginAndPostToWall() {
facebook.authorize(this, PERMISSIONS, Facebook.FORCE_DIALOG_AUTH, new LoginDialogListener());
}
Write below code into your wall post button click event
facebook = new Facebook(APP_ID);
restoreCredentials(facebook);
if (!facebook.isSessionValid()) {
loginAndPostToWall();
} else {
postToWall();
}

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

Categories

Resources