AsyncTask类中的android.os.NetworkOnMainThreadException

时间:2013-12-03 05:26:09

标签: android android-asynctask

我希望通过JSON从互联网获取数据,我正在使用AsynkTask类来执行此操作并且正常工作,但如果我添加或更改任何数据  代码并再次运行我的程序它停止使用android.os.NetworkOnMainThreadException 但我从来没有在main thread上运行此代码,我必须点击fix project,然后clean项目再次运行,它再次正常运行,问题是什么? 我正在运行的代码如下:

    public class NetworkDocStateThread extends AsyncTask<String, Void, Void> {

    HttpResponse responseState;

    @Override
    protected Void doInBackground(String... params) {

        try {
            responseState = JsonDocumnet
                    .SendDocumentState(Financial.selectedGuId);

        } catch (Exception ex) {
            ex.printStackTrace();
        }

        return null;
    }

    @Override
    protected void onPostExecute(Void post) {
        try {

            Financial.documnetStateDs = JsonDocumnet
                    .DocumentState(responseState);

                documentStateSpinner.add(Financial.documnetStateDs.get(i)
                        .getTitle());
            }

            SpinnerStateAdapter = new ArrayAdapter<String>(Documnet.this,
                    R.layout.spinnlayout, R.id.docstateid,
                    documentStateSpinner);


            SpinnerNumAdapter = new ArrayAdapter<String>(Documnet.this,
                    R.layout.spinnlayout, R.id.docstateid, getResources()
                            .getStringArray(R.array.numPerPage));

            SpinnerSortAdapter = new ArrayAdapter<String>(Documnet.this,
                    R.layout.spinnlayout, R.id.docstateid, getResources()
                    .getStringArray(R.array.SortBy));

            new NetworkDocThread().execute(Financial.selectedGuId, "5",

                    "0", "Id", "-1");

            docStateSpinner.setAdapter(SpinnerStateAdapter);
            NumberPerPageSpinner.setAdapter(SpinnerNumAdapter);
            SortBySpinner.setAdapter(SpinnerSortAdapter);

        } catch (IllegalStateException e) {

            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }

        super.onPostExecute(post);
    }

}

和第二个AsyncTask类:

public class NetworkDocThread extends AsyncTask<String, Void, Void> {

    HttpResponse responseDoc;

    @Override
    protected Void doInBackground(String... s) {
        try {
            responseDoc = JsonDocumnet.SendDocumnet(s[0], s[1], s[2], s[3],
                    s[4]);

        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(Void post) {


            try {
                Financial.docs = JsonDocumnet.Document(responseDoc);
                CreatingData();

            } catch (IOException e) { 
                e.printStackTrace();
            } catch (JSONException e) {
                ;
            }

            dialog.dismiss();


        }
    }
}

和清单文件:

   <uses-permission android:name="android.permission.INTERNET" />

和我的LogCat错误

