0

I am trying to run http get request on my onclick function from button, I have edittext where in need to supply by user the edittext contain the url to be use on http get request.

my button is :

<Button
        android:id="@+id/mybutton"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="button" 
        android:onClick="Functionbtn"/>

and in my activity I got

public void Functionbtn(View view) {
    Toast.makeText(getApplicationContext(), "this is my toast",
            Toast.LENGTH_LONG).show();

    // Creating JSON Parser instance
    JSONParser jParser = new JSONParser();

    // getting JSON string from URL
    JSONObject json = jParser.getJSONFromUrl(url);

    try {
        // Getting Array of Contacts
        contacts = json.getJSONArray(TAG_CONTACTS);

        // looping through All Contacts
        for (int i = 0; i < contacts.length(); i++) {
            JSONObject c = contacts.getJSONObject(i);

            // Storing each json item in variable
            String id = c.getString(TAG_ID);
            String name = c.getString(TAG_NAME);

            Toast.makeText(getApplicationContext(), id + " = " + name,
                    Toast.LENGTH_LONG).show();

        }
    } catch (JSONException e) {
        e.printStackTrace();
    }

}

and I got an error like :

08-12 18:01:21.353: E/AndroidRuntime(10940): Caused by: android.os.NetworkOnMainThreadException
08-12 18:01:21.353: E/AndroidRuntime(10940):    at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1133)
08-12 18:01:21.353: E/AndroidRuntime(10940):    at java.net.InetAddress.lookupHostByName(InetAddress.java:385)

Some say put my target sdk to 9 but I don't think that is the best practice for this.

Could anyone help me not really sure what to do. Thanks in advance.

CaffeineShots
  • 2,172
  • 7
  • 33
  • 58

3 Answers3

2

Don't do such network related work inside UI thread. Always do network based work inside AsyncTask anc call it from UI thread.

public void Functionbtn(View view) {
   new GetTaskDone().execute();
}

And:

protected class GetTaskDone extends AsyncTask<Void, Void, String> {

     @Override
     protected void onPreExecute() {
          super.onPreExecute();
          Toast.makeText(getApplicationContext(), "this is my toast",
          Toast.LENGTH_LONG).show();
     }

    protected String doInBackground(Void... params) {

    // Creating JSON Parser instance
    JSONParser jParser = new JSONParser();

    // getting JSON string from URL
    JSONObject json = jParser.getJSONFromUrl(url);

    try {
        // Getting Array of Contacts
        contacts = json.getJSONArray(TAG_CONTACTS);

        // looping through All Contacts
        for (int i = 0; i < contacts.length(); i++) {
            JSONObject c = contacts.getJSONObject(i);

            // Storing each json item in variable
            String id = c.getString(TAG_ID);
            String name = c.getString(TAG_NAME);
            return id + " = " + name;
        }
    } catch (JSONException e) {
        e.printStackTrace();
        return null;
    }
    }

    @Override
    protected void onPostExecute(String result) {
          super.onPostExecute(result);
          Toast.makeText(getApplicationContext(), result,
                    Toast.LENGTH_LONG).show();
    }

}
Kaidul
  • 15,409
  • 15
  • 81
  • 150
1

Because of android's strict rules, you can't and you shouldn't run network tasks (or similar tasks that take time to complete) on the UI Thread.

Instead you should achieve it by running the tasks in a background thread using AsyncTask or Simple Java Threads.

Miro Markaravanes
  • 3,285
  • 25
  • 32
1

Allways remember to run network calls either in a thread or in a asynctask class. preferably asynctask.

Udit Kapahi
  • 2,277
  • 1
  • 27
  • 25