-1

我是android新手,我尝试使用这样的类从url解析json:

package com.***.exchanger;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

public class JSONParser {

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

    // constructor
    public JSONParser() {

    }

    public JSONObject getJSONFromUrl(String url) {

        // Making HTTP request
        try {
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpGet httpPost = new HttpGet(url);

            HttpResponse httpResponse = httpClient.execute(httpPost);
            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, "UTF-8"), 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("Buffer Error", "Error converting result " + e.toString());
        }

        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // return JSON String
        return jObj;

    }
}

当我在没有 asynctask 的情况下进行解析时 - 一切都很好,我得到了 json 结果,等等......

但现在我的代码是这样的:

public class ExchangerListActivity extends ListActivity {

    private static String url;


    private static final String TAG_BANKS = "bank";
    private static final String TAG_ID = "id";
    private static final String TAG_NAME = "name";
    private static final String TAG_Exc_count = "exch_count";
    private static final String TAG_central_office_address = "central_office_address";
    JSONArray banks = null;
    JSONObject json;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_exchanger_list);
        url = "http://192.168.1.4:3000/banks.json";
        JSONParser jParser = new JSONParser();    
        JSONObject json = jParser.getJSONFromUrl(url);

        ListViewLoaderTask listViewLoaderTask = new ListViewLoaderTask();
        listViewLoaderTask.execute(json);
    }


     private class ListViewLoaderTask extends AsyncTask<JSONObject, Void, ListAdapter>{

            JSONObject jObject;
            /** Doing the parsing of xml data in a non-ui thread */
            @Override
            protected ListAdapter doInBackground(JSONObject... strJson) {

                url = "http://192.168.1.4:3000/banks.json";

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


                JSONParser jParser = new JSONParser();


                JSONObject json = jParser.getJSONFromUrl(url);

                try {

                    banks = json.getJSONArray(TAG_BANKS);


                    for(int i = 0; i < banks.length(); i++){
                        JSONObject c = banks.getJSONObject(i);

                        String id = c.getString(TAG_ID);
                        String name = c.getString(TAG_NAME);
                        String central_office_address = c.getString(TAG_central_office_address);
                        String exchangers_list_count = c.getString(TAG_Exc_count);

                        HashMap<String, String> map = new HashMap<String, String>();

                        map.put(TAG_ID, id);
                        map.put(TAG_NAME, name);
                        map.put(TAG_central_office_address, central_office_address);
                        map.put(TAG_Exc_count, exchangers_list_count);

                        contactList.add(map);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                final ListAdapter adapter = new SimpleAdapter(ExchangerListActivity.this, contactList,
                        R.layout.bank_list,
                        new String[] { TAG_NAME, TAG_central_office_address, TAG_Exc_count }, new int[] {
                                R.id.bank_name, R.id.central_office_address, R.id.exchangers_list_count});

                return adapter;
            }

            /** Invoked by the Android system on "doInBackground" is executed completely */
            /** This will be executed in ui thread */
            @Override
            protected void onPostExecute(ListAdapter adapter) {

                /** Getting a reference to listview of main.xml layout file */
                ListView listView = ExchangerListActivity.this.getListView();

                /** Setting the adapter containing the country list to listview */
                listView.setAdapter(adapter);
                //setListAdapter(adapter);
/*
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
*/
        @SuppressWarnings("unchecked")
        @Override
        public void onItemClick(AdapterView<?> parent, android.view.View view,
                int position, long id) {
            Intent in = new Intent(getApplicationContext(), BankExchangersListActivity.class);
            String a = ((Map<String, String>) adapter.getItem(position)).get(TAG_ID);
            in.putExtra("Bank_id", a);
            startActivity(in);
        }

    });

*/ } }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.exchanger_list, menu);
        return true;
    }

}

然后我得到错误:

