Post text on facebook wall - android

I wish to post a text / link defined by me on my wall. The way I'm doing, okay opening the box wall and posting a text set time. I want to post a text as if it were a variable.
Eg String text = "Text to be posted"
and this text appear on my wall. Any idea?
public void postToWall() {
facebook.dialog(cxt, "feed",new DialogListener() {
#Override
public void onFacebookError(FacebookError e) {
}
#Override
public void onError(DialogError e) {
}
public void onComplete(String response, Object state) {
Log.d("Profile", response);
String json = response;
try {
// Facebook Profile
JSONObject profile = new JSONObject(json);
// nome usu�rio
final String name = profile.getString("name");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "Comentário enviado com sucesso" + "Name: " + name,
Toast.LENGTH_LONG).show();
}
});
} catch (JSONException e) {
e.printStackTrace();
} }
#Override
public void onCancel() {
}
#Override
public void onComplete(Bundle values) {
// TODO Auto-generated method stub
}
});
}

Related

Issue getting Facebook information

I want facebook profile information in my code. This code works Log.e("in try start", "tryyyyyyyyy"); until here but after that not even single log is executed.
private Facebook facebook;
private AsyncFacebookRunner mAsyncRunner;
String FILENAME = "AndroidSSO_data";
private SharedPreferences mPrefs;
public void loginToFacebook() {
// mPrefs = getPreferences(SharedPreferences.);
// String access_token = mPrefs.getString("access_token", null);
//long expires = mPrefs.getLong("access_expires", 0);
// if (access_token != null) {
// facebook.setAccessToken(access_token);
// }
// if (expires != 0) {
// facebook.setAccessExpires(expires);
// }
if (!facebook.isSessionValid()) {
facebook.authorize(getActivity(),
new String[] { "email", "publish_actions" },
new DialogListener() {
#Override
public void onCancel() {
// Function to handle cancel event
}
#Override
public void onComplete(Bundle values) {
// Function to handle complete event
// Edit Preferences and update facebook acess_token
Toast.makeText(getActivity(), "hiiiiii", Toast.LENGTH_SHORT).show();
//mPrefs=getSharedPreferences("data", getActivity().MODE_PRIVATE);
SharedPreferences.Editor editor = mPrefs.edit();
editor.putString("access_token",
facebook.getAccessToken());
editor.putLong("access_expires",
facebook.getAccessExpires());
editor.commit();
Log.e("getProfileInformation entry", "getProfileInformation");
getProfileInformation();
}
#Override
public void onFacebookError(FacebookError e) {
// TODO Auto-generated method stub
}
#Override
public void onError(DialogError e) {
// TODO Auto-generated method stub
}
});
}
}
public void getProfileInformation() {
Toast.makeText(getActivity(), "byeeeeeee", Toast.LENGTH_SHORT).show();
Log.e("getProfileInformation start", "getProfileInformation");
mAsyncRunner.request("me", new RequestListener() {
#Override
public void onComplete(String response, Object state) {
Log.d("Profile", response);
String json = response;
try {
Log.e("in try start", "tryyyyyyyyy");
JSONObject profile = new JSONObject(json);
// getting name of the user
Log.d("profile", ""+profile);
fb_name = profile.getString("name");
// getting email of the user
fb_email = profile.getString("email");
Log.d("fb_name", "naem"+fb_name+"emial"+fb_email);
//fb_login=true;
// fb_Image = getUserPic(fb_email);
// LoginFuction();
} catch (JSONException e) {
e.printStackTrace();
Log.e("catchhhhhh", ""+e.getMessage());
}
}
public Bitmap getUserPic(String userID) {
String imageURL;
Bitmap bitmap = null;
Log.d("TAG", "Loading Picture");
imageURL = "http://graph.facebook.com/"+userID+"/picture?type=small";
try {
bitmap = BitmapFactory.decodeStream((InputStream)new URL(imageURL).getContent());
} catch (Exception e) {
Log.d("TAG", "Loading Picture FAILED");
e.printStackTrace();
}
return bitmap;
}
#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) {
}
});
}
This code does not give me any name or emailId.
-Hello Abhishek !
- I have tried using Facebook sdk4.+ and i am getting profile info perfectly.
-Firs of all add below code into your oncreate method before setcontentview
FacebookSdk.sdkInitialize(getApplicationContext());
-Then Create you Callbackmanager using below code:-
callbackManager = CallbackManager.Factory.create();
-Add Permissions using below code:-
permission.add("publish_actions");
-Below code is used for Login
LoginManager.getInstance().registerCallback(callbackManager,
new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(final LoginResult loginResult) {
// App code
GraphRequest request = GraphRequest.newMeRequest(
act,
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(
JSONObject object,
GraphResponse response) {
// Application code
if (!TextUtils.isEmpty(object.toString())) {
try {
JSONObject jresJsonObject = new JSONObject(object.toString());
String id = "", name = "", gender = "";
if (!(jresJsonObject.isNull("id"))) {
id = jresJsonObject.getString("id");
}
if (!(jresJsonObject.isNull("gender"))) {
gender = jresJsonObject.getString("gender");
if (gender.equals("male")) {
gender = "0";
} else {
gender = "1";
}
}
if (!(jresJsonObject.isNull("name"))) {
name = jresJsonObject.getString("name");
}
} catch (Exception e) {
}
}
Log.e("graphrequest", response.toString());
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,gender,link");
request.setParameters(parameters);
request.executeAndWait();
}
#Override
public void onCancel() {
Log.i("", "Access Token:: " + "loginResult.getAccessToken()");
}
#Override
public void onError(FacebookException exception) {
Log.i("", "Access Token:: " + "loginResult.getAccessToken()");
}
});
LoginManager.getInstance().logInWithPublishPermissions(this, permission);
-Last but no least add below code in your OnActivitResult
callbackManager.onActivityResult(requestCode, resultCode, data);
NOTE:- This is using latest Facebook sdk
-Please inform me if it is not usefull or you are still getting issue in this.

Auto post on Facebook from Android game on user behalf

I have developed a physics based (Box2d) game for android using Processing and I want to add score sharing option to it so that the user can share his/her best score on their facebook timeline after the game. I have setup Facebook SDK in eclipse. I have searched over internet and found this solution:
public class FacebookConnector {
private static final String APP_ID = "*************";
private Facebook facebook;
private AsyncFacebookRunner mAsyncRunner;
String FILENAME = "AndroidSSO_data";
SharedPreferences mPrefs;
public FacebookConnector() {
facebook = new Facebook(APP_ID);
mAsyncRunner = new AsyncFacebookRunner(facebook);
}
public void loginToFacebook() {
mPrefs = getPreferences(MODE_PRIVATE);
String access_token = mPrefs.getString("access_token", null);
long expires = mPrefs.getLong("access_expires", 0);
if (access_token != null) {
facebook.setAccessToken(access_token);
}
if (expires != 0) {
facebook.setAccessExpires(expires);
}
if (!facebook.isSessionValid()) {
facebook.authorize(LocalPakistaniGames.this,
new String[] { "email",
"publish_stream" }, 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();
}
public void onError(DialogError error) {
// Function to handle error
}
public void onFacebookError(FacebookError fberror) {
// Function to handle Facebook errors
}
});
}
}
public void logoutFromFacebook() {
mAsyncRunner.logout(LocalPakistaniGames.this,
new RequestListener() {
#Override
public void onComplete(String response, Object state) {
Log.d("Logout from Facebook", response);
if (Boolean.parseBoolean(response) == true) {
// User successfully Logged out
}
}
#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) {
}
});
}
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
final String name = profile.getString("name");
// getting email of the user
final String email = profile.getString("email");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Name: " + name + "\nEmail: " + email,
Toast.LENGTH_LONG).show();
}
});
} catch (JSONException e) {
e.printStackTrace();
}
}
public void onIOException1(IOException e, Object state) {
}
public void onFileNotFoundException1(FileNotFoundException e,
Object state) {
}
public void onMalformedURLException1(MalformedURLException e,
Object state) {
}
#Override
public void onFacebookError(FacebookError e, Object state) {
}
#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 onMalformedURLException(MalformedURLException e,
Object state) {
// TODO Auto-generated method stub
}
});
}
public void postToWall(int level, int score) {
// post on user's wall.
String msg = "I just made new best score in Level " + level
+ ". My new Best Score is " + score + ". Beat my score!";
final Bundle parameters = new Bundle();
parameters.putString("description", msg);
parameters.putString("picture", "http://i57.tinypic.com/fui2o.png");
parameters.putString("link",
"https://www.facebook.com/LocalPakistaniGamesAndroid");
parameters.putString("name", "Local Pakistani Games");
parameters.putString("caption",
"Share this. Be a part of preserving Pakistani culture.");
LocalPakistaniGames.this.runOnUiThread(new Runnable() {
public void run() {
facebook.dialog(LocalPakistaniGames.this, "feed",
parameters, new DialogListener() {
#Override
public void onComplete(Bundle values) {
// TODO Auto-generated method stub
if (values != null) {
Toast.makeText(LocalPakistaniGames.this,
"Shared successfully on your timeline!",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(
LocalPakistaniGames.this,
"Share cancelled!",
Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFacebookError(FacebookError e) {
// TODO Auto-generated method stub
Toast.makeText(LocalPakistaniGames.this,
"Facebook Error!",
Toast.LENGTH_SHORT)
.show();
}
#Override
public void onError(DialogError e) {
// TODO Auto-generated method stub
Toast.makeText(LocalPakistaniGames.this,
"Error!", Toast.LENGTH_SHORT)
.show();
}
#Override
public void onCancel() {
// TODO Auto-generated method stub
Toast.makeText(LocalPakistaniGames.this,
"Share cancelled!",
Toast.LENGTH_SHORT).show();
}
});
}
});
}
}
Its working fine and giving a pre-filled dialog box where user can either share or close the dialog box. I have checked and It's sharing correctly on Facebook timeline. But the problem is that it is not using Facebook app installed on the device. Its using chrome on my device to login to Facebook.
Is there any way to force it to use Facebook app for android instead of going to chrome (or any other browser)??
There are many issues with your use of the Facebook SDK, but I will jump straight to your problem.
You're using the "feed" dialog to share. This is a web dialog, which is why it's popping up a WebView (not the actual browser app). You also do not pass any session or access tokens to the feed dialog, which is why the user needs to login before they can share.
If you want to share using the Facebook app, I would recommend this doc: https://developers.facebook.com/docs/android/share
If you want to properly use the Facebook SDK (rather than the old deprecated one), please start here: https://developers.facebook.com/docs/android/getting-started/
Here is the solution to your problem. If you want to make automatic publications on facebook wall, you have to use graph api.
Also, the first thing that you have to do is login with facebook and after that, you have to do another request for permissions.
If you are using LoginManager:
LoginManager.getInstance().logInWithPublishPermissions(this, Arrays.asList("publish_actions"));
this line of code gives to your app the permissions to make publications in behalf to the user

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

Get the album of each facebook album w.r.t album id - facebook android-sdk

I have got all the facebook albums (and their id )using facebook android sdk, and displayed them in a list.
Now on particular list item click, i want to get all the photos of that album (w.r.t "id" )
I got album id this way:
if (!facebook.isSessionValid()) {
facebook.authorize(this, new String[] { "user_photos" },
new DialogListener() {
public void onComplete(Bundle values) {
mAsyncRunner.request("me/albums", new albumsRequestListener());
}
public void onFacebookError(FacebookError error) {
}
public void onError(DialogError e) {
}
public void onCancel() {
}
});
}
public class albumsRequestListener implements RequestListener {
public void onComplete(String response, Object state) {
// TODO Auto-generated method stub
try {
Log.d("Facebook-Example", "Response: " + response.toString());
JSONObject json = Util.parseJson(response);
String count = "0";
JSONArray jArrData = new JSONArray();
jArrData = json.getJSONArray("data");
for (int i = 0; i < jArrData.length(); i++) {
JSONObject objAlbum = jArrData.getJSONObject(i);
String albumId = objAlbum
.getString("id");
String albumName = objAlbum
.getString("name");
if(objAlbum.has("count"))
{
count = objAlbum.getString("count");
}
else
{
count = "0";
}
FbAlbums obj = new FbAlbums();
obj.setId(albumId);
obj.setName(albumName);
obj.setCount(count);
listFbAlbums.add(obj);
}
FB.this.runOnUiThread(new Runnable() {
public void run() {
adapter = new FbAlbumsListAdapter(
getApplicationContext(),listFbAlbums);
lvAlmbums.setAdapter(adapter);
pb.setVisibility(View.INVISIBLE);
lvAlmbums.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(getApplicationContext(), position, Toast.LENGTH_SHORT).show();
}
});
}
});
} catch (JSONException e) {
Log.w("Facebook-Example", "JSON Error in response");
} catch (FacebookError e) {
Log.w("Facebook-Example", "Facebook Error: " + e.getMessage());
}
}
public void onIOException(IOException e, Object state) {
// TODO Auto-generated method stub
}
public void onFileNotFoundException(FileNotFoundException e,
Object state) {
// TODO Auto-generated method stub
}
public void onMalformedURLException(MalformedURLException e,
Object state) {
// TODO Auto-generated method stub
}
public void onFacebookError(FacebookError e, Object state) {
// TODO Auto-generated method stub
}
}
How can i get the json that contains source of each album's images?
Or is there some other way?
Any help will be appreciated,
Thanks
Just use the album ID and add /photos to the end:
mAsyncRunner.request(albumid+"/photos", new photosRequestListener());

