Fetch Facebook friends in android - android

I am working on an android app in which i need to login with Facebook and fetch facebook friends.
I am using below code for fetching facebook friends:
public class FriendsRequestListener implements RequestListener {
/**
* Called when the request to get friends has been completed.
* Retrieve and parse and display the JSON stream.
*/
public void onComplete(final String response) {
try {
// process the response here: executed in background thread
Log.d("Facebook-Example-Friends Request", "response.length(): " +
response.length());
Log.d("Facebook-Example-Friends Request", "Response: " + response);
final JSONObject json = new JSONObject(response);
JSONArray d = json.getJSONArray("data");
int l = (d != null ? d.length() : 0);
Log.d("Facebook-Example-Friends Request", "d.length(): " + l);
for (int i=0; i<l; i++) {
JSONObject o = d.getJSONObject(i);
String n = o.getString("name");
String id = o.getString("id");
}
// Only the original owner thread can touch its views
} catch (JSONException e) {
Log.w("Facebook-Example", "JSON Error in response");
}
}
#Override
public void onComplete(String response, Object state) {
// TODO Auto-generated method stub
}
#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
}
#Override
public void onFacebookError(FacebookError e, Object state) {
// TODO Auto-generated method stub
}
}
The way to call this class:
mAsyncRunner = new AsyncFacebookRunner(facebook);
mAsyncRunner.request("me/friends", new FriendsRequestListener());
The problem is that my code is not doing anything on call of above code.

you can use this api https://graph.facebook.com/v1.0/me/friends?fields=picture,id,username&limit=${limit}&access_token=${accessToken}
this is a v1.0 api which allows user to fetch all friends list

