更高API的NetworkOnMainThreadException

时间:2013-01-29 03:40:31

标签: android android-fragments nullpointerexception

我只有在高级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)

3 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:1)

试试这个,使用AsyncTask方法来解决你的问题..

protected class GetTask extends AsyncTask<Void, Void, Integer> {

protected void onPreExecute() {
ProgressDialog  mProgressDialog = ProgressDialog.show(MainActivity.this,
            "", "Finding cars");
}

@Override
protected Integer doInBackground(Void... params) {
    // TODO Auto-generated method stub
    //Do your stuff

    return 0;
}

protected void onPostExecute(Integer result) {
    super.onPostExecute(result);


    if (mProgressDialog.isShowing()) {
        mProgressDialog.dismiss();
    }


}
}

答案 2 :(得分:0)

如果有人进入这种情况。我决定发布我的工作代码

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);

        new task().execute();

    }

    class task extends AsyncTask<String, String, Void> {
        private ProgressDialog progressDialog = new ProgressDialog(getActivity());
        InputStream is = null;
        String result = "";

        protected void onPreExecute() {
            progressDialog.setMessage("Download data...");
            progressDialog.show();
        }

        @Override
        protected Void doInBackground(String... params) {
            String url_select = "http://xxxxxxxxxxxx/android_link.php";

            HttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url_select);

            ArrayList<NameValuePair> param = new ArrayList<NameValuePair>();

            try {
                httpPost.setEntity(new UrlEncodedFormEntity(param));

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

                // read content
                is = httpEntity.getContent();

            } catch (Exception e) {

                Log.e("log_tag", "Error in http connection " + e.toString());
            }
            try {
                BufferedReader br = new BufferedReader(
                        new InputStreamReader(is));
                StringBuilder sb = new StringBuilder();
                String line = "";
                while ((line = br.readLine()) != null) {
                    sb.append(line + "\n");
                }
                is.close();
                result = sb.toString();

            } catch (Exception e) {
                // TODO: handle exception
                Log.e("log_tag", "Error converting result " + e.toString());
            }

            return null;

        }

        protected void onPostExecute(Void v) {

            // ambil data dari Json database
            try {
                JSONArray Jarray = new JSONArray(result);
                for (int i = 0; i < Jarray.length(); i++) {
                    JSONObject Jasonobject = null;
                    Jasonobject = Jarray.getJSONObject(i);

                    // get an output on the screen
                    String bid = Jasonobject.getString("brand_id");
                    String sname = Jasonobject.getString("series_name");

                }
                this.progressDialog.dismiss();

            } catch (Exception e) {
                // TODO: handle exception
                Log.e("log_tag", "Error parsing data " + e.toString());
            }
        }
    }
}