Android: get facebook friends list - android

I am using the Facebook SDK to post messages on walls.
Now I need to fetch the Facebook friends list. Can anybody help me with this?
-- Edit --
try {
Facebook mFacebook = new Facebook(Constants.FB_APP_ID);
AsyncFacebookRunner mAsyncRunner = new AsyncFacebookRunner(mFacebook);
Bundle bundle = new Bundle();
bundle.putString("fields", "birthday");
mFacebook.request("me/friends", bundle);
} catch(Exception e){
Log.e(Constants.LOGTAG, " " + CLASSTAG + " Exception = "+e.getMessage());
}
When I execute my activity, I'm not seeing anything, but in LogCat there is a debug message like:
06-04 17:43:13.863: DEBUG/Facebook-Util(409): GET URL: https://graph.facebook.com/me/friends?format=json&fields=birthday
And when I tried to access this url directly from the browser, I'm getting the following error response:
{
error: {
type: "OAuthException"
message: "An active access token must be used to query information about the current user."
}
}

You are about half way there. You've sent the request, but you haven't defined anything to receive the response with your results. You can extend BaseRequestListener class and implement its onComplete method to do that. Something like this:
public class FriendListRequestListener extends BaseRequestListener {
public void onComplete(final String response) {
_error = null;
try {
JSONObject json = Util.parseJson(response);
final JSONArray friends = json.getJSONArray("data");
FacebookActivity.this.runOnUiThread(new Runnable() {
public void run() {
// Do stuff here with your friends array,
// which is an array of JSONObjects.
}
});
} catch (JSONException e) {
_error = "JSON Error in response";
} catch (FacebookError e) {
_error = "Facebook Error: " + e.getMessage();
}
if (_error != null)
{
FacebookActivity.this.runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(), "Error occurred: " +
_error, Toast.LENGTH_LONG).show();
}
});
}
}
}
Then in your request you can specify the request listener to use for receiving the response from the request, like this:
mFacebook.request("me/friends", bundle, new FriendListRequestListener());

Using FQL Query
String fqlQuery = "SELECT uid, name, pic_square FROM user WHERE uid IN " +
"(SELECT uid2 FROM friend WHERE uid1 = me() LIMIT 25)";
Bundle params = new Bundle();
params.putString("q", fqlQuery);
Session session = Session.getActiveSession();
Request request = new Request(session,"/fql", params,HttpMethod.GET, new Request.Callback(){
public void onCompleted(Response response) {
Log.i(TAG, "Result: " + response.toString());
try{
GraphObject graphObject = response.getGraphObject();
JSONObject jsonObject = graphObject.getInnerJSONObject();
Log.d("data", jsonObject.toString(0));
JSONArray array = jsonObject.getJSONArray("data");
for(int i=0;i<array.length();i++)
{
JSONObject friend = array.getJSONObject(i);
Log.d("uid",friend.getString("uid"));
Log.d("name", friend.getString("name"));
Log.d("pic_square",friend.getString("pic_square"));
}
}catch(JSONException e){
e.printStackTrace();
}
}
});
Request.executeBatchAsync(request);

I was dealing with that and I found the answer.
The problem is that you want to access to your data without previous registration with your facebook token.
First, you must to define your Facebook variable:
Facebook mFacebook = new Facebook(getString(R.string.fb_id));
Later, define your AsyncFacebookRunner:
final AsyncFacebookRunner mAsyncRunner = new AsyncFacebookRunner(mFacebook);
Ok, now you must to authorize your request, with autorize method. Note that you must implement callback methods on DialogListener(), put attention on onComplete() method. On that method you must to run the friend fetch request. Now your request will pass because now you are authenticated.
Now the code:
mFacebook.authorize(this, fb_perms, new DialogListener(){
/**
* Triggered on a successful Facebook registration.
*/
public void onComplete(Bundle values) {
mAsyncRunner.request("me/friends", new FriendListRequestListener());
}
/**
* Triggered on a FacebookError.
*/
public void onFacebookError(FacebookError e) {
}
/**
* Triggered on a DialogError.
*/
public void onError(DialogError e) {
}
/**
* Triggered when the User cancels the Facebook Login.
*/
public void onCancel() {
}
});
You can use the FriendListRequestListener class that was post by #Kon
I hope this helps.
Cheers!

