0

我正在尝试解析四方场地并将它们显示在列表中。早些时候,我在没有 asyncTask 的情况下完成了它,并添加了 Runtime excpetion。所以我加了一个,但我仍然有那种错误。我是android新手,我不太明白这个错误。

这是 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)

这是代码

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


     }

}
}

谢谢你的帮助 !

4

1 回答 1

1

添加这个..

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

把它放在清单文件中

     <uses-permission android:name="android.permission.INTERNET"/>
于 2013-07-26T11:45:54.540 回答