Skip to content Skip to sidebar Skip to footer

Android - Runtime Error While Trying Httpget On A Url In Android

I'm trying to collect some json data, put those in a string and show them in my app through a toast as for test. I'm pretty sure that the server allows me and responds to my reques

Solution 1:

Here is an example of AsyncTask below. Also here is a great tutorial

classMyAsyncTaskextendsAsyncTask<String, String, Void> {

    privateProgressDialogprogressDialog=newProgressDialog(MainActivity.this);
    InputStreaminputStream=null;
    Stringresult=""; 

    protectedvoidonPreExecute() {
        progressDialog.setMessage("Your progress dialog message...");
        progressDialog.show();
        progressDialog.setOnCancelListener(newOnCancelListener() {
            publicvoidonCancel(DialogInterface arg0) {
                MyAsyncTask.this.cancel(true);
            }
        });
    }

    @Overrideprotected Void doInBackground(String... params) {

        Stringurl_select="http://yoururlhere.com";

                ArrayList<NameValuePair> param = newArrayList<NameValuePair>();

        try {
            // Set up HTTP post// HttpClient is more then less deprecated. Need to change to URLConnectionHttpClienthttpClient=newDefaultHttpClient();

            HttpPosthttpPost=newHttpPost(url_select);
            httpPost.setEntity(newUrlEncodedFormEntity(param));
            HttpResponsehttpResponse= httpClient.execute(httpPost);
            HttpEntityhttpEntity= httpResponse.getEntity();

            // Read content & Log
            inputStream = httpEntity.getContent();
        } catch (UnsupportedEncodingException e1) {
            Log.e("UnsupportedEncodingException", e1.toString());
            e1.printStackTrace();
        } catch (ClientProtocolException e2) {
            Log.e("ClientProtocolException", e2.toString());
            e2.printStackTrace();
        } catch (IllegalStateException e3) {
            Log.e("IllegalStateException", e3.toString());
            e3.printStackTrace();
        } catch (IOException e4) {
            Log.e("IOException", e4.toString());
            e4.printStackTrace();
        }
        // Convert response to string using String Buildertry {
            BufferedReaderbReader=newBufferedReader(newInputStreamReader(inputStream, "iso-8859-1"), 8);
            StringBuildersBuilder=newStringBuilder();

            Stringline=null;
            while ((line = bReader.readLine()) != null) {
                sBuilder.append(line + "\n");
            }

            inputStream.close();
            result = sBuilder.toString();

        } catch (Exception e) {
            Log.e("StringBuilding & BufferedReader", "Error converting result " + e.toString());
        }
    } // protected Void doInBackground(String... params)protectedvoidonPostExecute(Void v) {

        //parse JSON datatry{
            JSONArrayjArray=newJSONArray(result);

            for(int i=0; i < jArray.length(); i++) {

                JSONObjectjObject= jArray.getJSONObject(i);

                Stringname= jObject.getString("name");
                Stringtab1_text= jObject.getString("tab1_text");
                intactive= jObject.getInt("active");


            } // End for Loopthis.progressDialog.dismiss();

        } catch (JSONException e) {

            Log.e("JSONException", "Error: " + e.toString());

        } // catch (JSONException e)


    } // protected void onPostExecute(Void v)

} //class MyAsyncTask extends AsyncTask<String, String, Void>

I call my AsyncTask with this line:

new MyAsyncTask().execute();

Here is a Youtube tutorial (from the New Boston) for AsyncTask that I found helpful.

Android Application Development Tutorial - 101 - Async Task class to load stuffAndroid Application Development Tutorial - 102 - The 4 AsyncTask MethodsAndroid Application Development Tutorial - 103 - ProgressDialog and Correction

Solution 2:

You should never access network from the main thread. Use AsyncTask class' doInBackground method to access the network.

Post a Comment for "Android - Runtime Error While Trying Httpget On A Url In Android"