0

I'm trying to parse the foursquare venues and show them in a list. Earlier, I did it without asyncTask and ad a Runtime excpetion. So I add one, but I still have that kinf of error. I'm new on android and I don't realy understand the error.

Here is the LogCat

07-26 13:15:16.595: E/AndroidRuntime(11330): FATAL EXCEPTION: main
07-26 13:15:16.595: E/AndroidRuntime(11330): android.os.NetworkOnMainThreadException
07-26 13:15:16.595: E/AndroidRuntime(11330):    at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1118)
07-26 13:15:16.595: E/AndroidRuntime(11330):    at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
07-26 13:15:16.595: E/AndroidRuntime(11330):    at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
07-26 13:15:16.595: E/AndroidRuntime(11330):    at java.net.InetAddress.getAllByName(InetAddress.java:214)
07-26 13:15:16.595: E/AndroidRuntime(11330):    at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
07-26 13:15:16.595: E/AndroidRuntime(11330):    at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
07-26 13:15:16.595: E/AndroidRuntime(11330):    at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
07-26 13:15:16.595: E/AndroidRuntime(11330):    at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
07-26 13:15:16.595: E/AndroidRuntime(11330):    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:670)
07-26 13:15:16.595: E/AndroidRuntime(11330):    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:509)
07-26 13:15:16.595: E/AndroidRuntime(11330):    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
07-26 13:15:16.595: E/AndroidRuntime(11330):    at com.mykong.android.JSonResultActivity$BackgroundTask.doInBackground(JSonResultActivity.java:197)
07-26 13:15:16.595: E/AndroidRuntime(11330):    at com.mykong.android.JSonResultActivity$BackgroundTask.onPostExecute(JSonResultActivity.java:238)
07-26 13:15:16.595: E/AndroidRuntime(11330):    at com.mykong.android.JSonResultActivity$BackgroundTask.onPostExecute(JSonResultActivity.java:1)
07-26 13:15:16.595: E/AndroidRuntime(11330):    at android.os.AsyncTask.finish(AsyncTask.java:631)
07-26 13:15:16.595: E/AndroidRuntime(11330):    at android.os.AsyncTask.access$600(AsyncTask.java:177)
07-26 13:15:16.595: E/AndroidRuntime(11330):    at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
07-26 13:15:16.595: E/AndroidRuntime(11330):    at android.os.Handler.dispatchMessage(Handler.java:99)
07-26 13:15:16.595: E/AndroidRuntime(11330):    at android.os.Looper.loop(Looper.java:137)
07-26 13:15:16.595: E/AndroidRuntime(11330):    at android.app.ActivityThread.main(ActivityThread.java:4921)
07-26 13:15:16.595: E/AndroidRuntime(11330):    at java.lang.reflect.Method.invokeNative(Native Method)
07-26 13:15:16.595: E/AndroidRuntime(11330):    at java.lang.reflect.Method.invoke(Method.java:511)
07-26 13:15:16.595: E/AndroidRuntime(11330):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1027)
07-26 13:15:16.595: E/AndroidRuntime(11330):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:794)
07-26 13:15:16.595: E/AndroidRuntime(11330):    at dalvik.system.NativeStart.main(Native Method)

And here is the code

public class JSonResultActivity extends ListActivity {
   private static String urlSearch = "https://api.foursquare.com/v2/venues/search?ll=40.7,-74&radius=0&client_id=50QO00GZKUPA25PDGO1IY3UHMK3IBEMO2F4CTO5M2DBLVGQD&client_secret=MVJZGC3WT4V55DQPJYBFNZ5X3IACIDLFVM1HKA2WBTEHAXDF&v=20130703";



@Override
public void onCreate(Bundle savedInstanceState) {
  final String method = "GET";
  super.onCreate(savedInstanceState);
  new BackgroundTask(urlSearch, method, null).execute();
}

final class BackgroundTask extends AsyncTask<String, Void, String> {

    ArrayList<HashMap<String, String>> venuesList = new ArrayList<HashMap<String, String>>();

    private static final String TAG_VENUES = "venues";
    private static final String TAG_ID = "id";
    private static final String TAG_NAME = "name";
    private static final String TAG_CONTACT = "contact";
    private static final String TAG_LOCATION = "location";
    private static final String TAG_ADDRESS = "address";
    private static final String TAG_CROSS_STREET = "crossStreet";
    private static final String TAG_CITY = "city";
    private static final String TAG_STATE = "state";
    private static final String TAG_POSTAL_CODE = "postalCode";
    private static final String TAG_COUNTRY = "country";
    private static final String TAG_LAT = "lat";
    private static final String TAG_LNG = "lng";
    private static final String TAG_DISTANCE = "distance";

    public InputStream is = null;
    public JSONObject jObj;
    public String json = "";    


    // variables passed in:
    String url;
    String method = "GET";
    List<NameValuePair> params;

    // constructor
    public BackgroundTask(String url, String method, 
        List<NameValuePair> params)
    {
        this.url = url;
        this.method = method;
        this.params = params;
    }





