У меня есть класс AsyncTask для загрузки изображения из Интернета и установки его в ImageView
(ссылка здесь )
Соответствующий код активности:
public class ListAdoptions extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_adoptions);
recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
mAdapter = new PetsAdapter(petList);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(mAdapter);
preparePetData();
}
private void preparePetData() {
DownloadImageTask imgtask = new DownloadImageTask((ImageView) findViewById(R.id.picture));
imgtask.execute("https://i.ytimg.com/vi/opKg3fyqWt4/hqdefault.jpg");
mAdapter.notifyDataSetChanged();
}
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public DownloadImageTask(ImageView bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}
}
Ошибка:
Process: com.example.test3, PID: 8427
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setImageBitmap(android.graphics.Bitmap)' on a null object reference
at com.example.petadoption.ListAdoptions$DownloadImageTask.onPostExecute(ListAdoptions.java:171)
at com.example.petadoption.ListAdoptions$DownloadImageTask.onPostExecute(ListAdoptions.java:150)
at android.os.AsyncTask.finish(AsyncTask.java:695)
at android.os.AsyncTask.-wrap1(Unknown Source:0)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:712)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6541)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)