Facebook with android - Get ID
I have a line of code
String id = facebook.request("me");
System.out.println(id);
This returns all the details but i was wondering how to retu开发者_如何学编程rn Just the ID of the person?
Any ideas?
Thanks
JSONObject jObject = new JSONObject(authenticatedFacebook.request("me"));
String id =jObject.getString("id");
This will returns the Id of the Logged User..Similarly you can get all data by replacing the Tag Name..
Actually, Lena's answer is more efficient, and can work, but is missing one bit... The fields=id should be passed as a new Bundle object. Then you only get the ID in the response from Facebook.
Bundle bundle = new Bundle();
bundle.putString("fields", "id");
AsyncFacebookRunner asyncRunner = new AsyncFacebookRunner(facebook);
asyncRunner.request("me", bundle, new AsyncFacebookRunner.RequestListener() {
public void onMalformedURLException(MalformedURLException e, Object state) {
// TODO Auto-generated method stub
}
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 onFacebookError(FacebookError e, Object state) {
// TODO Auto-generated method stub
}
public void onComplete(String response, Object state) {
JSONObject jObject;
try {
jObject = new JSONObject(response);
Log.d("FACEBOOK ID", jObject.getString("id"));
} catch (JSONException e) {
e.printStackTrace();
}
}
});
In the documentation it says that you can request "me?fields=id"
instead of "me"
so that only the needed data is transmitted.
However, using the Android API mAsyncRunner.request("me?fields=id", ...)
results in the following error, even when under the same circumstances "me"
works fine:
{
"error": {
"message": "An active access token must be used to query information about the current user.",
"type": "OAuthException",
"code": 2500
}
}
So I guess getting the whole bunch of information and extracting the ID as Venky explained is the best way.
精彩评论