在AsyncTask InputStream中获取android.os.NetworkOnMainThreadException

时间:2019-06-13 07:13:43

标签: android android-asynctask

我在Android设备上崩溃,该设备显示android.os.NetworkOnMainThreadException中有关AsyncTask的异常。为什么会出现此异常? onPreExecute中的第60行是例外。

我使用WeakReference发送上下文。请在这里说明使用WeakReference的优势。

public class MainActivity extends AppCompatActivity {

    RecyclerView recyclerView;
    RecyclerView.LayoutManager layoutManager;
    RecyclerViewAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        recyclerView = findViewById(R.id.rview);
        layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setHasFixedSize(true);
        MyTask task = new MyTask(this);
        task.execute();
    }

    static class MyTask extends AsyncTask {
        BufferedReader reader;
        private WeakReference < MainActivity > contextRef;

        MyTask(MainActivity mainActivity) {
            contextRef = new WeakReference < >(mainActivity);
        }

        @Override
        protected void onPreExecute() {
            try {
                URL url = new URL("https://api.myjson.com/bins/1fi1zm");

                URLConnection connection = url.openConnection();
                InputStream stream = connection.getInputStream();
                reader = new BufferedReader(new InputStreamReader(stream));

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

        @Override
        protected Object doInBackground(Object[] objects) {
            return null;
        }

        @Override
        protected void onPostExecute(Object o) {
            MainActivity context = contextRef.get();
            if (context != null) {
                Gson gson = new Gson();
                List < Contact > list;
                try {
                    list = Arrays.asList(gson.fromJson(reader.readLine(), Contact[].class));
                    context.adapter = new RecyclerViewAdapter(list);
                    context.recyclerView.setAdapter(context.adapter);
                } catch(IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

2 个答案:

答案 0 :(得分:0)

以此替换您的代码

     @Override
    protected void onPreExecute() {

    }

    @Override
    protected Object doInBackground(Object[] objects) {
 try {
            URL url = new URL("https://api.myjson.com/bins/1fi1zm");



    URLConnection connection = url.openConnection();
        InputStream stream = connection.getInputStream();
        reader = new BufferedReader(new InputStreamReader(stream));

    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return reader;
}

答案 1 :(得分:0)

问题出在onPreExecute()中的代码。它在主线程上运行,您不能在此处执行后台任务。试试这个

static class MyTask extends AsyncTask {

BufferedReader reader;
private WeakReference<MainActivity> contextRef;

MyTask(MainActivity mainActivity) {
    contextRef = new WeakReference<>(mainActivity);
}


@Override
protected void onPreExecute() {

}

@Override
protected Object doInBackground(Object[] objects) {
    try {
        URL url = new URL("https://api.myjson.com/bins/1fi1zm");

        URLConnection connection = url.openConnection();
        InputStream stream = connection.getInputStream();
        reader = new BufferedReader(new InputStreamReader(stream));

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

    return null;
}

@Override
protected void onPostExecute(Object o) {
    MainActivity context = contextRef.get();

    if (context != null) {
        Gson gson = new Gson();
        List<Contact> list;
        try {
            list = Arrays.asList(gson.fromJson(reader.readLine(), Contact[].class));
            context.adapter = new RecyclerViewAdapter(list);
            context.recyclerView.setAdapter(context.adapter);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

}

让我知道它是否解决了您的问题。