logcat-error android.os.NetworkOnMainThreadException

时间:2014-01-05 09:51:34

标签: android json android-asynctask

我想检查localhost中是否存在位置,如果该位置存在与否,它将响应系统并获取消息(toast),但我的应用程序在我运行时强行停止,我不知道为什么,并且我的代码在哪里?

这是我的主要代码

public class SetLocationActivity extends Activity implements OnClickListener{

    private JSONParser jsonParser;
    private static String ServerURL="http://myurl/asset"; 
    private static String location_tag ="location";
    private String stats = null;
    Button go;
    EditText location;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_set_location);
        location = (EditText)findViewById(R.id.edit_location);
        go = (Button)findViewById(R.id.btn_go);
        go.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        //Call class JSONParser
        jsonParser = new JSONParser();
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("tag",location_tag));
        params.add(new BasicNameValuePair("loc",location.getText().toString()));
        JSONObject json = jsonParser.getJSONFromUrl(ServerURL, params);

        try {
            Context context = getApplicationContext();
            int duration = Toast.LENGTH_SHORT;

            stats = json.getString("lo");
            if(stats != null) {
                CharSequence text = "List Location in"+stats;
                Toast toast = Toast.makeText(context, text, duration);
                toast.show();
            } else {
                CharSequence text = "Location not found";
                Toast toast = Toast.makeText(context, text, duration);
                toast.show();
            }       
        }catch(JSONException e) {
            //TODO Auto-Generated catch block
            e.printStackTrace();
        }
    }

这是我的JSONParser代码

public class JSONParser {

    static InputStream is = null;
    static JSONObject jObj = null;
    static String json ="";

    //Constructor
    public JSONParser() {

    }


    public JSONObject getJSONFromUrl(String url, List<NameValuePair> params) {

            // Making HTTP request 
            try { 
                // defaultHttpClient 
                DefaultHttpClient httpClient = new DefaultHttpClient(); 
                HttpPost httpPost = new HttpPost(url); 
                httpPost.setEntity(new UrlEncodedFormEntity(params));

                HttpResponse httpResponse = httpClient.execute(httpPost); 
                HttpEntity httpEntity = httpResponse.getEntity(); 
                is = httpEntity.getContent();

            } catch (UnsupportedEncodingException e) { 
                e.printStackTrace(); 
            } catch (ClientProtocolException e) { 
                e.printStackTrace(); 
            } catch (IOException e) { 
                e.printStackTrace(); 
            }

            try { 
                BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8); 
                StringBuilder sb = new StringBuilder(); 
                String line = null; 
                while ((line = reader.readLine()) != null) { 
                    sb.append(line + "\n"); 
                } 
                is.close(); 
                json = sb.toString(); 
                Log.e("JSON", json); 
            } catch (Exception e) { 
                Log.e("Buffer Error", "Error converting result " + e.toString()); 
            }

            // try parse the string to a JSON object 
            try { 
                jObj = new JSONObject(json);            
            } catch (JSONException e) { 
                Log.e("JSON Parser", "Error parsing data " + e.toString()); 
            }

            // return JSON String 
            return jObj;
        } 
    }

这是我的logcat

01-05 16:37:23.382: E/AndroidRuntime(1096): FATAL EXCEPTION: main
01-05 16:37:23.382: E/AndroidRuntime(1096): android.os.NetworkOnMainThreadException
01-05 16:37:23.382: E/AndroidRuntime(1096):     at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1118)
01-05 16:37:23.382: E/AndroidRuntime(1096):     at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84)
01-05 16:37:23.382: E/AndroidRuntime(1096):     at libcore.io.IoBridge.connectErrno(IoBridge.java:127)
01-05 16:37:23.382: E/AndroidRuntime(1096):     at libcore.io.IoBridge.connect(IoBridge.java:112)
01-05 16:37:23.382: E/AndroidRuntime(1096):     at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
01-05 16:37:23.382: E/AndroidRuntime(1096):     at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459)
01-05 16:37:23.382: E/AndroidRuntime(1096):     at java.net.Socket.connect(Socket.java:842)
01-05 16:37:23.382: E/AndroidRuntime(1096):     at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:119)
01-05 16:37:23.382: E/AndroidRuntime(1096):     at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:144)
01-05 16:37:23.382: E/AndroidRuntime(1096):     at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
01-05 16:37:23.382: E/AndroidRuntime(1096):     at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
01-05 16:37:23.382: E/AndroidRuntime(1096):     at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
01-05 16:37:23.382: E/AndroidRuntime(1096):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
01-05 16:37:23.382: E/AndroidRuntime(1096):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
01-05 16:37:23.382: E/AndroidRuntime(1096):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
01-05 16:37:23.382: E/AndroidRuntime(1096):     at com.example.assetscanner.JSONParser.getJSONFromUrl(JSONParser.java:84)
01-05 16:37:23.382: E/AndroidRuntime(1096):     at com.example.assetscanner.SetLocationActivity.onClick(SetLocationActivity.java:54)
01-05 16:37:23.382: E/AndroidRuntime(1096):     at android.view.View.performClick(View.java:4162)
01-05 16:37:23.382: E/AndroidRuntime(1096):     at android.view.View$PerformClick.run(View.java:17082)
01-05 16:37:23.382: E/AndroidRuntime(1096):     at android.os.Handler.handleCallback(Handler.java:615)
01-05 16:37:23.382: E/AndroidRuntime(1096):     at android.os.Handler.dispatchMessage(Handler.java:92)
01-05 16:37:23.382: E/AndroidRuntime(1096):     at android.os.Looper.loop(Looper.java:137)
01-05 16:37:23.382: E/AndroidRuntime(1096):     at android.app.ActivityThread.main(ActivityThread.java:4867)
01-05 16:37:23.382: E/AndroidRuntime(1096):     at java.lang.reflect.Method.invokeNative(Native Method)
01-05 16:37:23.382: E/AndroidRuntime(1096):     at java.lang.reflect.Method.invoke(Method.java:511)
01-05 16:37:23.382: E/AndroidRuntime(1096):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1007)
01-05 16:37:23.382: E/AndroidRuntime(1096):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:774)
01-05 16:37:23.382: E/AndroidRuntime(1096):     at dalvik.system.NativeStart.main(Native Method)

在这个logcat上面的主要错误我认为是“android.os.NetworkOnMainThreadException”,我搜索了这个错误,有人说使用AsyncTask或StrictMode来解决这个问题。但我不知道我在哪里放置AsyncTask代码以及如何使用?

我想知道我的代码在哪里出错,它是在主代码或JSONParser代码上。

请帮我解决这个问题,谢谢你的关注

1 个答案:

答案 0 :(得分:1)

对于长时间的操作,我们必须使用ui线程中的另一个线程。使用Async Task fornetwork relation opeartion。它不会阻止你的ui更新。

快乐编码