Using AccessToken stored in string variable in a new Graph Request - android

I am a novice programmer trying to use graph API to post a photo to a Facebook page.But I need the page access token for that.I stored the page accesssToken into a string variable using this..
AccessToken token=AccessToken.getCurrentAccessToken();
GraphRequest request = GraphRequest.newGraphPathRequest(
token,
"/me/accounts",
new GraphRequest.Callback() {
#Override
public void onCompleted(GraphResponse response) {
// Insert your code here
try {
JSONObject res=new JSONObject(response.toString());
JSONArray data=res.getJSONArray("data");
accessToken = "";
for(int i=0;i<data.length();i++){
JSONObject temp=data.getJSONObject(i);
if(temp.has("access_token")){
accessToken=temp.getString("access_token");
break;
}
}
}catch (JSONException e)
{
e.printStackTrace();
}
}
});
request.executeAsync();
Now I need to use this accessToken in another graph Request for posting the photos into the Facebook page.But since I have the token in string format I am not able to use it in the new Graph Request.
Can you guys help me with converting the string Token to an AccessToken Object.I have seen the Documentation but could not get an I idea on what to be done...so Please Help me..Thanks

Related

facebook graph android sdk - under what circumstance will server response be null?

sometimes randomly a few of my users are getting null values from facebook graph request. but the only thing im requesting from the user is a email address ? lets say the usr did not have a email address but used a phone number to register with facebook. then still why would the raw server response be null. For most of my users its working. anyway, let me show you what my graph request looks like to shed some light:
GraphRequest request = GraphRequest.newMeRequest(
token,
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject userInfo, GraphResponse response) {
if (userInfo == null)
Crashlytics.log("facebook graph info null:" + response.getRawResponse());
String email = "";
try {
email = userInfo.getString("email");
} catch (JSONException e1) {
e1.printStackTrace();
/* sometimes i end up in this catch block and the rawResponse object is null
}
presenter.presentPasswordPrompt(task, email, credential);
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "email");
request.setParameters(parameters);
request.executeAsync();
as you can see i am printing out a log when the user info is null but the value from response.getRawResponse() is null itself so i cant figure out what the issue is.

How to get user email and birthday from Facebook API Version v2.4

I am not able to get the facebook user email in API version v2.4. I have one app in api version2.3 it returns the email and other details of the user but now facebook updated the api version to new application. if i use the old application like veriosn <=2.3 its returning the user email by using the following code. But in api version 2.4 i am not able to get the email and date of birth.
GraphRequest.newMeRequest(result.getAccessToken(), new GraphRequest.GraphJSONObjectCallback()
{
#Override
public void onCompleted(JSONObject me, GraphResponse response)
{
if (response.getError() != null)
{
// handle error
}
else
{
Log.e("",""+me.toString());
Log.e("",""+response.getJSONObject().toString());
}
}
}).executeAsync();
You'll have to explicitly define which fields you want to retrieve with your request, for example /me?fields=id,name,email,birthday instead of just /me
See
https://developers.facebook.com/docs/apps/changelog#v2_4
To try to improve performance on mobile networks, Nodes and Edges in v2.4 requires that you explicitly request the field(s) you need for your GET requests. For example, GET /v2.4/me/feed no longer includes likes and comments by default, but GET /v2.4/me/feed?fields=comments,likes will return the data. For more details see the docs on how to request specific fields.
Since v2.4 you need include in your request the fields that you need.
GraphRequest request = GraphRequest.newMeRequest(
AccessToken.getCurrentAccessToken(), new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject userMe, GraphResponse response) {
if(userMe!=null){
//...... do your things
}
}
});
Bundle parameters = new Bundle();
//Add the fields that you need, you dont forget add the right permission
parameters.putString("fields","email,id,name,picture,birthday");
request.setParameters(parameters);
//Now you can execute
GraphRequest.executeBatchAsync(request);
Here is code block that worked for me:
GraphRequest request = GraphRequest.newMeRequest(loginResult.getAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
final JSONObject jsonObject = response.getJSONObject();
try{
email = jsonObject.getString("email");
first_name = jsonObject.getString("first_name");
last_name = jsonObject.getString("last_name");
gender = jsonObject.getString("gender");
birthday = jsonObject.getString("birthday");
} catch (JSONException e){
e.printStackTrace();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "email,first_name,last_name,gender,birthday");
request.setParameters(parameters);
request.executeAsync();
Hope this helps!

Facebook Graph API field expansion in Android app

Is field expansion supported in Facebook's Android SDK? where can I find an example?
There is great documentation on field expansion for the Graph APi. However, I cannot find any documentation for the android-sdk-3. Is it supported?
The problem starts when you want to do the following:
/me?fields=name,birthday,photos.limit(10).fields(id, picture)
In Facebook android SDK it seems that adding the parameters as a string doesn't work
E.g.
request = Request.newGraphPathRequest(session, "me/friendlists", new Request.Callback() {
public void onCompleted(Response response) ...
}
Bundle parameters = new Bundle();
parameters.putString("fields","members.fields(id)", "list_type");
request.setParameters(parameters);
Session session = Session.getActiveSession();
Bundle parameters = new Bundle();
parameters.putString("fields","picture,description,source");
new Request(session, /me/videos/uploaded, parameters, HttpMethod.GET,
new Request.Callback() {
public void onCompleted(Response response) {
GraphObject responseGraphObject = response
.getGraphObject();
JSONObject json = responseGraphObject
.getInnerJSONObject();
try {
JSONArray array = json.getJSONArray("data");
for (int i = 0; i < array.length(); i++) {
JSONObject main = array.getJSONObject(i);
String surce = main.optString("source");
String picture = main.optString("picture");
String videoname = main
.optString("description");
System.out.println(surce);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}).executeAsync();
*get video data from faecbook by graph api and also put string in bundle *
The Android SDK is used to make Graph API queries
You make the API calls with the same parameters and same return values as when making raw HTTP calls to graph.facebook.com or using the Graph API Explorer tool -
Just change your existing calls to the API to include the additional fields you want, following the syntax in the Field Expansion documentation, e.g. if you're currently calling /me/friends you can change it to /me/friends?fields=name,birthday

Get friend interests using android facebook SDK

In my app my intention is to get some interests of a friend like music, books, tv. This information is public. For this I think I don't need to send a permission.
Based on facebook (poor)documentation, mainly this links:
Field Expansion to get friend interest I only need to pass friend ID in the expanded friends field.
Doing some tests on GraphExplorer I see it creates the following query to get movies form some friend:
MY_ID?fields=friends.uid(FRIEND_ID).fields(movies)
I use this and execute execute this code on a Request.newMyFriendRequest asynchronously:
Session activeSession = Session.getActiveSession();
if(activeSession.getState().isOpened()){
Request request = Request.newMyFriendsRequest(activeSession,
new GraphUserListCallback(){
#Override
public void onCompleted(List<GraphUser> users, Response response){
GraphUser user = users.get(0);
JSONObject friendLikes = user.getInnerJSONObject();
try {
JSONArray data = friendLikes.getJSONObject("friends").getJSONArray("data");
Log.i("JSON", friendLikes.toString());
addInterests(data, 0);
} catch (JSONException e) {
e.printStackTrace();
}
}
});
Bundle bundle = new Bundle();
bundle.putString("fields", "friends.uid("+friendID+").fields(movies)");
request.setParameters(bundle);
request.executeAsync();
All times I execute this code I receive the following error from JSON:
W/System.err(694): org.json.JSONException: No value for friends.
If this isn't the way to get friend interests using GraphAPI, what do I need to do to get these values?
[EDIT] Solved posting friends_likes permission on Login. Permission is not sended inside Request.
I modified a bit my solution. If anyone is interested:
String fqlQuery = "SELECT music, books, movies FROM user where uid ="+friendID;
Bundle bundle = new Bundle();
bundle.putString("q", fqlQuery);
Request request = new Request(activeSession, "/fql", bundle, HttpMethod.GET,
new Request.Callback() {
#Override
public void onCompleted(Response response) {
// TODO Auto-generated method stub
Log.i("INFO", response.toString());
}
});
Request.executeBatchAsync(request);

Android Facebook SDK - How To Query Facebook Notifications

I have the Facebook SDK for Android working in my app. I can't seem to find any examples or documentation on how to use the SDK code to get Notifications. I have the permission "manage_notifications" set and I am assuming that I need to use the .request() method, but the graphPath parameter eludes me.
Does anyone have an example of how to get the Facebook notifications using the Facebook SDK for Android?
While the other answers are helpfull, what I was looking for was an example of the Android Code. I have figured it out though and have posted it here. The code below gets the logged in/authenticated users notifications.
//Initialze your Facebook object, etc.
Facebook _facebook = ...
...
Bundle bundle = new Bundle();
bundle.putString(Facebook.TOKEN, _accessToken);
String result = _facebook.request("me/notifications", bundle, "GET");
Then you will need to parse the string "result". It's in json format. Here is an example of what that will look like:
JSONObject jsonObjectResults = new JSONObject(result);
JSONArray jsonNotificationDataArray = jsonObjectResults.getJSONArray("data");
for (int i=0;i<jsonNotificationDataArray.length();i++)
{
JSONObject jsonNotificationData = jsonNotificationDataArray.getJSONObject(i);
if (_debug) Log.v("Title: " + jsonNotificationData.getString("title"));
}
I hope that other people find this useful.
By default the /USER_ID/notifications endpoint only includes unread notifications (i.e there'll only be a return value if the third jewel on the top line of Facebook.com is lit up and has a red number inside it)
If you want to also include notifications the user has already read, you can make a request to /USER_ID/notifications?include_read=1 - manage_notifications is the correct extended permission for this
You can check the Session Object of Facebook SDK 3.0 to ensure the Session is opened.
After that you can get the JSON data with the help of following code:
Session session = Session.getActiveSession();
if (session.isOpened())
{
//access_token = session.getAccessToken();
Request graphRequest = Request.newGraphPathRequest(session, "me/home", new
Request.Callback()
{
public void onCompleted(Response response)
{
//Create the GraphObject from the response
GraphObject responseGraphObject = response.getGraphObject();
//Create the JSON object
JSONObject json = responseGraphObject.getInnerJSONObject();
Log.i("JSON", json.toString());
try
{
YOUR_JSON_ARRAY= json.getJSONArray("data");
}
catch (JSONException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
Request.executeBatchAsync(graphRequest);
}
You can also use a FQL query. The format of the query will be
SELECT notification_id, sender_id, title_html, body_html, href
FROM notification
WHERE recipient_id=userid
AND is_unread = 1
AND is_hidden = 0
Please refer to this page for details http://developers.facebook.com/docs/reference/fql/notification/
The results of this query can be received in onComplete() of a listener which implements BaseRequestListener.
This is how I get notifications
final Session session =Session.getActiveSession();
if(session.isOpened()){
String aaa=new String();
aaa="SELECT title_text,updated_time FROM notification WHERE recipient_id=me() AND is_unread=1";
Bundle params = new Bundle();
params.putString("q", aaa);
new Request(session,"/fql",params,HttpMethod.GET,new Request.Callback() {
public void onCompleted(Response response) {
try
{
GraphObject go = response.getGraphObject();
JSONObject jso = go.getInnerJSONObject();
JSONArray arr = jso.getJSONArray( "data" );
String splitting=arr.toString().replaceAll("\\\\|\\{|\\}|\\[|\\]", "");
String[] arrayresponse=splitting.split("\\,");
String s = "";
for (int i = 0; i < arrayresponse.length; i++) {
if (arrayresponse[i].length()>13){
if (arrayresponse[i].substring(1,13).equals("updated_time"))
s+="* "+getDate(Long.valueOf(arrayresponse[i].substring(15,arrayresponse[i].length())))+"\n";
else
s+=" "+arrayresponse[i].substring(14,arrayresponse[i].length()-1)+"\n\n";
}
}
text2.setVisibility(View.VISIBLE);
NotificationMessage.setVisibility(View.VISIBLE);
NotificationMessage.setMovementMethod(new ScrollingMovementMethod());
NotificationMessage.setText(s);
readMailBox(session);
}catch ( Throwable t )
{
t.printStackTrace();
}
}
}
).executeAsync();
}
else{
// NotificationMessage.setVisibility(View.INVISIBLE);
Log.i(TAG, "Logged out...");
}
}

Categories

Resources