OnMainThreadException错误,虽然在主线程上没有执行网络操作?

时间:2013-08-26 16:48:58

标签: android multithreading exception asynchronous main

所以我正在创建一个应用程序,我只是初学者,但我遇到了困难,我有这个代码:

public class MenuChoice extends Activity {
    InputStream string = null;
    ArrayList<String> Deals = null;
    ArrayList<String> ImageBase;
    int currentDeal = 0;

    public void StreamReader() throws IOException{
        InputStreamReader is = new InputStreamReader(string);
        StringBuilder sb=new StringBuilder();
        BufferedReader br = new BufferedReader(is);
        String read = br.readLine();

        while(read != null) {
            //System.out.println(read);
            sb.append(read);
            read =br.readLine();

        }
        String[] DealList = sb.toString().split("±");
        //ArrayList<String> deals = new ArrayList<String>();
        for(int i = 0; i < DealList.length; i++){
            Log.d("msgs", DealList[i]);
            if(DealList[i].length() > 5){
                Deals.add(DealList[i]);
            }
        }
//      return deals;
    }
    public String DownloadImg(String urla, String newname){
        String fileName = null;
        try{
        URL url = new URL (urla);
        InputStream input = url.openStream();
        try {
        //The sdcard directory e.g. '/sdcard' can be used directly, or 
        //more safely abstracted with getExternalStorageDirectory()
        File storagePath = Environment.getExternalStorageDirectory();
        OutputStream output = new FileOutputStream (storagePath + "/" + newname + "/.png");
        fileName = storagePath + "/" + newname + "/.png";
        try {
            byte[] buffer = new byte[5000];
            int bytesRead = 0;
            while ((bytesRead = input.read(buffer, 0, buffer.length)) >= 0) {
                output.write(buffer, 0, bytesRead);
            }
        } finally {
            output.close();
        }
        } finally {
        input.close();
        }
        }
        catch(Exception e){
        }

        return fileName;
    }
    public void SetInp(InputStream inp){
        string = inp;
    }

    public class GetDeals extends AsyncTask<Void, Void, Void>{

        @Override
        protected Void doInBackground(Void... params) {
            InputStream str = null;
            HttpClient htc = new DefaultHttpClient();
            HttpPost htp = new HttpPost("site/android_connect.php");
                try {
                    HttpEntity resp = htc.execute(htp).getEntity();
                    InputStream strings = resp.getContent();
                    str = strings;
                } catch (ClientProtocolException e) {
                    Log.d("problema" ,"BAD!");
                    e.printStackTrace();
                } catch (IOException e) {
                    Log.d("problema" ,"BAD!");
                    e.printStackTrace();
                }
            string = str;
            return null;

    }
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_menu_choice);

        try {
            new GetDeals().execute().get();
        }
        catch(Exception e){}
        /*    try {
            Deals = StreamReader(string);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        /*
        for(int i = 0; i<Deals.size(); i++){

            ImageBase.add(DownloadImg(Deals.get(i), "Deal"+i));
            Log.d("bugger", DownloadImg(Deals.get(i), "Deal"+i));
        }
        */
        try {
            StreamReader();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }



    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_choice, menu);
        return true;
    }

}

所以我抛出了这个错误:

  