    @Override
    public String doInBackground(String... urls) {

        String url = "https://api.foursquare.com/v2/venues/search?ll=40.7,-74&radius=0&client_id=50QO00GZKUPA25PDGO1IY3UHMK3IBEMO2F4CTO5M2DBLVGQD&client_secret=MVJZGC3WT4V55DQPJYBFNZ5X3IACIDLFVM1HKA2WBTEHAXDF&v=20130703";
        try {
            if(method == "POST"){
                DefaultHttpClient httpClient = new DefaultHttpClient();
                httpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY,
                        CookiePolicy.BROWSER_COMPATIBILITY);
                HttpPost httpPost = new HttpPost(url);
                httpPost.setEntity(new UrlEncodedFormEntity(params));

                HttpResponse httpResponse = httpClient.execute(httpPost);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();

            } else if(method == "GET"){
               /* DefaultHttpClient httpClient = new DefaultHttpClient();
                String paramString = URLEncodedUtils.format(params, "utf-8");
                url += "?" + paramString;
                HttpGet httpGet = new HttpGet(url);

                HttpResponse httpResponse = httpClient.execute(httpGet);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            json = sb.toString();
        } catch (Exception e) {
            Log.e("fail!", "Error convert stream to String: " + e.toString());
        }



        try {
            Thread.sleep(1000);         
        } catch (InterruptedException e) {
           e.printStackTrace();
        }

        return json;


    }

     protected void onPostExecute(String json) {
            try {
                json = doInBackground(url);
                jObj = new JSONObject(json);
            } catch (JSONException e) {
                Log.e("JSON Parser", "Error parsing data " + e.toString());
            }
            try {

                // récupérer la liste de toutes les venues

                JSONArray venues = jObj.getJSONObject("response").getJSONArray("venues"); 

                // parcourir toute la liste des venues
                for(int i = 0; i < venues.length(); i++){

                // parcours du tableau de venues
                JSONObject ven = venues.getJSONObject(i);

                // stocker chaque item du JSONObject venue dans une variable de type String
                String id = ven.getString(TAG_ID);
                String name = ven.getString(TAG_NAME);


                // récupérer le JSONObject phone qui contient deux items
                JSONObject location = null;
                try {
                    location = ven.getJSONObject(TAG_LOCATION);
                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                String address = location.getString(TAG_ADDRESS);
                String crossStreet= location.getString(TAG_CROSS_STREET);
                String city= location.getString(TAG_CITY);
                String state= location.getString(TAG_STATE);
                String postalCode= location.getString(TAG_POSTAL_CODE);
                String country= location.getString(TAG_COUNTRY);
                String lat= location.getString(TAG_LAT);
                String lng= location.getString(TAG_LNG);
                String distance= location.getString(TAG_DISTANCE);



                /*if(jsonObjLoc.has("myAddress")) { // name of field to look for 

                       myTextAddress = jsonObjLoc.getString("address");
            }*/

                // créer une HashMap pour ajouter les informations dans chaque item
                HashMap<String, String> map = new HashMap<String, String>();

                // insérer dans la HashMap les données que l’on veut afficher sous la forme de clé/valeur
                //map.put(TAG_ID, id);
                map.put(TAG_NAME, name);
                map.put(TAG_ADDRESS, address);
                //map.put(TAG_CITY, city);
                map.put(TAG_LAT, lat);
                map.put(TAG_LNG, lng);
                //map.put(TAG_DISTANCE, distance);

                // ajouter une HashMap à notre ArrayList
                venuesList.add(map);
                }

                //créer un SimpleAdapter qui se chargera de placer les données dans chaque item de notre listView
                ListAdapter adapter = 
                        new SimpleAdapter(JSonResultActivity.this, venuesList,R.layout.activity_json_result, 
                        new String[] { TAG_NAME, TAG_ADDRESS, TAG_LAT, TAG_LNG }, 
                        new int[] {R.id.name, R.id.address, R.id.lat, R.id.lng });



            // attribuer à notre listView l'adapter que l'on vient de créer
            setListAdapter(adapter);
            }
           catch (JSONException e) 
            {
            e.printStackTrace();
            } 


     }

}
}

Thanks for your help !

FD_
  • 12,947
  • 4
  • 35
  • 62
Vinvinlol
  • 3
  • 1
  • 1
  • 5
  • possible duplicate of [android.os.NetworkOnMainThreadException](http://stackoverflow.com/questions/6343166/android-os-networkonmainthreadexception) – Raghunandan Jul 26 '13 at 11:35
  • Use AsynchTask (http://developer.android.com/reference/android/os/AsyncTask.html) Example: http://stackoverflow.com/questions/17057712/pass-arraylist-bean-from-android-to-webservice-php/17058208#17058208 – Karan Mavadhiya Jul 26 '13 at 11:37
  • I'm already using an asyncTask – Vinvinlol Jul 26 '13 at 11:43
  • Consider using [droidQuery](http://bit.ly/droidquery) to greatly simplify the async task and background thread stuff (such as parsing the HTTP Entity). – Phil Jul 26 '13 at 11:44
  • As the stack trace implies, you're calling `doInBackground()` from your `postExecute()` which runs in the main UI thread. You should not be calling any of the `AsyncTask` overloads yourself. – laalto Jul 28 '13 at 15:20

1 Answers1

1

add this..

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

put this in manifest file

     <uses-permission android:name="android.permission.INTERNET"/>
selva_pollachi
  • 4,147
  • 4
  • 29
  • 42
  • I had already add the Internet permission before, but now I just add the StrictMode, and it works ! Thanks ! – Vinvinlol Jul 26 '13 at 11:55
  • This is bad advice. Networking code will still run on the UI thread, causing non-responsive behavior. – laalto Jul 28 '13 at 15:19
  • Well it works but maybe it's a bad advice.. Do you have any advice for me @laalto ? – Vinvinlol Jul 29 '13 at 11:22
  • @user2610281 Refactor your code so that the networking code is in `AsyncTask` `doInBackground()` (and don't call that function yourself from UI thread). – laalto Jul 29 '13 at 11:28