0

I want to get some WordDefinition from AONAWARE.COM, I have tried to parse XML like this :

protected String getWordDefinition(Context context, String word) {
    StringBuilder wordDefination = new StringBuilder();
    HttpClient httpClient = new DefaultHttpClient();
    StringBuilder queryString = new StringBuilder(URL);
    queryString.append(word);
    HttpGet request = new HttpGet(queryString.toString());
    HttpResponse httpResponse;
    try {
        httpResponse = httpClient.execute(request);
        HttpEntity httpEntity = httpResponse.getEntity();
        BufferedReader bufferedReader = new BufferedReader(
                new InputStreamReader(httpEntity.getContent()));
        String readLineString = "";
        while ((readLineString = bufferedReader.readLine()) != null) {
            wordDefination.append(readLineString + "\n");
            Log.e(AONAWARE_TAG, "Init " + wordDefination );
        }
        return (wordDefination.toString());
    } catch (ClientProtocolException e) {
        e.printStackTrace();
        return null;
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}

I was Successful for one or two times to get data from getWordDefinition, but now suddenly I'm getting this android.os.NetworkOnMainThreadException and the LogCat below :

03-02 17:11:31.601: W/dalvikvm(614): threadid=1: thread exiting with uncaught exception (group=0x40a13300)
03-02 17:11:31.631: E/AndroidRuntime(614): FATAL EXCEPTION: main
03-02 17:11:31.631: E/AndroidRuntime(614): android.os.NetworkOnMainThreadException
03-02 17:11:31.631: E/AndroidRuntime(614):  at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117)
03-02 17:11:31.631: E/AndroidRuntime(614):  at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
03-02 17:11:31.631: E/AndroidRuntime(614):  at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
03-02 17:11:31.631: E/AndroidRuntime(614):  at java.net.InetAddress.getAllByName(InetAddress.java:214)
03-02 17:11:31.631: E/AndroidRuntime(614):  at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
.
.
.

why? how to solve this Exception?

Arshad Ali
  • 3,082
  • 12
  • 56
  • 99

2 Answers2

2

You can't perform network operations on the main-thread (UI-thread). This is a reasonable behaviour because this kind of operations can have a long duration, so your UI can appear freezed. You should always do long-timed operations in a different thread. Consider using AsyncTask.

user2340612
  • 10,053
  • 4
  • 41
  • 66
1

You have to do network processes in a worker thread, the best waway to use an async task.

user3057944
  • 701
  • 1
  • 8
  • 19