5

I want to show friend list after log in to facebook through my app in a ListView. But my code is not working. I have also used classes like friendsArrayAdapter. I have used following code

protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.friendlist_screen);
    facebook = new Facebook(APP_ID);
    mAsyncRunner = new AsyncFacebookRunner(facebook);

    lv = (ListView) findViewById(R.id.friendsList);
    friendsArrayAdapter = new FriendsArrayAdapter(this, R.layout.rowlayout, friends);
    lv.setAdapter(friendsArrayAdapter);
}

FriendsRequestListener.class

public class FriendsRequestListener implements com.facebook.android.AsyncFacebookRunner.RequestListener {

    public void onComplete(final String response, Object state) {
        mSpinner.dismiss();
        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");
                Friend f = new Friend();
                f.id = id;
                f.name = n;
                friends.add(f);
            }
            // Only the original owner thread can touch its views
            FrndActivity.this.runOnUiThread(new Runnable() {
                public void run() {
                    friendsArrayAdapter = new FriendsArrayAdapter(
                        FrndActivity.this, R.layout.rowlayout, friends);
                    lv.setAdapter(friendsArrayAdapter);
                    friendsArrayAdapter.notifyDataSetChanged();
                }
            });
        } catch (JSONException e) {
            Log.w("Facebook-Example", "JSON Error in response");
        }
    }

Please sugest how to show the names in ListView and if I need to make any other classes for this thing?

Renjith
  • 5,783
  • 9
  • 31
  • 42
Nidhi
  • 699
  • 13
  • 26

1 Answers1

5

MainActivity.java

    import java.io.FileNotFoundException;
    import java.io.IOException;
    import java.net.MalformedURLException;
    import java.util.ArrayList;

    import org.json.JSONArray;
    import org.json.JSONException;
    import org.json.JSONObject;

    import com.facebook.android.AsyncFacebookRunner;
    import com.facebook.android.AsyncFacebookRunner.RequestListener;
    import com.facebook.android.DialogError;
    import com.facebook.android.Facebook;
    import com.facebook.android.FacebookError;
    import com.facebook.android.Facebook.DialogListener;
    import com.facebook.android.Util;
    import android.app.Activity;
    import android.content.Intent;
    import android.content.SharedPreferences;
    import android.os.Bundle;
    import android.util.Log;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.view.Window;
    import android.view.WindowManager;
    import android.widget.Button;
    import android.widget.ListView;
    import android.widget.Toast;

    @SuppressWarnings("deprecation")
    public class MainActivity extends Activity {

        // Your Facebook APP ID
        private static String APP_ID = "197574013719352"; // Replace your App ID here

        // Instance of Facebook Class
        public static Facebook facebook = null;
        public static AsyncFacebookRunner mAsyncRunner = null;
        String FILENAME = "AndroidSSO_data";
        private SharedPreferences mPrefs;
        String _error;

        Button button;

        ArrayList<String> friends_list;
        ListView lv;

        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);

            this.requestWindowFeature(Window.FEATURE_NO_TITLE);
            getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

            setContentView(R.layout.main);

            facebook = new Facebook(APP_ID);
            mAsyncRunner = new AsyncFacebookRunner(facebook);   
            friends_list = new ArrayList<String>();
            button = (Button) findViewById(R.id.button);
            lv = (ListView) findViewById(R.id.list);

            button.setOnClickListener(new OnClickListener()
            {

                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    loginToFacebook();
                }

            });

        }

        public void loginToFacebook() {
            mPrefs = getPreferences(MODE_PRIVATE);

            if (!facebook.isSessionValid()) {
                facebook.authorize(this, new String[] { "email", "publish_stream" },
                        new DialogListener() {

                            @Override
                            public void onCancel() {
                                // Function to handle cancel event
                            }

                            @Override
                            public void onComplete(Bundle values) {
                                // Function to handle complete event
                                // Edit Preferences and update facebook acess_token
                                SharedPreferences.Editor editor = mPrefs.edit();
                                editor.putString("access_token",
                                        facebook.getAccessToken());
                                editor.putLong("access_expires",
                                        facebook.getAccessExpires());
                                editor.commit();     

                                mAsyncRunner.request("me/friends", new FriendsRequestListener());

                                Toast.makeText(getApplicationContext(), "Success ", Toast.LENGTH_LONG).show();

                                button.setText("LogOut");

                            }

                            @Override
                            public void onError(DialogError error) {
                                // Function to handle error

                            }

                            @Override
                            public void onFacebookError(FacebookError fberror) {
                                // Function to handle Facebook errors

                            }

                        });
            }
        }

        private class FriendsRequestListener implements RequestListener {
            String friendData;

            //Method runs when request is complete
            public void onComplete(String response, Object state) {
                Log.v("", "FriendListRequestONComplete");
                //Create a copy of the response so i can be read in the run() method.
                friendData = response; 
                Log.v("friendData--", ""+friendData);
                //Create method to run on UI thread
                MainActivity.this.runOnUiThread(new Runnable() {
                    public void run() {
                        try {
                            //Parse JSON Data
                            JSONObject json;
                            json = Util.parseJson(friendData);

                            //Get the JSONArry from our response JSONObject
                            JSONArray friendArray = json.getJSONArray("data");

                            Log.v("friendArray--", ""+friendArray);

                            for(int i = 0; i< friendArray.length(); i++)
                            {
                                JSONObject frnd_obj = friendArray.getJSONObject(i);
                                friends_list.add(frnd_obj.getString("name")+"~~~"+frnd_obj.getString("id"));
                            }

  Intent ide = new Intent(MainActivity.this,Next.class);
                                ide.putStringArrayListExtra("friends", friends_list);
                                ide.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                                startActivity(ide);

                          //  ArrayAdapter<String> adapter = new ArrayAdapter<String>(getBaseContext(), android.R.layout.simple_list_item_1,android.R.id.text1, friends_list);
                         //   lv.setAdapter(adapter);

                        } catch (JSONException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        } catch (FacebookError e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                });
            }

            @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

            }
            }

    }

