Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
639 views
in Technique[技术] by (71.8m points)

android - how to find out or fetch all friend list of facebook with their profile pic,name and id

I am working in one application in which I have to fetch all the friends list from Facebook.

I have implemented code like this :

Facebook mFacebook = new Facebook("141118172662401");
AsyncFacebookRunner mAsyncRunner = new AsyncFacebookRunner(mFacebook);
Bundle params = new Bundle();
params.putString("fields", "name,id");
mAsyncRunner.request("me/friends", params, "GET", new FriendListRequestListener(), null);
    }
});
}

public class FriendListRequestListener {
  public void onComplete(final String response) {
      _error = null;
        try {
            JSONObject json = Util.parseJson(response);
            final JSONArray friends = json.getJSONArray("data");
            FacebookFriendsActivity.this.runOnUiThread(new Runnable() {
                JSONObject data;
                public void run() {
                try{

                    try {
                        data = Util.parseJson(response);
                    } catch (FacebookError e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    JSONArray friendsData = data.getJSONArray("data");
                   // mDbAdapter.deleteAllFriends();

                    for (int i = 0; i < friendsData.length(); i++) {
                        JSONObject friend = friendsData.getJSONObject(i);
                       /* mDbAdapter.addFriend(friend.getString("name"),
                                friend.getString("id"));*/
                    }
                    }catch (Exception e) {
                        // TODO: handle exception
                    }
                }
            });

        } catch (JSONException e) {
            _error = "JSON Error in response";
        } catch (FacebookError e) {
            _error = "Facebook Error: " + e.getMessage();
        }

        if (_error != null)
        {
            FacebookFriendsActivity.this.runOnUiThread(new Runnable() {
                public void run() {
                    Toast.makeText(getApplicationContext(), "Error occurred:  " + 
                                    _error, Toast.LENGTH_LONG).show();
                }
            });
        }
    }
}

Throws Error in this line :

mAsyncRunner.request("me/friends", params, "GET", new FriendListRequestListener(), null);

What is wrong in this? also added Asyncronous class..

If there are any other methods or sources to find out Facebook friends then please let me know.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

use this for getting Friend List.

    public class FriendsList extends Activity implements OnItemClickListener 
{

    private Handler mHandler;
    protected ListView friendsList;
    protected static JSONArray jsonArray;
    protected String graph_or_fql;

    /*
     * Layout the friends' list
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mHandler = new Handler();
        setContentView(R.layout.friends_list);

        Bundle extras = getIntent().getExtras();
        String apiResponse = extras.getString("API_RESPONSE");
        graph_or_fql = extras.getString("METHOD");
        try {
            if(graph_or_fql.equals("graph")) {
                jsonArray = new JSONObject(apiResponse).getJSONArray("data");
            } else {
                jsonArray = new JSONArray(apiResponse);
            }
        } catch (JSONException e) {
            showToast("Error: " + e.getMessage());
            return;
        }
        friendsList = (ListView)findViewById(R.id.friends_list);
        friendsList.setOnItemClickListener(this);
        friendsList.setAdapter(new FriendListAdapter(this));

        showToast(getString(R.string.can_post_on_wall));
    }

    /*
     * Clicking on a friend should popup a dialog for user to post on friend's wall.
     */