05-02 20:16:21.749: E/AndroidRuntime(4057): FATAL EXCEPTION: main
05-02 20:16:21.749: E/AndroidRuntime(4057): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.pavel.exchanger/com.pavel.exchanger.ExchangerListActivity}: android.os.NetworkOnMainThreadException
05-02 20:16:21.749: E/AndroidRuntime(4057):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
05-02 20:16:21.749: E/AndroidRuntime(4057):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
05-02 20:16:21.749: E/AndroidRuntime(4057):     at android.app.ActivityThread.access$600(ActivityThread.java:141)
05-02 20:16:21.749: E/AndroidRuntime(4057):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
05-02 20:16:21.749: E/AndroidRuntime(4057):     at android.os.Handler.dispatchMessage(Handler.java:99)
05-02 20:16:21.749: E/AndroidRuntime(4057):     at android.os.Looper.loop(Looper.java:137)
05-02 20:16:21.749: E/AndroidRuntime(4057):     at android.app.ActivityThread.main(ActivityThread.java:5041)
05-02 20:16:21.749: E/AndroidRuntime(4057):     at java.lang.reflect.Method.invokeNative(Native Method)
05-02 20:16:21.749: E/AndroidRuntime(4057):     at java.lang.reflect.Method.invoke(Method.java:511)
05-02 20:16:21.749: E/AndroidRuntime(4057):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
05-02 20:16:21.749: E/AndroidRuntime(4057):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
05-02 20:16:21.749: E/AndroidRuntime(4057):     at dalvik.system.NativeStart.main(Native Method)
05-02 20:16:21.749: E/AndroidRuntime(4057): Caused by: android.os.NetworkOnMainThreadException
05-02 20:16:21.749: E/AndroidRuntime(4057):     at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117)
05-02 20:16:21.749: E/AndroidRuntime(4057):     at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84)
05-02 20:16:21.749: E/AndroidRuntime(4057):     at libcore.io.IoBridge.connectErrno(IoBridge.java:127)
05-02 20:16:21.749: E/AndroidRuntime(4057):     at libcore.io.IoBridge.connect(IoBridge.java:112)
05-02 20:16:21.749: E/AndroidRuntime(4057):     at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
05-02 20:16:21.749: E/AndroidRuntime(4057):     at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459)
05-02 20:16:21.749: E/AndroidRuntime(4057):     at java.net.Socket.connect(Socket.java:842)
05-02 20:16:21.749: E/AndroidRuntime(4057):     at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:119)
05-02 20:16:21.749: E/AndroidRuntime(4057):     at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:144)
05-02 20:16:21.749: E/AndroidRuntime(4057):     at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
05-02 20:16:21.749: E/AndroidRuntime(4057):     at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
05-02 20:16:21.749: E/AndroidRuntime(4057):     at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
05-02 20:16:21.749: E/AndroidRuntime(4057):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
05-02 20:16:21.749: E/AndroidRuntime(4057):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
05-02 20:16:21.749: E/AndroidRuntime(4057):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
05-02 20:16:21.749: E/AndroidRuntime(4057):     at com.pavel.exchanger.JSONParser.getJSONFromUrl(JSONParser.java:39)
05-02 20:16:21.749: E/AndroidRuntime(4057):     at com.pavel.exchanger.ExchangerListActivity.onCreate(ExchangerListActivity.java:45)
05-02 20:16:21.749: E/AndroidRuntime(4057):     at android.app.Activity.performCreate(Activity.java:5104)
05-02 20:16:21.749: E/AndroidRuntime(4057):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
05-02 20:16:21.749: E/AndroidRuntime(4057):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
05-02 20:16:21.749: E/AndroidRuntime(4057):     ... 11 more

我做错了什么?如何运行我的活动以进行 json 解析和显示?

4

1 回答 1

3

我做错了什么?

getJSONFromUrl()您从您的活动中调用onCreate()(参见第 45 行ExchangerListActivity.java)。这是您getJSONFromUrl()在您的AsyncTask. 大概你忘了删除你调用它的案例onCreate()

于 2013-05-02T20:25:40.620 回答