0

I am trying to fetch facebook friends in my android app my code is working fine in lower android versions but it's showing NetworkOnMainThreadException in 4.0 and later versions.

Here is my code:

public static void getFaceBookFriendsIDs() {

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    JSONObject result = new JSONObject(facebook.request("me/friends"));
                    JSONArray friendsArray = result.getJSONArray("data");
                    //friendsList = new ArrayList<String>();
                    for (int i = 0; i < friendsArray.length(); i++) {
                        //friendsList.add(friendsArray.getJSONObject(i).getString("id"));
                        String id=friendsArray.getJSONObject(i).getString("id");
                        String name=friendsArray.getJSONObject(i).getString("name");
                        contactBean=new ContactBean();
                        contactBean.setFbId(id);
                        contactBean.setUserName(name);
                        com.interactiveapp.Constants.fbContactListArrayList.add(contactBean);
                    }
                } 
                catch (MalformedURLException e) {
                    e.printStackTrace();

                } 
                catch (JSONException e) {
                    e.printStackTrace();

                } 
                catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();

        /////////////HANDLE RESPONSE//////////
        Message m = new Message();
        m.obj="";
        m.arg1 =1 ;
        saveHandler.dispatchMessage(m);

    }
Ricky Khatri
  • 952
  • 2
  • 16
  • 42

1 Answers1

0

you have to add this lines in >= 4.0 Android os

StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);

or you can use: https://stackoverflow.com/a/16103640/1168654

Community
  • 1
  • 1
Dhaval Parmar
  • 18,812
  • 8
  • 82
  • 177