Hi Please check below link
Facebook API for Android: how to get extended info regarding user`s friends?
Post on user's friends facebook wall through android application

I faced the same problem yesterday.
I wondering if you have overriden the onActivityResult() function?
private Facebook mFacebook=null;
...
...
...
#Override
protected void onActivityResult(int requestCode,
int resultCode,
Intent data) {
mFacebook.authorizeCallback(requestCode, resultCode, data);
}

Check this answer in order to know how to get Facebook friend list and who of these friends have installed your app using new Facebook SDK 3.0 for Android.

I'm doing something like this is working good....
jsonObj = Util.parseJson(facebook.request("me/friends"));
JSONArray jArray = jsonObj.getJSONArray("data");
for(int i=0;i<jArray.length();i++){
JSONObject json_data = jArray.getJSONObject(i);
Log.v("THIS IS DATA", i+" : "+jArray.getJSONObject(i));
}
Hope it is helpful...

If somebody is reading this in late 2015, the answer and code is quite simple. Take a look at official documentation here (in the code window click on Android SDK).
Keep in mind that you need to have user_friends permission.
Bro tip for android-rx users - get your friends synchronously, then process message and return Observable:
public Observable<List<Friend>> execute() {
return Observable.defer(new Func0<Observable<List<Friend>>>() {
#Override
public Observable<List<Friend>> call() {
AccessToken a = AccessToken.getCurrentAccessToken();
if (Utils.isValid(a)) {
try {
GraphResponse res = new GraphRequest(AccessToken.getCurrentAccessToken(), "me/friends").executeAndWait();
// process result
return Observable.just(your friend list);
} catch (Exception e) {
// notify user or load again
}
}
// invalid access token -> notify user
}
}).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread());
}

Related

Querying friends' birthdays using updated facebook sdk

I am trying to access my friends' birthdays using the latest facebook sdk. Due to latest updates, I am forced to call the api multiple times to accomplish this. Once to fetch my friends and then use their user-id to query their birthdays.
The second query, the inner query to get birthdays, is being skipped altogether.
And I am not sure if I am even doing this right.
Here is my background AsyncTask class which contains the calls :
/**
* Background Async Task to Load all friends by making calls the Graph API
* */
class LoadAllFriends extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
...
}
/**
* getting All friends and birthdays from api
* */
protected String doInBackground(String... args) {
try
{
final AccessToken accessToken = AccessToken.getCurrentAccessToken();
GraphRequestAsyncTask graphRequestAsyncTask = new GraphRequest(
accessToken,
"/me/friends",
null,
HttpMethod.GET,
new GraphRequest.Callback() {
public void onCompleted(GraphResponse response) {
try
{
friends = response.getJSONObject().getJSONArray("data");
Log.d("Friends length",String.valueOf(friends.length()));
for (int l=0; l < friends.length(); l++)
{
final HashMap hm = new HashMap<String, Date>();
hm.put("uid", friends.getJSONObject(l).getString("id"));
hm.put("name",friends.getJSONObject(l).getString("name"));
GraphRequestAsyncTask graphRequestAsyncTask = new GraphRequest(
accessToken,
"/"+hm.get("uid"),
null,
HttpMethod.GET,
new GraphRequest.Callback() {
public void onCompleted(GraphResponse response) {
try
{
JSONArray birthday = response.getJSONObject().getJSONArray("data");
Log.d("birthday",(String) birthday.getJSONObject(0).get("birthday"));
hm.put("date", (Date) birthday.getJSONObject(0).get("birthday"));
} catch (Exception e) {
e.printStackTrace();
}
}}).executeAsync();
friendsList.add(hm);
}
DateFormat dateFormat = new SimpleDateFormat("MM/dd/yy");
Calendar cal = Calendar.getInstance();
Date date1 = dateFormat.parse(dateFormat.format(cal.getTime()));
cal.add(Calendar.DATE, 30);
Date date2 = dateFormat.parse(dateFormat.format(cal.getTime()));
Iterator<HashMap<String, Object>> iter = friendsList.iterator();
while (iter.hasNext())
{
HashMap<String, Object> map = iter.next();
Log.d("uid", (String) map.get("uid"));
Log.d("name", (String) map.get("name"));
Log.d("date", (String) map.get("date"));
/*if (date1.compareTo((Date) map.get("date")) < 0 ||
date2.compareTo((Date) map.get("date")) > 0)
{
friendsList.remove(map);
}*/
}
}
catch (JSONException e)
{
e.printStackTrace();
}
catch (ParseException e)
{
e.printStackTrace();
}
}
}
).executeAsync();
if (friendsList.size() > 0)
{
friendsFound = true;
}
else
{
friendsFound = false;
}
}
catch(NullPointerException e){
e.printStackTrace();
}
catch(RuntimeException e){
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url)
{
// dismiss the dialog after getting all events
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable()
{
public void run()
{
...
}
});
}
}
Here :
Log.d("birthday",(String) birthday.getJSONObject(0).get("birthday"));
in the inner api call is not displayed in the terminal. Log output is being displayed for friends.length() and from the iterator and only for uid and name. Log for date throws the following error :
AndroidRuntime: FATAL EXCEPTION: main
Process: com.supre.www.surprise, PID: 18142
java.lang.NullPointerException: println needs a message
at android.util.Log.println_native_inner(Native Method)
at android.util.Log.println_native(Log.java:290)
at android.util.Log.d(Log.java:323)
at com.supre.www.surprise.HomeActivity$LoadAllFriends$1.onCompleted(HomeActivity.java:237)
at com.facebook.GraphRequest$5.run(GraphRequest.java:1368)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5312)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:901)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:696)
Please Help!
You canĀ“t get the birthdays of friends who did not authorize your App, for privacy reasons. All friend permissions have been removed with v2.0 of the Graph API: https://developers.facebook.com/docs/apps/changelog#v2_0
You can only get birthdays of friends who authorized your App with user_friends and user_birthday, with the following API call: me/friends?fields=name,birthday
You can not access friends detail unless they have your app installed and made a login/signup inside your app with Facebook. Only
"summary": {
"total_count": 2
}
Only friends who installed this app are returned in API v2.0 and
higher. total_count in summary represents the total number of friends,
including those who haven't installed the app.
If any friends having your app installed, here is the code that will give access to their data:
GraphRequest request = GraphRequest.newMeRequest(
accessToken,
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
// Insert your code here
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "email,birthday,friends{birthday}");
request.setParameters(parameters);
request.executeAsync();
Let me know if anyone having issues!

How to get all details about friend lists from facebook

I have this snippet
AsyncFacebookRunner mAsyncRunner = new AsyncFacebookRunner(mFacebook);
Bundle bundle = new Bundle();
bundle.putString("fields", "birthday");
mAsyncRunner.request("me/friends", bundle, new FriendListRequestListener());
and it works somehow, I mean I can read the ids from all my friends.
But in I want to read everything how can I do that ?
String _error = null;
JSONObject json = Util.parseJson(response);
final JSONArray friends = json.getJSONArray("data");
for (int i = 0; i < friends.length(); i++) {
Log.v("id:", "id= "+friends.get(i).toString());
}
What should I do to get info about my friends and to read that info
I guess this is the key, this is from the example I found and it works fine
bundle.putString("fields", "birthday");
but when I put for example, doesn't works
bundle.putString("fields", "friends_relationships");
-----------------EDIT 1-------------------------
code for permissions
mFacebook.authorize(Example.this, new String[] {"offline_access", "user_interests", "friends_interests","friends_relationships","friends_relationship_details"},new DialogListener() {
#Override
public void onComplete(Bundle values) {}
#Override
public void onFacebookError(FacebookError error) {}
#Override
public void onError(DialogError e) {}
#Override
public void onCancel() {}
});
-------------- EDIT 2 --------------
{"error":{"message":"An active access token must be used to query information about the current user.","type":"OAuthException","code":2500}}
Graph API is the smart choice in most cases. To retrieve your friend information you need to collect some extended permissions from the user first. Then you can retrieve a lot more information other than the basic ones.
Following is a list of extended permissions related to friends different kind of information
friends_about_me
friends_activities
friends_birthday
friends_checkins
friends_education_history
friends_events
friends_games_activity
friends_groups
friends_hometown
friends_interests
friends_likes
friends_location
friends_notes
friends_online_presence
friends_photo_video_tags
friends_photos
friends_relationship_details
friends_relationships
friends_religion_politics
friends_status
friends_subscriptions
friends_videos
friends_website
friends_work_history
facebook.authorize(this, new String[] {"offline_access", "user_interests", "friends_interests"},
Edit :-
If your app needs more than this basic information to function, you
must request specific permissions from the user. This is accomplished
by passing String[] of permissions to the authorize method. The
following example shows how to ask for access to user's email address,
get extended access token and check-in user at a place:
facebook.authorize(this, new String[] { "email", "publish_checkins" },
new DialogListener() {
#Override
public void onComplete(Bundle values) {}
#Override
public void onFacebookError(FacebookError error) {}
#Override
public void onError(DialogError e) {}
#Override
public void onCancel() {}
}
);
Look at here for more details.
Edit :-
mAsyncRunner.request("me/friends?fields=id,name,birthday,relationship_status", new FriendListRequestListener());
JSONObject json = Util.parseJson(response);
final JSONArray friends = json.getJSONArray("data");
for(int i=0;i<friends.length();i++)
{
JSONObject object = friends.getJSONObject(i);
Log.i("------------------ Id",object.getString("id"));
Log.i("------------------ Name",object.getString("name"));
Log.i("------------------ RelationShip",object.getString("relationship_status"));
}
There are separate permissions for your friends relationships. Check out the permissions documentation.
You'll want to request -
friends_relationships
friends_relationship_details
This is now longer possible as of May 2015 when the v1.0 facebook Graph API got deprecated.
try this :
Bundle params = new Bundle();
params.putString("fields", "name, picture, location");
mAsyncFacebook.request("me/friends",params, new RequestListener(){
#Override
public void onComplete(String response, Object object) {
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(response);
} catch (JSONException e) {
Log.d(TAG,"Exception :"+e);
}
}
}
to know about the keys see this link : https://developers.facebook.com/docs/authentication/permissions/

Trouble with accessing friends using Facebook-Android SDK

I have been struggling with android and the Facebook's graph API and I'm sure this is a piece of cake for intermediate programmers. What I want is a very simple Android application that logs in a user to Facebook, get the users consent to access information and finally to seamlessly query the graph API to get the users friends. I mention the work seamless because I have seen many sample applications that require the user to push a "get friends" button but I do not want that. I wish to extract the users friends without requiring him to push anything.
I have pasted the code below. I am able to to log-in and grant permission to my application. Next, I expect it to display my friends but it just directs me to a blank page. The problem might be that I am accessing the graph API in the wrong place because the Logcat does not contain the messages I print before and after the request. Could you please help me.
public class FacebookLogin extends Activity {
Facebook mFacebook = new Facebook("XXXXXXXXXXXX");
AsyncFacebookRunner mAsyncRunner = new AsyncFacebookRunner(mFacebook);
View linearLayout;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
linearLayout = findViewById(R.id.main_layout);
mFacebook.authorize(this, new DialogListener() {
#Override
public void onComplete(Bundle values)
{
Log.d("Facebook-Example-Friends Request", "Started API request");
mAsyncRunner.request("me/friends", new FriendsRequestListener());
Log.d("Facebook-Example-Friends Request", "Finished API request");
}
#Override
public void onFacebookError(FacebookError error) {}
#Override
public void onError(DialogError e) {}
#Override
public void onCancel() {}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
mFacebook.authorizeCallback(requestCode, resultCode, data);
}
public class FriendsRequestListener implements RequestListener
{
/**
* Called when the request to get friends has been completed.
* Retrieve, parse and display the JSON stream.
*/
public void onComplete(final String response)
{
Log.d("Facebook-Example-Friends Request", "FriendsListenerOnComplete");
try
{
JSONObject json = Util.parseJson(response);
final JSONArray friends = json.getJSONArray("data");
FacebookLogin.this.runOnUiThread(new Runnable()
{
public void run()
{
int l = (friends != null ? friends.length() : 0);
for (int i=0; i<l; i++)
{
try
{
JSONObject o = friends.getJSONObject(i);
TextView tv = new TextView(FacebookLogin.this);
tv.setText(o.getString("name"));
((LinearLayout) linearLayout).addView(tv);
}
catch(JSONException e)
{
Toast.makeText(getApplicationContext(), "JSON parsing error", Toast.LENGTH_LONG);
}
}
}
});
}
catch(JSONException e)
{
Log.d("Facebook-Example-Friends Request", "JSON Error in response");
}
catch(FacebookError e)
{
Log.d("Facebook-Example-Friends Request", "Facebook Error in response");
}
}
}
}
i think you see this answer you got some idea..
Facebook/Twitter Integration in my android application
and
http://android-sample-solution.blogspot.com

Android: How to post update on Facebook wall automatically?

I want my android application to automatically post a preset message when the user click on a button. The preset message will be set by the user, so I am guessing that is not a violation of Facebook policies. How do I do this?
private static final String[] PERMISSIONS =
new String[] {"publish_stream", "read_stream", "offline_access"};
Facebook authenticatedFacebook = new Facebook(APP_ID);
postButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
authenticatedFacebook.authorize(Tests.this, PERMISSIONS,
new TestPostListener());
}
});
public class TestPostListener implements DialogListener {
public void onComplete(Bundle values) {
try {
Log.d("Tests", "Testing request for 'me'");
String response = authenticatedFacebook.request("me");
JSONObject obj = Util.parseJson(response);
Log.d("Tests", "Testing graph API wall post");
Bundle parameters = new Bundle();
parameters.putString("message", "Amit Siddhpura");
parameters.putString("description", "Hi Mr. Amit Siddhpura");
response = authenticatedFacebook.request("me/feed", parameters,
"POST");
Log.d("Tests", "got response: " + response);
} catch (Throwable e) {
e.printStackTrace();
}
}
public void onCancel() {
}
public void onError(DialogError e) {
e.printStackTrace();
}
public void onFacebookError(FacebookError e) {
e.printStackTrace();
}
}
You have to create Application on Facebook
And get authenticate from user, then you can get a access_token to post some message through Graph API
I think your application have to request extended permissions : publish_stream, offline_access
There is Facebook-Android-SDK source code on github, you can refer it.
http://developers.facebook.com/docs/guides/mobile
http://www.androidpeople.com/android-facebook-api-example-using-fbrocket/

Post on Facebook wall using Facebook Android SDK without opening dialog box

Using the Facebook SDK, I can login and store my access_token into a database. When I try to create a post, the Facebook wall is still empty on both my phone and emulator due to these problems:
1) I fetch an access_token from the database and pass the access_token to Facebook, but I'm not allowed to post on a wall.
2) I cannot post my message without opening a dialog box.
mPostButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
String message = "Post this to my wall";
Bundle params = new Bundle();
params.putString("message", message);
mAsyncRunner.request("me/feed", params, "POST", new WallPostRequestListener());
}
});
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;
Example.this.runOnUiThread(new Runnable() {
public void run() {
mText.setText(text);
}
});
}
}
How can I post to Facebook without opening the dialog box?
i applied following code and could successfully posted my message on wall.
public void postOnWall(String msg) {
Log.d("Tests", "Testing graph API wall post");
try {
String response = mFacebook.request("me");
Bundle parameters = new Bundle();
parameters.putString("message", msg);
parameters.putString("description", "test test test");
response = mFacebook.request("me/feed", parameters,
"POST");
Log.d("Tests", "got response: " + response);
if (response == null || response.equals("") ||
response.equals("false")) {
Log.v("Error", "Blank response");
}
} catch(Exception e) {
e.printStackTrace();
}
}
I updated my tutorial at http://www.integratingstuff.com/2010/10/14/integrating-facebook-into-an-android-application/ and it is now exactly answering this question.
It is based on and basically the same as Ankit's answer, but guides people from start to finish through implementing the whole process.
Well it's not that something gets posted on wall without informing user. When user allows your application, then the Android Facebook sdk presents another page, where there is a text that your applications sends, and a textBox where user can write on his wall, similar to the screenshot i have attached
The actual layout on mobile device is slightly different, but it's in the same format. This process is well shown in the sample examples of facebook android sdk.
Now check the question asked in this post:
Facebook Connect Android -- using stream.publish # http://api.facebook.com/restserver.php'>Facebook Connect Android -- using stream.publish # http://api.facebook.com/restserver.php
In that question look for these : postParams.put(), similar type of lines will be there in some of your JAVA files. These are the lines using which you can post the data to Facebook.
For example:
postParams.put("user_message", "TESTING 123");
is the message,
postParams.put("attachment", "{\"name\":\"Facebook Connect for Android\",\"href\":\"http://code.google.com/p/fbconnect-android/\",\"caption\":\"Caption\",\"description\":\"Description\",\"media\":[{\"type\":\"image\",\"src\":\"http://img40.yfrog.com/img40/5914/iphoneconnectbtn.jpg\",\"href\":\"http://developers.facebook.com/connect.php?tab=iphone/\"}],\"properties\":{\"another link\":{\"text\":\"Facebook home page\",\"href\":\"http://www.facebook.com\"}}}");
is the line where you are providing icon for application, description,caption, title etc.
I used Ankit's code for posting on facebook wall but his code give me error android.os.NetworkOnMainThreadException.
After searching on this problem a solution told me that put your code in AsyncTask to get rid out of this problem. After modified his code it's working fine for me.
The modified code is looks like:
public class UiAsyncTask extends AsyncTask<Void, Void, Void> {
public void onPreExecute() {
// On first execute
}
public Void doInBackground(Void... unused) {
// Background Work
Log.d("Tests", "Testing graph API wall post");
try {
String response = facebook.request("me");
Bundle parameters = new Bundle();
parameters.putString("message", "This test message for wall post");
parameters.putString("description", "test test test");
response = facebook.request("me/feed", parameters, "POST");
Log.d("Tests", "got response: " + response);
if (response == null || response.equals("") || response.equals("false")) {
Log.v("Error", "Blank response");
}
} catch(Exception e) {
e.printStackTrace();
}
return null;
}
public void onPostExecute(Void unused) {
// Result
}
}
This class helps me for sent messages on my Facebook wall WITHOUT dialog:
public class FBManager{
private static final String FB_ACCESS_TOKEN = "fb_access_token";
private static final String FB_EXPIRES = "fb_expires";
private Activity context;
private Facebook facebookApi;
private Runnable successRunnable=new Runnable(){
#Override
public void run() {
Toast.makeText(context, "Success", Toast.LENGTH_LONG).show();
}
};
public FBManager(Activity context){
this.context = context;
facebookApi = new Facebook(FB_API_ID);
facebookApi.setAccessToken(restoreAccessToken());
}
public void postOnWall(final String text, final String link){
new Thread(){
#Override
public void run(){
try {
Bundle parameters = new Bundle();
parameters.putString("message", text);
if(link!=null){
parameters.putString("link", link);
}
String response = facebookApi.request("me/feed", parameters, "POST");
if(!response.equals("")){
if(!response.contains("error")){
context.runOnUiThread(successRunnable);
}else{
Log.e("Facebook error:", response);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}.start();
}
public void save(String access_token, long expires){
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
Editor editor=prefs.edit();
editor.putString(FB_ACCESS_TOKEN, access_token);
editor.putLong(FB_EXPIRES, expires);
editor.commit();
}
public String restoreAccessToken(){
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
return prefs.getString(FB_ACCESS_TOKEN, null);
}
public long restoreExpires(){
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
return prefs.getLong(FB_EXPIRES, 0);
}
}

Categories

Resources