    12-03 05:08:43.022: E/AndroidRuntime(1106): FATAL EXCEPTION: main
    12-03 05:08:43.022: E/AndroidRuntime(1106): android.os.NetworkOnMainThreadException
    12-03 05:08:43.022: E/AndroidRuntime(1106):     at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117)
    12-03 05:08:43.022: E/AndroidRuntime(1106):     at libcore.io.BlockGuardOs.recvfrom(BlockGuardOs.java:163)
    12-03 05:08:43.022: E/AndroidRuntime(1106):     at libcore.io.IoBridge.recvfrom(IoBridge.java:513)
    12-03 05:08:43.022: E/AndroidRuntime(1106):     at java.net.PlainSocketImpl.read(PlainSocketImpl.java:488)
    12-03 05:08:43.022: E/AndroidRuntime(1106):     at java.net.PlainSocketImpl.access$000(PlainSocketImpl.java:46)
    12-03 05:08:43.022: E/AndroidRuntime(1106):     at java.net.PlainSocketImpl$PlainSocketInputStream.read(PlainSocketImpl.java:240)
    12-03 05:08:43.022: E/AndroidRuntime(1106):     at org.apache.http.impl.io.AbstractSessionInputBuffer.fillBuffer(AbstractSessionInputBuffer.java:103)
    12-03 05:08:43.022: E/AndroidRuntime(1106):     at org.apache.http.impl.io.AbstractSessionInputBuffer.read(AbstractSessionInputBuffer.java:134)
   12-03 05:08:43.022: E/AndroidRuntime(1106):  at org.apache.http.impl.io.ContentLengthInputStream.read(ContentLengthInputStream.java:174)
   12-03 05:08:43.022: E/AndroidRuntime(1106):  at org.apache.http.conn.EofSensorInputStream.read(EofSensorInputStream.java:159)
   12-03 05:08:43.022: E/AndroidRuntime(1106):  at java.io.InputStreamReader.read(InputStreamReader.java:244)
   12-03 05:08:43.022: E/AndroidRuntime(1106):  at java.io.BufferedReader.fillBuf(BufferedReader.java:130)
   12-03 05:08:43.022: E/AndroidRuntime(1106):  at java.io.BufferedReader.readLine(BufferedReader.java:354)
   12-03 05:08:43.022: E/AndroidRuntime(1106):  at json.JsonDocumnet.Documen(JsonDocumnet.java:200)
   12-03 05:08:43.022: E/AndroidRuntime(1106):  at activity.Documnet$NetworkDocThread.onPostExecute(Documnet.java:375)
   12-03 05:08:43.022: E/AndroidRuntime(1106):  at activity.Documnet$NetworkDocThread.onPostExecute(Documnet.java:1)
   12-03 05:08:43.022: E/AndroidRuntime(1106):  at android.os.AsyncTask.finish(AsyncTask.java:631)
   12-03 05:08:43.022: E/AndroidRuntime(1106):  at android.os.AsyncTask.access$600(AsyncTask.java:177)
   12-03 05:08:43.022: E/AndroidRuntime(1106):  at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
   12-03 05:08:43.022: E/AndroidRuntime(1106):  at android.os.Handler.dispatchMessage(Handler.java:99)
   12-03 05:08:43.022: E/AndroidRuntime(1106):  at android.os.Looper.loop(Looper.java:137)
   12-03 05:08:43.022: E/AndroidRuntime(1106):  at android.app.ActivityThread.main(ActivityThread.java:5041)
   12-03 05:08:43.022: E/AndroidRuntime(1106):  at java.lang.reflect.Method.invokeNative(Native Method)
   12-03 05:08:43.022: E/AndroidRuntime(1106):  at java.lang.reflect.Method.invoke(Method.java:511)
   12-03 05:08:43.022: E/AndroidRuntime(1106):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
   12-03 05:08:43.022: E/AndroidRuntime(1106):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
   12-03 05:08:43.022: E/AndroidRuntime(1106):  at dalvik.system.NativeStart.main(Native Method)

我正在使用2个AsynkTask类,因为我需要第二个类中第一个类的数据,而我无法在onPostExecute的{​​{1}}中进行网络I / O. / p>

EDIT ////////////////////

和文件功能:

AsyncTask

第200行是while((line = in.readLine())!= null)

3 个答案:

答案 0 :(得分:1)

尝试在onCreate(Bundle bundle)

上添加以下代码
@Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
                    .permitAll().build();
    StrictMode.setThreadPolicy(policy);

//your code 
}

答案 1 :(得分:1)

您只是在doInBackground中获取HttpResponse的引用。但是HttpResponse上的所有读/写操作也涉及网络操作。并且您正在读取在UI线程中运行的onPOstExecute()中的HttpResponse。试试这个...

public class NetworkDocStateThread extends AsyncTask<String, Void, Void> {


    @Override
    protected Void doInBackground(String... params) {

        try {
            HttpResponse responseState = JsonDocumnet
                    .SendDocumentState(Financial.selectedGuId);
            Financial.documnetStateDs = JsonDocumnet
                    .DocumentState(responseState);
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        return null;
    }

    @Override
    protected void onPostExecute(Void post) {
        try {


            documentStateSpinner.add(Financial.documnetStateDs.get(i)
                    .getTitle());

            SpinnerStateAdapter = new ArrayAdapter<String>(Documnet.this,
                    R.layout.spinnlayout, R.id.docstateid,
                    documentStateSpinner);

            SpinnerNumAdapter = new ArrayAdapter<String>(Documnet.this,
                    R.layout.spinnlayout, R.id.docstateid, getResources()
                            .getStringArray(R.array.numPerPage));

            SpinnerSortAdapter = new ArrayAdapter<String>(Documnet.this,
                    R.layout.spinnlayout, R.id.docstateid, getResources()
                            .getStringArray(R.array.SortBy));

            new NetworkDocThread().execute(Financial.selectedGuId, "5",

            "0", "Id", "-1");

            docStateSpinner.setAdapter(SpinnerStateAdapter);
            NumberPerPageSpinner.setAdapter(SpinnerNumAdapter);
            SortBySpinner.setAdapter(SpinnerSortAdapter);

        } catch (IllegalStateException e) {

            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }

        super.onPostExecute(post);
    }

}

答案 2 :(得分:0)

执行网络连接任务时,例如从主线程中的服务器获取数据,则会出现此问题。建议您使用doInbackground()的{​​{1}}方法执行此类任务,或者您也可以通过将以下代码放在活动的AsyncTask中来避免此问题:

onCreate()

我希望当你已经在主线程中编写了大量代码时,它会解决你的问题。