Next.java

    import java.util.ArrayList;

    import android.app.Activity;
    import android.content.Intent;
    import android.os.Bundle;
    import android.view.Window;
    import android.view.WindowManager;
    import android.widget.ArrayAdapter;
    import android.widget.ListView;

    public class Next extends Activity{

        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);

            this.requestWindowFeature(Window.FEATURE_NO_TITLE);
            getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
            setContentView(R.layout.list);

            Intent i = getIntent();

            ArrayList<String> friends_data = i.getStringArrayListExtra("friends");

            ListView lv = (ListView) findViewById(R.id.list);

            ArrayAdapter<String> adapter = new ArrayAdapter<String>(getBaseContext(), android.R.layout.simple_list_item_1,android.R.id.text1, friends_data);
            lv.setAdapter(adapter);

        }

    }
Mohammed
  • 13
  • 3
Hariharan
  • 24,741
  • 6
  • 50
  • 54
  • its not working. i tried many times but the friend list is not opening in list view. can u pls suggest other way/ – Nidhi Aug 09 '13 at 11:08
  • actually i am using this code now but don't know where the problem is! – Nidhi Aug 12 '13 at 04:18
  • error in logcat: I/dalvikvm(5443): Could not find method android.support.v4.content.LocalBroadcastManager.getInstance, referenced from method com.facebook.Session.postActiveSessionAction and it also shows " W/Facebook-Example(5443): JSON Error in response" – Nidhi Aug 12 '13 at 08:31
  • Here i pasted all codes with list of friends... http://mahahari777.blogspot.in/2013/08/how-to-retrieve-facebook-contacts-and.html – Hariharan Aug 12 '13 at 08:57
  • this is really useful. thank you. but i am using two different activities ,one for login button and other for list view. and now if i am putting "mAsyncRunner.request("me/friends", new FriendsRequestListener());" in onComplete() method of login,it suggests to make a class FriendsRequestListener. but i made dis one in list view activity. how can i link these both.i use that class as above. – Nidhi Aug 12 '13 at 09:11
  • Use arraylist as public static ArrayList friends_list; after getting details i toast as success after that add Intent ide = new Intent(MainActivity.this,Next.class); ide.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(ide); then use the public arraylist in Next.class and display as listview.. – Hariharan Aug 12 '13 at 09:21
  • i have used only one listview in frnd list screen. i want that when login button is clicked ,after successful login,the second activity opens and also the frnd list of user shows in list view. i have used row layout text box for the name only that would save in the list view – Nidhi Aug 13 '13 at 06:06
  • 1
    I have edited and pasted new version of the code here http://pastebin.com/5fCRxtLd – Hariharan Aug 13 '13 at 06:16
  • you have declared two intents.. and in first intent you have not passed the friends data. So, remove the first intent which will make it work fine. – Hariharan Aug 13 '13 at 06:17
  • i am facing a prblm.When the user is on the FriendList screen and hits back,the user is taken to the login screen but the login button doesn't work after these steps.and also When the user after logging in goes to the background the app asks for the user to login again.This is incorrect,the user should be able to stay logged in after coming back to foreground and the same screen should show up where the user left. pls suggest – Nidhi Aug 13 '13 at 09:17
  • use boolean for that if logout means take that as false if does't logout means take as true... – Hariharan Aug 13 '13 at 10:01
  • hi Hari. can u please tell how to add friends picture with names in list view in this code? i am new to android and i think your methods are easy as well as very effective to make a wonderful app.. thank you in advance. – Nidhi Aug 14 '13 at 06:42
  • i also want to knw should i have to delete ArrayAdapter adapter = new ArrayAdapter(getBaseContext(),R.layout.rowlayout,R.id.rowtext_top, friends); lv.setAdapter(adapter); – Nidhi Aug 14 '13 at 09:44
  • i am done with it. thanks 4 ur help in fetching friends names – Nidhi Aug 23 '13 at 06:20
  • Hii hari.. I use your above code but not get anything. Please help me for get Friends List... – patel135 Feb 23 '15 at 10:16