Facebook SSO , differentiating the login and wall post messages

I have made a sample for posting on Facebook using the basic Facebook library provided at developer.facebook.com and it works just fine with SSO,
btnPostOnFb.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
{
facebook.authorize(FBIntegrationSampleActivity.this, new String[]{ "user_photos,publish_checkins,publish_actions,publish_stream"}, new DialogListener() {
#Override
public void onComplete(Bundle values) {
if(values!=null && values.containsKey("access_token")){
postOnWall("NEW POST from" +count+"Android -Anuj");
Log.e("post on wall", "WALLPOST");
Toast.makeText(getApplicationContext(), "SUCCESSFULLY POSTED MSG ON WALL", Toast.LENGTH_SHORT).show();
}else if(values!=null)
Log.e("LOGINE SUCCESS", "LOGIN SUCCESS");
Toast.makeText(getApplicationContext(), "SUCCESSFULLY LOGGED IN", Toast.LENGTH_SHORT).show();
}
#Override
public void onFacebookError(FacebookError error) {
Log.e("onFBERROR", "ONFBERROR");
}
#Override
public void onError(DialogError e) {
Log.e("on DESI ERROR", "ON_ERROR");
}
#Override
public void onCancel() {
Log.e("onCANCEL", "ONCANCEL");
}
});
}
}
});
Which successfully posts on the Facebook wall, what i want is, I need to show the user that he has successfully signed in, and a message would be posted there after.
The Issue i face is the onComplete(Bundle values) method is called for both successful login and for successful post, how can i differentiate between both of them, is there a key in the Bundle values that can help to find the differnence?
Any suggestions are welcome.
Problem is that you are using for Authentication and Posting. No need to do like this :
For Authentication use
facebook.authorize(a, PERMISSIONS,-1,new LoginListener());
And for posting :
1) Without Dialog facebook.request(parameters)
2) With Dialog
facebook.dialog(this,"stream.publish",parameters,new TestUiServerListener());
public class TestUiServerListener implements DialogListener {
public void onComplete(Bundle values) {
final String postId = values.getString("post_id");
if (postId != null) {
new AsyncFacebookRunner(ZValues.authenticatedFacebook).request(postId,new TestPostRequestListener());
} else {
Post_Message_Title.this.runOnUiThread(new Runnable() {
public void run() {
}
});
}
}
public void onCancel() {
}
public void onError(DialogError e) {
e.printStackTrace();
}
public void onFacebookError(FacebookError e) {
e.printStackTrace();
}
}
public class TestPostRequestListener implements RequestListener {
public void onComplete(final String response, final Object state) {
try {
JSONObject json = Util.parseJson(response);
String postId = json.getString("id");
this.runOnUiThread(new Runnable() {
public void run() {
successLoginShowDialog(); // Dialog after Login succeeds
}
});
} catch (Throwable e) {
}
}
public void onFacebookError(FacebookError e, final Object state) {
e.printStackTrace();
}
public void onFileNotFoundException(FileNotFoundException e,
final Object state) {
e.printStackTrace();
}
public void onIOException(IOException e, final Object state) {
e.printStackTrace();
}
public void onMalformedURLException(MalformedURLException e,
final Object state) {
e.printStackTrace();
}
}
Just create a method successLoginShowDialog() and show whatever you want ,
If Post is success , In TestPostRequestListener below Thread will be called , so do all stuffs in this Thread :
this.runOnUiThread(new Runnable() {
public void run() {
successLoginShowDialog(); // Dialog after Login succeeds
}
});
to postOnWall() you can get its response:
public void postToWall(String message) {
Bundle parameters = new Bundle();
parameters.putString("message", message);
parameters.putString("description", "topic share");
try {
fbObj.request("me");
String response = fbObj.request("me/feed", parameters, "POST");
Log.d("Tests", "got response: " + response);
if (response == null || response.equals("")
|| response.equals("false")) {
// showToast("Blank response.");
Toast.makeText(context, "blank response", Toast.LENGTH_SHORT)
.show();
} else {
// showToast("Message posted to your facebook wall!");
Toast.makeText(context,
"Message posted to your facebook wall!",
Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
// showToast("Failed to post to wall!");
e.printStackTrace();
}
}

Categories

Resources