Advertisement
programusy

Untitled

Oct 20th, 2023
51
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.96 KB | None | 0 0
  1. If you want to set an ImageView's resource from a web URL without using external libraries like Picasso, you can use the Android `AsyncTask` to download the image and set it in the ImageView. Here's an example:
  2.  
  3. ```java
  4. import android.graphics.Bitmap;
  5. import android.graphics.BitmapFactory;
  6. import android.os.AsyncTask;
  7. import android.widget.ImageView;
  8. import java.io.InputStream;
  9. import java.io.IOException;
  10. import java.net.HttpURLConnection;
  11. import java.net.URL;
  12.  
  13. // Assuming you have an ImageView with the id "imageView" in your layout XML.
  14. ImageView imageView = findViewById(R.id.imageView);
  15.  
  16. String imageUrl = "https://www.example.com/your_image.jpg";
  17.  
  18. new DownloadImageTask(imageView).execute(imageUrl);
  19.  
  20. private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
  21. ImageView imageView;
  22.  
  23. public DownloadImageTask(ImageView imageView) {
  24. this.imageView = imageView;
  25. }
  26.  
  27. @Override
  28. protected Bitmap doInBackground(String... urls) {
  29. String imageUrl = urls[0];
  30. Bitmap bitmap = null;
  31. try {
  32. URL url = new URL(imageUrl);
  33. HttpURLConnection connection = (HttpURLConnection) url.openConnection();
  34. connection.setDoInput(true);
  35. connection.connect();
  36. InputStream input = connection.getInputStream();
  37. bitmap = BitmapFactory.decodeStream(input);
  38. } catch (IOException e) {
  39. e.printStackTrace();
  40. }
  41. return bitmap;
  42. }
  43.  
  44. @Override
  45. protected void onPostExecute(Bitmap result) {
  46. if (result != null) {
  47. imageView.setImageBitmap(result);
  48. }
  49. }
  50. }
  51. ```
  52.  
  53. In this code, we create an `AsyncTask` called `DownloadImageTask` that downloads the image from the web in the background. In the `onPostExecute` method, we set the downloaded image into the ImageView. Make sure to replace `"https://www.example.com/your_image.jpg"` with the actual URL of the image you want to display.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement