android-高级API上的NetworkOnMainThreadException

我只有在较高的API上调试时才会强制关闭脚本:16,但是在API上运行时效果很好:10.可能是我的项目设置问题吗?

这是对服务器的简单请求,以获取片段中的类别列表.

gallery.java

public class gallery extends Fragment {

    JSONArray jArray;
    String result = null;
    InputStream is = null;
    StringBuilder sb = null;
    private ListView storeList;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        View myFragmentView = inflater.inflate(R.layout.tab_frag1_layout,
                container, false);
        storeList = (ListView) inflater.inflate(R.layout.list, null);
        return myFragmentView;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);

    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onActivityCreated(savedInstanceState);

        ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        // http post
        try {
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(
                    "http://xxx.xxx.xxx/android_link.php");
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();
            is = entity.getContent();
        } catch (Exception e) {
            Log.e("log_tag", "Error in http connection" + e.toString());
        }
        // convert response to string
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            sb = new StringBuilder();
            sb.append(reader.readLine() + "\n");

            String line = "0";
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            result = sb.toString();
        } catch (Exception e) {
            Log.e("log_tag", "Error converting result " + e.toString());
        }
        // paring data
        int ct_id;
        String ct_name;
        try {
            jArray = new JSONArray(result);
            JSONObject json_data = null;
            for (int i = 0; i < jArray.length(); i++) {
                json_data = jArray.getJSONObject(i);
                ct_id = json_data.getInt("brand_id");
                ct_name = json_data.getString("series_name");

            }
        } catch (JSONException e1) {
            Toast.makeText(getActivity(), "No Data Found", Toast.LENGTH_LONG)
                    .show();
        } catch (ParseException e1) {
            e1.printStackTrace();
        }
    }

log.txt的

01-29 03:25:54.653: E/log_tag(4324): Error in http connectionandroid.os.NetworkOnMainThreadException
01-29 03:25:54.653: E/log_tag(4324): Error converting result java.lang.NullPointerException
01-29 03:25:54.653: W/dalvikvm(4324): threadid=1: thread exiting with uncaught exception (group=0xb5e98288)
01-29 03:25:54.653: E/AndroidRuntime(4324): FATAL EXCEPTION: main
01-29 03:25:54.653: E/AndroidRuntime(4324): java.lang.NullPointerException
01-29 03:25:54.653: E/AndroidRuntime(4324):     at org.json.JSONTokener.nextCleanInternal(JSONTokener.java:116)
01-29 03:25:54.653: E/AndroidRuntime(4324):     at org.json.JSONTokener.nextValue(JSONTokener.java:94)
01-29 03:25:54.653: E/AndroidRuntime(4324):     at org.json.JSONArray.<init>(JSONArray.java:87)
01-29 03:25:54.653: E/AndroidRuntime(4324):     at org.json.JSONArray.<init>(JSONArray.java:103)
01-29 03:25:54.653: E/AndroidRuntime(4324):     at com.nazartt.angtrading.gallery.onActivityCreated(gallery.java:93)
01-29 03:25:54.653: E/AndroidRuntime(4324):     at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:891)
01-29 03:25:54.653: E/AndroidRuntime(4324):     at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1080)
01-29 03:25:54.653: E/AndroidRuntime(4324):     at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:622)
01-29 03:25:54.653: E/AndroidRuntime(4324):     at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1416)
01-29 03:25:54.653: E/AndroidRuntime(4324):     at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:420)
01-29 03:25:54.653: E/AndroidRuntime(4324):     at android.os.Handler.handleCallback(Handler.java:615)
01-29 03:25:54.653: E/AndroidRuntime(4324):     at android.os.Handler.dispatchMessage(Handler.java:92)
01-29 03:25:54.653: E/AndroidRuntime(4324):     at android.os.Looper.loop(Looper.java:137)
01-29 03:25:54.653: E/AndroidRuntime(4324):     at android.app.ActivityThread.main(ActivityThread.java:4745)
01-29 03:25:54.653: E/AndroidRuntime(4324):     at java.lang.reflect.Method.invokeNative(Native Method)
01-29 03:25:54.653: E/AndroidRuntime(4324):     at java.lang.reflect.Method.invoke(Method.java:511)
01-29 03:25:54.653: E/AndroidRuntime(4324):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
01-29 03:25:54.653: E/AndroidRuntime(4324):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
01-29 03:25:54.653: E/AndroidRuntime(4324):     at dalvik.system.NativeStart.main(Native Method)

解决方法:

如果尝试在主(UI)线程(StrictMode)上进行网络操作,则新版本的Android(3.0)上会出现NetworkOnMainThreadException.使用AsyncTask进行网络操作,设置简单,并且以逻辑方式进行操作(在后台执行某些操作,然后在完成后发布到UI线程).

上一篇:java-JTextField自动完成错误


下一篇:java-NullPointerException:在派生类中重写基类的构造方法调用方法