Я получаю сбой в устройстве Android, которое показывает исключение около android.os.NetworkOnMainThreadException
в AsyncTask
. Почему я получаю это исключение? Исключение составляет строка 60 в onPreExecute
.
Я отправляю контекст с помощью 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();
}
}
}
}
}