什么应该是这个例外的正确答案? " Android.os.NetworkOnMainThreadException"

时间:2014-03-19 05:20:54

标签: android

解决此问题的正确方法是什么?

这是我的活动代码

public class MainActivity extends Activity {

    JSONParser jsonParser = new JSONParser();
    ItemsAdapter adapter;
    ListView list;
    ListView list2;
    HashMap<String, String> map;
    ProgressDialog myPd_bar;
    static String img_url;
    private String strJson1 = "";
    private String url = "http://www.*************************************************";
    String img_test_url = "http://*************************************************";
    ImageView imageView;

    String bName;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        list = (ListView) findViewById(R.id.listView1);
        list2 = (ListView) findViewById(R.id.listView2); 
        accessWebService();

    }

    // Async Task to access the web
    private class LoadData extends AsyncTask<String, Void, String> {

        @Override
        protected void onPreExecute() {
            // TODO Auto-generated method stub
            myPd_bar = new ProgressDialog(MainActivity.this);
            myPd_bar.setMessage("Loading....");
            myPd_bar.setTitle(null);
            myPd_bar.show();
            super.onPreExecute();
        }

        @Override
        protected String doInBackground(String... params) {
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(params[0]);
            try {
                HttpResponse response = httpclient.execute(httppost);
                strJson1 = inputStreamToString(
                        response.getEntity().getContent()).toString();
            }

            catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }

        private StringBuilder inputStreamToString(InputStream is) {
            String rLine = "";
            StringBuilder answer = new StringBuilder();
            BufferedReader rd = new BufferedReader(new InputStreamReader(is));

            try {
                while ((rLine = rd.readLine()) != null) {
                    answer.append(rLine);
                }
            }

            catch (IOException e) {
                // e.printStackTrace();
                Toast.makeText(getApplicationContext(),
                        "Error..." + e.toString(), Toast.LENGTH_LONG).show();
            }
            return answer;
        }

        @Override
        protected void onPostExecute(String result) {
            getImageData();
            myPd_bar.dismiss();
        }
    }// end async task

    public void accessWebService() {
        LoadData task = new LoadData();
        // passes values for the urls string array
        task.execute(new String[] { url });
    }

    // build hash set for list view
    public void getImageData() {

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

        ArrayList<Pair<String,String>> listData = new ArrayList<Pair<String,String>>();

        try {
            JSONObject jsonResponse = new JSONObject(strJson1);
            JSONArray jsonMainNode = jsonResponse.optJSONArray("bank");

            for (int i = 0; i < jsonMainNode.length(); i++) {
                JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
                img_url = jsonChildNode.optString("logo");
                String test1 = img_test_url + img_url;
                bName = jsonChildNode.optString("id");
                //map.put(bName, test1);
                listData.add(new Pair<String,String>(bName,test1 ));
            }

            ItemsAdapter adapter = new ItemsAdapter(getApplicationContext(),listData);
            list.setAdapter(adapter);

        } catch (JSONException e) {
            Toast.makeText(getApplicationContext(), "Connection Error...",
                    Toast.LENGTH_LONG).show();
        }

        list.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                    long arg3) {
                // TODO Auto-generated method stub

                @SuppressWarnings("unchecked")
                Pair<String, String> item = (Pair<String, String>)arg0.getItemAtPosition(arg2);
                String id = item.first;
                Log.d("Bank Name", id);

                List<String> cards_name = new ArrayList<String>();

                try {
                    List<NameValuePair> params = new ArrayList<NameValuePair>();
                    params.add(new BasicNameValuePair("Bank_Name", id));
                    Log.d("request!", "starting");
                    JSONObject jsonResponse = jsonParser.makeHttpRequest("http://*************************************************", "POST", params);
                    Log.d("Credite Cards", jsonResponse.toString());
                    JSONArray jsonMainNode = jsonResponse.optJSONArray("creditcards");

                    for (int i = 0; i < jsonMainNode.length(); i++) {
                        JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
                            String card = jsonChildNode.optString("name");
                            Log.d("Card_name", card);
                            cards_name.add(card);

                    }

                    ArrayAdapter adapter2 = new ArrayAdapter(MainActivity.this, android.R.layout.simple_list_item_1, cards_name);
                    list2.setAdapter(adapter2);

                } catch (JSONException e) {
                    Toast.makeText(getApplicationContext(), "Error..." + e.toString(),
                            Toast.LENGTH_LONG).show();
                }
            }
        });
    }   

}

3 个答案:

答案 0 :(得分:4)

我想这就是你出错的地方

JSONObject jsonResponse = jsonParser.makeHttpRequest("http://*************************************************", "POST", params);

在onPostExecute中你有

getImageData();

getImageData()中,您有listview项目点击监听器

list.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
..// rest of the code
JSONObject jsonResponse = jsonParser.makeHttpRequest("http://*************************************************", "POST", params); 
// network operation on main thread

这个获取json对象必须在后台线程

中进行

此外,你无法从后台线程更新ui

Toast.makeText(getApplicationContext(),
                    "Error..." + e.toString(), Toast.LENGTH_LONG).show();

必须删除

答案 1 :(得分:0)

   JSONObject jsonResponse = jsonParser.makeHttpRequest("http://*************************************************", "POST", params);
 //this should be in a separate non ui thread

答案 2 :(得分:0)

对于android中的http请求,使用以下库管理请求的所有自动设置的更好方法是简单的几行代码

检查以下链接。 http://loopj.com/android-async-http/

下载jar文件并粘贴到lib文件夹中,然后只写几行,就像简单的get方法一样

});

import com.loopj.android.http。*;

AsyncHttpClient client = new AsyncHttpClient();

client.get(&#34; http://www.google.com&#34;,新的AsyncHttpResponseHandler(){

@Override
public void onSuccess(String response) {
    System.out.println(response);
}

});