How do I implement this image view in an async task?

后端 未结 3 533
故里飘歌
故里飘歌 2021-01-29 05:33

I have an url passed to an activity and I am trying to show the image from the url full screen, however it throws a main network thread exception.

From what I can find

3条回答
  •  不要未来只要你来
    2021-01-29 06:04

    It should be something like this. In the doInBackground you get the image, and in the onPostExecute you set it

    private class DownloadFilesTask extends AsyncTask  {
         @Override
         protected Bitmap doInBackground(String... urls) {
              Bitmap bitmap = null; 
              try {
                  bitmap = BitmapFactory.decodeStream((InputStream)new URL(urls[0]).getContent());
              } catch (MalformedURLException e) {
                   e.printStackTrace();
              } catch (IOException e) {
                 e.printStackTrace();
              }
              return bitmap;
         }
         @Override
         protected void onPostExecute(Bitmap bitmap) {
            ImageView i = (ImageView)findViewById(R.id.imgView);
            i.setImageBitmap(bitmap);
         }
     }
    

    Then, you call it inside your onCreate method

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        String url = getIntent().getStringExtra("SelectedImageURL");
        new DownloadFilesTask ().execute(url); 
    }
    

提交回复
热议问题