08-26 17:42:52.030:E / AndroidRuntime(10221):致命异常:主要   08-26 17:42:52.030:E / AndroidRuntime(10221):   java.lang.RuntimeException:无法启动活动   ComponentInfo {plugMedia.kcrarea / plugMedia.kcrarea.MenuChoice}:   android.os.NetworkOnMainThreadException 08-26 17:42:52.030:   E / AndroidRuntime(10221):at   android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1956)   08-26 17:42:52.030:E / AndroidRuntime(10221):at   android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)   08-26 17:42:52.030:E / AndroidRuntime(10221):at   android.app.ActivityThread.access $ 600(ActivityThread.java:123)08-26   17:42:52.030:E / AndroidRuntime(10221):at   android.app.ActivityThread $ H.handleMessage(ActivityThread.java:1147)   08-26 17:42:52.030:E / AndroidRuntime(10221):at   android.os.Handler.dispatchMessage(Handler.java:99)08-26   17:42:52.030:E / AndroidRuntime(10221):at   android.os.Looper.loop(Looper.java:137)08-26 17:42:52.030:   E / AndroidRuntime(10221):at   android.app.ActivityThread.main(ActivityThread.java:4424)08-26   17:42:52.030:E / AndroidRuntime(10221):at   java.lang.reflect.Method.invokeNative(Native Method)08-26   17:42:52.030:E / AndroidRuntime(10221):at   java.lang.reflect.Method.invoke(Method.java:511)08-26 17:42:52.030:   E / AndroidRuntime(10221):at   com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:787)   08-26 17:42:52.030:E / AndroidRuntime(10221):at   com.android.internal.os.ZygoteInit.main(ZygoteInit.java:554)08-26   17:42:52.030:E / AndroidRuntime(10221):at   dalvik.system.NativeStart.main(Native Method)08-26 17:42:52.030:   E / AndroidRuntime(10221):引起:   android.os.NetworkOnMainThreadException 08-26 17:42:52.030:   E / AndroidRuntime(10221):at   android.os.StrictMode $ AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1099)   08-26 17:42:52.030:E / AndroidRuntime(10221):at   libcore.io.BlockGuardOs.recvfrom(BlockGuardOs.java:163)08-26   17:42:52.030:E / AndroidRuntime(10221):at   libcore.io.IoBridge.recvfrom(IoBridge.java:503)08-26 17:42:52.030:   E / AndroidRuntime(10221):at   java.net.PlainSocketImpl.read(PlainSocketImpl.java:488)08-26   17:42:52.030:E / AndroidRuntime(10221):at   java.net.PlainSocketImpl.access $ 000(PlainSocketImpl.java:46)08-26   17:42:52.030:E / AndroidRuntime(10221):at   java.net.PlainSocketImpl $ PlainSocketInputStream.read(PlainSocketImpl.java:240)   08-26 17:42:52.030:E / AndroidRuntime(10221):at   org.apache.http.impl.io.AbstractSessionInputBuffer.fillBuffer(AbstractSessionInputBuffer.java:103)   08-26 17:42:52.030:E / AndroidRuntime(10221):at   org.apache.http.impl.io.AbstractSessionInputBuffer.read(AbstractSessionInputBuffer.java:120)   08-26 17:42:52.030:E / AndroidRuntime(10221):at   org.apache.http.impl.io.ChunkedInputStream.getChunkSize(ChunkedInputStream.java:211)   08-26 17:42:52.030:E / AndroidRuntime(10221):at   org.apache.http.impl.io.ChunkedInputStream.nextChunk(ChunkedInputStream.java:183)   08-26 17:42:52.030:E / AndroidRuntime(10221):at   org.apache.http.impl.io.ChunkedInputStream.read(ChunkedInputStream.java:155)   08-26 17:42:52.030:E / AndroidRuntime(10221):at   org.apache.http.conn.EofSensorInputStream.read(EofSensorInputStream.java:159)   08-26 17:42:52.030:E / AndroidRuntime(10221):at   java.io.InputStreamReader.read(InputStreamReader.java:244)08-26   17:42:52.030:E / AndroidRuntime(10221):at   java.io.BufferedReader.fillBuf(BufferedReader.java:130)08-26   17:42:52.030:E / AndroidRuntime(10221):at   java.io.BufferedReader.readLine(BufferedReader.java:390)08-26   17:42:52.030:E / AndroidRuntime(10221):at   plugMedia.kcrarea.MenuChoice.StreamReader(MenuChoice.java:59)08-26   17:42:52.030:E / AndroidRuntime(10221):at   plugMedia.kcrarea.MenuChoice.onCreate(MenuChoice.java:158)08-26   17:42:52.030:E / AndroidRuntime(10221):at   android.app.Activity.performCreate(Activity.java:4465)08-26   17:42:52.030:E / AndroidRuntime(10221):at   android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)   08-26 17:42:52.030:E / AndroidRuntime(10221):at   android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)   08-26 17:42:52.030:E / AndroidRuntime(10221):... 11更多

我理解它说我正在尝试在主线程上执行网络操作,但我所做的只是调用StreamReader,我假设它只是转换InputStream(从AsyncTask保存和检索但是它会抛出错误。

有任何帮助吗?是什么导致了它?

谢谢。

1 个答案:

答案 0 :(得分:1)

  

但是如果我删除.get(),它不会将InputSream string = null设置为它从链接获得的InputStream。

将您对InputStream及其结果(例如,StreamReader()来电)的使用移至onPostExecute()的{​​{1}},并移除对AsyncTask的调用}。正如Raghunandan指出的那样,get()基本上意味着首先拥有get()毫无意义,这就是为什么我有an outstanding feature request to get a Lint warning added for this