anuruddhika
anuruddhika

Reputation: 1559

what should be the correct answer for this exception? "Android.os.NetworkOnMainThreadException"

what is the correct way of fixing this problem?

This is my activity code

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

}

Upvotes: 1

Views: 220

Answers (3)

user3291565
user3291565

Reputation:

For the http request in android the better way to use the following library which is manage all the auto setting for the request there are simple few line code

Check the following link. http://loopj.com/android-async-http/

download the jar file and paste in the lib folder and then just write few lines like for simple get methods

});

import com.loopj.android.http.*;

AsyncHttpClient client = new AsyncHttpClient();

client.get("http://www.google.com", new AsyncHttpResponseHandler() {

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

});

Upvotes: 0

Raghunandan
Raghunandan

Reputation: 133560

I guess this where you go wrong

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

In onPostExecute you have

getImageData();

In getImageData() you have listview item click listener

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

This getting json object must be doen in a background thread

Also you cannot update ui from background thread

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

Must be removed

Upvotes: 4

Pulkit Sethi
Pulkit Sethi

Reputation: 1325

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

Upvotes: 0

Related Questions