문제

In my app, I have a method which takes a string of an address and gets information regarding it and turns it into a JSONObject using Google Geocode. The method is as follows:

public static JSONObject getLocationInfo(String address) {

    StringBuilder stringBuilder = new StringBuilder();

    try {
        address = address.replaceAll(" ","%20");    

        HttpPost httppost = new HttpPost("http://maps.google.com/maps/api/geocode/json?address=" + address + "&sensor=false");
        HttpClient client = new DefaultHttpClient();
        HttpResponse response;
        stringBuilder = new StringBuilder();


        response = client.execute(httppost);
        HttpEntity entity = response.getEntity();
        InputStream stream = entity.getContent();
        int b;
        while ((b = stream.read()) != -1) {
            stringBuilder.append((char) b);
        }
    } catch (ClientProtocolException e) {
    } catch (IOException e) {
    }

    JSONObject jsonObject = new JSONObject();
    try {
        jsonObject = new JSONObject(stringBuilder.toString());
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return jsonObject;
}

This works fine when I'm running the app through Eclipse on my device. However, when I make an APK and install it on the device, the app crashes in the above code. My log cat output is as follows:

 04-14 21:43:19.677: E/AndroidRuntime(21560): FATAL EXCEPTION: main
 04-14 21:43:19.677: E/AndroidRuntime(21560): Process: com.example.carpool, PID: 21560
 04-14 21:43:19.677: E/AndroidRuntime(21560): android.os.NetworkOnMainThreadException
 04-14 21:43:19.677: E/AndroidRuntime(21560):   at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1145)
 04-14 21:43:19.677: E/AndroidRuntime(21560):   at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
 04-14 21:43:19.677: E/AndroidRuntime(21560):   at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
 04-14 21:43:19.677: E/AndroidRuntime(21560):   at java.net.InetAddress.getAllByName(InetAddress.java:214)
 04-14 21:43:19.677: E/AndroidRuntime(21560):   at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
 04-14 21:43:19.677: E/AndroidRuntime(21560):   at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
 04-14 21:43:19.677: E/AndroidRuntime(21560):   at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
 04-14 21:43:19.677: E/AndroidRuntime(21560):   at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
 04-14 21:43:19.677: E/AndroidRuntime(21560):   at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
 04-14 21:43:19.677: E/AndroidRuntime(21560):   at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
 04-14 21:43:19.677: E/AndroidRuntime(21560):   at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
 04-14 21:43:19.677: E/AndroidRuntime(21560):   at com.example.carpool.Book.getLocationInfo(Book.java:421)
 04-14 21:43:19.677: E/AndroidRuntime(21560):   at com.example.carpool.Book$8.onItemClick(Book.java:236)
 04-14 21:43:19.677: E/AndroidRuntime(21560):   at android.widget.AutoCompleteTextView.performCompletion(AutoCompleteTextView.java:902)
 04-14 21:43:19.677: E/AndroidRuntime(21560):   at android.widget.AutoCompleteTextView.access$500(AutoCompleteTextView.java:91)
 04-14 21:43:19.677: E/AndroidRuntime(21560):   at android.widget.AutoCompleteTextView$DropDownItemClickListener.onItemClick(AutoCompleteTextView.java:1192)
 04-14 21:43:19.677: E/AndroidRuntime(21560):   at android.widget.AdapterView.performItemClick(AdapterView.java:299)
 04-14 21:43:19.677: E/AndroidRuntime(21560):   at android.widget.AbsListView.performItemClick(AbsListView.java:1113)
 04-14 21:43:19.677: E/AndroidRuntime(21560):   at android.widget.AbsListView$PerformClick.run(AbsListView.java:2904)
 04-14 21:43:19.677: E/AndroidRuntime(21560):   at android.widget.AbsListView$3.run(AbsListView.java:3638)
 04-14 21:43:19.677: E/AndroidRuntime(21560):   at android.os.Handler.handleCallback(Handler.java:733)
 04-14 21:43:19.677: E/AndroidRuntime(21560):   at android.os.Handler.dispatchMessage(Handler.java:95)
 04-14 21:43:19.677: E/AndroidRuntime(21560):   at android.os.Looper.loop(Looper.java:136)
 04-14 21:43:19.677: E/AndroidRuntime(21560):   at android.app.ActivityThread.main(ActivityThread.java:5017)
 04-14 21:43:19.677: E/AndroidRuntime(21560):   at java.lang.reflect.Method.invokeNative(Native Method)
 04-14 21:43:19.677: E/AndroidRuntime(21560):   at java.lang.reflect.Method.invoke(Method.java:515)
 04-14 21:43:19.677: E/AndroidRuntime(21560):   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
 04-14 21:43:19.677: E/AndroidRuntime(21560):   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
 04-14 21:43:19.677: E/AndroidRuntime(21560):   at dalvik.system.NativeStart.main(Native Method)

The exact line where it crashes is the response = client.execute(httppost); line. I don't know why this is happening and how can it be corrected?

도움이 되었습니까?

해결책

You are accessing the network from Main Thread. You have to do the network operation only in a background Thread

Use AsyncTask like this

 new AsyncTask<URL, Integer, Long>(){
            @Override
            protected Long doInBackground(URL... params) {
                try {

                    // call you method here

                } catch (Exception ex) {
                    // handle the exception here
                }
                return null;
            }
        }.execute();

다른 팁

android.os.NetworkOnMainThreadException means you are performing network on the main(ui) thread. you cannot perform network operation on main thread.android does not allow to do this. that's why it is crashing. move yout http request in asyntask , so it will run in seperate thread and your app will not get crashed.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top