To get all your facebook friends list you need to get "taggable_friends"
GraphRequestAsyncTask r = GraphRequest.newGraphPathRequest(fbToken,
"/me/taggable_friends", new Callback() {
#Override
public void onCompleted(GraphResponse response) {
//here you can parse the response
}
}
fbToken is your token from login. However, facebook uses paging, so you need to get the next page and then next value from friends request so you can parse it.
response.getJSONObject("paging").getString("next");
to get next page users using StringRequest
StringRequest sr = new StringRequest(Request.Method.GET, next,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
JSONObject friends = null;
try {
friends = new JSONObject(response);
parseResponse(friends);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
Check the full code Facebook friends list

Related

Graph api android throws error code 2500

I am Upload video from my application and get the information of that video (likes,comments)
Problem 1
I have done uploading but when i get video information it throws me error
Error
{"error":{"message":"Cannot specify type in both the path and query parameter.","type":"OAuthException","code":2500}}
I am using Facebook SDK 3.8
Problem 2
When i upload video it Only visible in my account but not visible from other account even though it is public
Code For Upload Video
private void Upload_Video() {
mDialog = new ProgressDialog(AndroidFacebookConnectActivity.this);
mDialog.setMessage("Uploding video...");
mDialog.show();
String path="/mnt/sdcard/abc/Mirror.mp4";
if (new File(path).exists()) {
try {
Bundle param;
try {
InputStream is = new FileInputStream(path);
byte[] data = readBytes(is);
param = new Bundle();
param.putString("title", "Test 2");
param.putString("message", "uploaded");
param.putByteArray("video.mov", data);
param.putString("contentType", "video/quicktime");
mAsyncRunner.request("kmavadhiya/videos", param, "POST",new FBRequestListener(), null);
Toast.makeText(getApplicationContext(), "Uploading...", Toast.LENGTH_SHORT).show();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
} else {
Toast.makeText(getApplicationContext(), "No videos found in sdcard ",Toast.LENGTH_SHORT).show();
}
}
public byte[] readBytes(InputStream inputStream) throws IOException {
// This dynamically extends to take the bytes you read.
ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
// This is storage overwritten on each iteration with bytes.
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
// We need to know how may bytes were read to write them to the byteBuffer.
int len = 0;
while ((len = inputStream.read(buffer)) != -1) {
byteBuffer.write(buffer, 0, len);
}
// And then we can return your byte array.
return byteBuffer.toByteArray();
}
Upload Request Listner
public class FBRequestListener implements RequestListener {
#Override
public void onComplete(String response, Object state) {
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(AndroidFacebookConnectActivity.this, "Upload Video Successfully...",Toast.LENGTH_LONG).show();
mDialog.dismiss();
}
});
Log.e("response", response);
try {
JSONObject jObject = new JSONObject(response);
String Id = (String) jObject.get("id");
Log.d("Video Id = ",""+Id);
Bundle param = new Bundle();
param.putString("type", "uploaded");
mAsyncRunner.request("kmavadhiya/videos/"+Id, param, "GET",new VideoDataRequestListener(), null);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void onIOException(IOException e, Object state) {
e.printStackTrace();
}
#Override
public void onFileNotFoundException(FileNotFoundException e,
Object state) {
Log.e("", "onFileNotFoundException");
e.printStackTrace();
}
#Override
public void onMalformedURLException(MalformedURLException e,
Object state) {
Log.e("", "onMalformedURLException");
e.printStackTrace();
}
#Override
public void onFacebookError(FacebookError e, Object state) {
Log.e("", "onFacebookError");
e.printStackTrace();
}
}
Video Data Listner
public class VideoDataRequestListener implements RequestListener {
#Override
public void onComplete(String response, Object state) {
// TODO Auto-generated method stub
Log.e("response", response);
}
#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
}
#Override
public void onFacebookError(FacebookError e, Object state) {
// TODO Auto-generated method stub
}
}
If I changed This Line
mAsyncRunner.request("kmavadhiya/videos/"+Id, param, "GET",new VideoDataRequestListener(), null);
With
mAsyncRunner.request("kmavadhiya/videos/", param, "GET",new VideoDataRequestListener(), null);
** I got Blank Response**
Reference
Link 1
Graph Api Reference Link
I Forget To Request Permission At Login time So Its Authentication Error
Add This In Login click
Session session = Session.getActiveSession();
if (!session.isOpened() && !session.isClosed()) {
session.openForRead(new Session.OpenRequest(this)
.setPermissions(Arrays.asList("basic_info","user_about_me","email","video_upload","user_videos")) // Permission List That You Want To Get
.setCallback(statusCallback));
} else {
Session.openActiveSession(this, true, statusCallback);
}
Reference
Permission List
https://developers.facebook.com/docs/facebook-login/access-tokens/
Set Permission Reference
https://developers.facebook.com/docs/android/login-with-facebook#permissions

Unable get all fields of friend list in facebook sdk sample and In Friend Picker Sample getting only id,name in android

I am developing facebok sample demo for get all friend list of login user.
I am running Friend Picker Sample successfully,But getstuck to extract all the details of friends like email,first_name,last_name etc.I am getting only id,name.
If anyone have idea please reply.
Here is mycode:-
public void getFriends(Properties properties, final OnFriendsRequestListener onFriendsRequestListener)
{
// if we are logged in
if (isLogin())
{
// move these params to method call parameters
Session session = getOpenSession();
Bundle bundle = null;
if (properties != null)
{
bundle = properties.getBundle();
}
Request request = new Request(session, "me/friends", bundle, HttpMethod.GET, new Request.Callback()
{
#Override
public void onCompleted(Response response)
{
List<GraphUser> graphUsers = typedListFromResponse(response, GraphUser.class);
FacebookRequestError error = response.getError();
if (error != null)
{
// log
logError("failed to get friends", error.getException());
// callback with 'exception'
if (onFriendsRequestListener != null)
{
onFriendsRequestListener.onException(error.getException());
}
}
else
{
// callback with 'complete'
if (onFriendsRequestListener != null)
{
List<Profile> friends = new ArrayList<Profile>(graphUsers.size());
for (GraphUser graphUser: graphUsers)
{
friends.add(Profile.create(graphUser));
}
onFriendsRequestListener.onComplete(friends);
}
}
}
});
RequestAsyncTask task = new RequestAsyncTask(request);
task.execute();
// callback with 'thinking'
if (onFriendsRequestListener != null)
{
onFriendsRequestListener.onThinking();
}
}
else
{
String reason = Errors.getError(ErrorMsg.LOGIN);
logError(reason, null);
// callback with 'fail' due to not being loged
if (onFriendsRequestListener != null)
{
onFriendsRequestListener.onFail(reason);
}
}
}
Thanks in advance...
After very sturggle i try some methods and finally found solution.
public void getFriendsList() {
Bundle bundle=new Bundle();
bundle.putString("fields","id,name,first_name,last_name,email,picture,gender,birthday,work");
mAsyncRunner.request("me/friends",bundle,friendsRequsetListener,null);
}
RequestListener friendsRequsetListener =new RequestListener() {
#Override
public void onMalformedURLException(MalformedURLException e, Object state) {
// TODO Auto-generated method stub
}
#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 onFacebookError(FacebookError e, Object state) {
// TODO Auto-generated method stub
}
#Override
public void onComplete(String response, Object state) {
// TODO Auto-generated method stub
String json = response;
try {
Log.e("Response","========>"+json);
}
catch(Exception e){
}
}
};
I hope this will help others. Thanks!!

Post text on facebook wall

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

Facebook Tagged photos in android -> facebook sdk

I am using the facebook api to do an android application. It asks the user to select friends to see tagged photos. (That is if the user selects two names A and B -> he should be able to see A and B in one photo). To do this pragmatically, I user the graph api explorer but finding it difficult to come up with the request call. Please refer the image:
For my query, above information should be used. That is, I need to get "picture" when I supply "id(userID)"..
Please tell me how this has to be done!
There are five steps involved with this:
step 1:
Login to Facebook:
private void loginToFacebook()
{
mPrefs = activity.getPreferences(Context.MODE_PRIVATE);
facebook = new Facebook(APP_ID);
accessToken = mPrefs.getString("access_token", null);
long expires = mPrefs.getLong("access_expires", 0);
if (accessToken != null)
{
facebook.setAccessToken(accessToken);
uploadPhoto(facebook, imageBitmap, null);
}
if (expires != 0)
{
facebook.setAccessExpires(expires);
}
if (!facebook.isSessionValid())
{
facebook.authorize(activity, new String[] {"publish_stream"}, Facebook.FORCE_DIALOG_AUTH, new DialogListener() {
public void onFacebookError(FacebookError arg0) {
// TODO Auto-generated method stub
}
public void onError(DialogError arg0) {
// TODO Auto-generated method stub
}
public void onComplete(Bundle arg0) {
SharedPreferences.Editor editor = mPrefs.edit();
editor.putString("access_token", facebook.getAccessToken());
editor.putLong("access_expires", facebook.getAccessExpires());
editor.commit();
uploadPhoto(facebook, imageBitmap, null);
}
public void onCancel() {
// TODO Auto-generated method stub
}
});
}
}
Step 2:
Upload the image to Facebook (bitmap is uploaded), note that this method is called within the login method. FOllowing method returns the ID of the uploaded image, so this is needed when tagging friends:
public String uploadPhoto(Facebook facebook, Bitmap image, String albumId)
{
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
if ( albumId == null ) {
albumId = "me";
}
ByteArrayOutputStream bos = new ByteArrayOutputStream();
image.compress(CompressFormat.JPEG, 75, bos);
byte[] photoBytes = bos.toByteArray();
Bundle params = new Bundle();
params.putString(facebook.TOKEN, accessToken);
params.putByteArray("picture", photoBytes);
try {
#SuppressWarnings("deprecation")
String resp = facebook.request(albumId + "/photos", params, "POST");
JSONObject json = Util.parseJson(resp);
if(json.getString("id") != null){
Toast.makeText(activity, "Image Successfully uploaded to facebook!", Toast.LENGTH_SHORT).show();
tagFriends();
}else{
Toast.makeText(activity, "Uploading failed, please try again!", Toast.LENGTH_SHORT).show();
}
uploadedImageID = json.getString("id");
return json.getString("id");
} catch ( IOException e ) {
Toast.makeText(activity, "Uploading failed, please try again!", Toast.LENGTH_SHORT).show();
} catch ( FacebookError e ) {
Toast.makeText(activity, "Uploading failed, please try again!", Toast.LENGTH_SHORT).show();
} catch ( JSONException e ) {
Toast.makeText(activity, "Uploading failed, please try again!", Toast.LENGTH_SHORT).show();
}
return null;
}
Step 3:
Get all friends of your facebook account and store in a hash map:
Bundle params = new Bundle();
params.putString(Facebook.TOKEN, accessToken);
mAsyncRunner.request("me/friends" , params , "GET", new RequestListener()
{
#Override
public void onMalformedURLException(MalformedURLException e, Object state)
{
}
#Override
public void onIOException(IOException e, Object state)
{
}
#Override
public void onFileNotFoundException(FileNotFoundException e, Object state)
{
}
#Override
public void onFacebookError(FacebookError e, Object state)
{
}
#Override
public void onComplete(String response, Object state)
{
try
{
JSONObject responseJsonObject = new JSONObject(response);
Log.d("InviteFriends.inviteFriends().new RequestListener() {...}:onComplete", "FB Response =>"+ responseJsonObject);
//event_id = event.getString("id");
//JSONObject responseJsonObject = new JSONObject(eventResponse);
JSONArray jsonArray = responseJsonObject.getJSONArray("data");
for (int i = 0; i < jsonArray.length(); i++)
{
HashMap<String, String> map = new HashMap<String, String>();
JSONObject e = jsonArray.getJSONObject(i);
map.put("id", e.getString("id"));
map.put("name", e.getString("name"));
mylist.add(map);
userIds = e.getString("id");
userName = e.getString("name");
Log.d("MainActivity:getAllEvents", "Friend ID, Name:" + userIds + "," + userName);
}
}
catch (Exception e)
{
Log.e("log_tag", "Error parsing data "+e.toString());
}
Step 4:
Show the list of names in a listview and capture the user IDs of the user names that the user touches from the list and store them in an array:
final ListView friends = (ListView) findViewById(R.id.lst_frnds);
ListAdapter adapter = new SimpleAdapter(getApplicationContext(), mylist , R.layout.friends_main, new String[] {"name" }, new int[] {R.id.item_title});
Log.d( "size","Friends->" + mylist.size());
friends.setAdapter(adapter);
friends.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(final AdapterView<?> parent, View view, int position, long id) {
#SuppressWarnings("unchecked")
HashMap<String, String> o = (HashMap<String, String>) friends.getItemAtPosition(position);
String selectedName = o.get("name");
String selectedId = o.get("id");
Toast.makeText(MemeList.this, "Your friend " + selectedName + "' was selected.", Toast.LENGTH_SHORT).show();
selectedFriendsIDs.add(selectedId);
selectedFriendsNames.add(selectedName);
}
Step 5:
Tag selected friends from the list:
btnSendInvites.setText(selectedFriendsIDs.size() + " selected, tag them now?");
btnSendInvites.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//Tagging friends
for(int i = 0; i < selectedFriendsIDs.size(); i++){
String inputParm = uploadedImageID + "/tags?to=" + selectedFriendsIDs.get(i);
Bundle params = new Bundle();
params.putString(Facebook.TOKEN, accessToken);
mAsyncRunner.request(inputParm, params, "POST", new RequestListener()
{
#Override
public void onMalformedURLException(MalformedURLException e, Object state)
{
}
public void onIOException1(IOException e, Object state)
{
}
#Override
public void onFileNotFoundException(FileNotFoundException e, Object state)
{
}
#Override
public void onFacebookError(FacebookError e, Object state)
{
}
#Override
public void onComplete(String response, Object state)
{
Log.d("Selected IDs ", "" + selectedFriendsIDs);
}
#Override
public void onIOException(IOException e, Object state)
{
// TODO Auto-generated method stub
}
}, null);
}
}
});
If successfully tagged, will return true.
Hope this helps someone!

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

Categories

Resources