    @Override
    public void onItemClick(AdapterView<?> arg0, View v, int position, long arg3) {
        try {   
            final long friendId;
            if(graph_or_fql.equals("graph")) {
                friendId = jsonArray.getJSONObject(position).getLong("id");
            } else {
                friendId = jsonArray.getJSONObject(position).getLong("uid");
            }
            String name = jsonArray.getJSONObject(position).getString("name");


            new AlertDialog.Builder(this)
            .setTitle(R.string.post_on_wall_title)
            .setMessage(String.format(getString(R.string.post_on_wall), name))
            .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    Bundle params = new Bundle();
                    /*
                     * Source Tag: friend_wall_tag
                     * To write on a friend's wall, provide friend's UID in the 'to' parameter.
                     * More info on feed dialog - https://developers.facebook.com/docs/reference/dialogs/feed/
                     */
                    params.putString("to", String.valueOf(friendId));
                    params.putString("caption", getString(R.string.app_name));
                    params.putString("description", getString(R.string.app_desc));
                    params.putString("picture", Utility.HACK_ICON_URL);
                    params.putString("name", getString(R.string.app_action));
                    Utility.mFacebook.dialog(FriendsList.this, "feed", params, new PostDialogListener());
                }

            })
            .setNegativeButton(R.string.no, null)
            .show();
        } catch (JSONException e) {
            showToast("Error: " + e.getMessage());
        }
    }

    /*
     * Callback after the message has been posted on friend's wall.
     */
    public class PostDialogListener extends BaseDialogListener {
        public void onComplete(Bundle values) {
            final String postId = values.getString("post_id");     
            if (postId != null) {                                                                                   
                showToast("Message posted on the wall.");            
            } else {                                                                                                
                showToast("No message posted on the wall.");                                                                       
            }   
        }
    }

    public void showToast(final String msg) {
        mHandler.post(new Runnable() {
            public void run() {
                Toast toast = Toast.makeText(FriendsList.this, msg, Toast.LENGTH_LONG);
                toast.show();
            }
        });
    }

    /**
     * Definition of the list adapter
     */
    public class FriendListAdapter extends BaseAdapter {
        private LayoutInflater mInflater;
        FriendsList friendsList;

        public FriendListAdapter(FriendsList friendsList) {
            this.friendsList = friendsList;
            if(Utility.model == null) {
                Utility.model = new FriendsGetProfilePics();
            }
            Utility.model.setListener(this);
            mInflater = LayoutInflater.from(friendsList.getBaseContext());
        }

        @Override
        public int getCount() {
            return jsonArray.length();
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            JSONObject jsonObject = null;
            try {
                jsonObject = jsonArray.getJSONObject(position);
            } catch (JSONException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            View hView = convertView;
            if(convertView == null) {
                hView = mInflater.inflate(R.layout.friend_item, null);
                ViewHolder holder = new ViewHolder();
                holder.profile_pic = (ImageView)hView.findViewById(R.id.profile_pic);
                holder.name = (TextView) hView.findViewById(R.id.name);
                holder.info = (TextView) hView.findViewById(R.id.info);
                hView.setTag(holder);
            }

            ViewHolder holder = (ViewHolder) hView.getTag();
            try {
                if(graph_or_fql.equals("graph")) {
                    holder.profile_pic.setImageBitmap(Utility.model.getImage(jsonObject.getString("id"), jsonObject.getString("picture")));
                } else {
                    holder.profile_pic.setImageBitmap(Utility.model.getImage(jsonObject.getString("uid"), jsonObject.getString("pic_square")));
                }
            } catch (JSONException e) {
                holder.name.setText("");
            }
            try {
                holder.name.setText(jsonObject.getString("name"));
            } catch (JSONException e) {
                holder.name.setText("");
            }
            try {
                if(graph_or_fql.equals("graph")) {
                    holder.info.setText(jsonObject.getJSONObject("location").getString("name"));
                } else {
                    JSONObject location = jsonObject.getJSONObject("current_location");
                    holder.info.setText(location.getString("city") + ", " + location.getString("state"));
                }

            } catch (JSONException e) {
                holder.info.setText("");
            }
            return hView;
        }   

    }


    class ViewHolder {
        ImageView profile_pic;
        TextView name;
        TextView info;
    }
}

And for FriendsGetProfilePics

   public class FriendsGetProfilePics
{


    Hashtable<String, Bitmap> friendsImages;
    Hashtable<String, String> positionRequested;
    BaseAdapter listener;
    int runningCount = 0;
    Stack<ItemPair> queue;

    /*
     * 15 max async tasks at any given time.
     */
    final int MAX_ALLOWED_TASKS = 15;

    public FriendsGetProfilePics() {
        friendsImages = new Hashtable<String, Bitmap>();
        positionRequested = new Hashtable<String, String>();
        queue = new Stack<ItemPair>();
    }

    /*
     * Inform the listener when the image has been downloaded. 
     * listener is FriendsList here.
     */
    public void setListener(BaseAdapter listener) {
        this.listener = listener;
        reset();
    }

    public void reset() {
        positionRequested.clear();
        runningCount = 0;
        queue.clear();
    }

    /*
     * If the profile pictore has already been downloaded and cached, return it
     * else excecute a new async task to fetch it - 
     * if total async tasks >15, queue the request.
     */
    public Bitmap getImage(String uid, String url) {
        Bitmap image = (Bitmap)friendsImages.get(uid);
        if(image != null) {
            return image;
        }
        if(!positionRequested.containsKey(uid)) {
            positionRequested.put(uid, "");
            if (runningCount >= MAX_ALLOWED_TASKS) {
                queue.push(new ItemPair(uid, url));
            } else {
                runningCount++;
                new GetProfilePicAsyncTask().execute(uid, url);
            }
        }
        return null;
    }

    public void getNextImage() {
        if(!queue.isEmpty()) {
            ItemPair item = (ItemPair)queue.pop();
            new GetProfilePicAsyncTask().execute(item.uid, item.url);
        }
    }

    /*
     * Start a AsyncTask to fetch the request
     */
    private class GetProfilePicAsyncTask extends AsyncTask<Object, Void, Bitmap> {
         String uid;
         protected Bitmap doInBackground(Object... params) {
             this.uid = (String)params[0];
             String url = (String)params[1];
             return Utility.getBitmap(url);
         }

         protected void onPostExecute(Bitmap result) {
             runningCount--;
             if(result != null) {
                 friendsImages.put(uid, result);
                 listener.notifyDataSetChanged();
                 getNextImage();
             }
         }
    }

    class ItemPair {
        String uid;
        String url;

        public ItemPair(String uid, String url) {
            this.uid = uid;
            this.url = url;
        }
    }

}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...