Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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:
- ```java
- import android.graphics.Bitmap;
- import android.graphics.BitmapFactory;
- import android.os.AsyncTask;
- import android.widget.ImageView;
- import java.io.InputStream;
- import java.io.IOException;
- import java.net.HttpURLConnection;
- import java.net.URL;
- // Assuming you have an ImageView with the id "imageView" in your layout XML.
- ImageView imageView = findViewById(R.id.imageView);
- String imageUrl = "https://www.example.com/your_image.jpg";
- new DownloadImageTask(imageView).execute(imageUrl);
- private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
- ImageView imageView;
- public DownloadImageTask(ImageView imageView) {
- this.imageView = imageView;
- }
- @Override
- protected Bitmap doInBackground(String... urls) {
- String imageUrl = urls[0];
- Bitmap bitmap = null;
- try {
- URL url = new URL(imageUrl);
- HttpURLConnection connection = (HttpURLConnection) url.openConnection();
- connection.setDoInput(true);
- connection.connect();
- InputStream input = connection.getInputStream();
- bitmap = BitmapFactory.decodeStream(input);
- } catch (IOException e) {
- e.printStackTrace();
- }
- return bitmap;
- }
- @Override
- protected void onPostExecute(Bitmap result) {
- if (result != null) {
- imageView.setImageBitmap(result);
- }
- }
- }
- ```
- 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