I am trying to build a simple app (a button that downloads an image and imageView) that downloads an image but the image is not being displayed in the app. The app runs without any errors but the Image is not being displayed. Here is my MainActivity code. Thanks much.
import androidx.appcompat.app.AppCompatActivity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class MainActivity extends AppCompatActivity {
ImageView imageView;
public void downloadImage(View view){
ImageDownloader task = new ImageDownloader();
Bitmap myImage;
try{
myImage = task.execute("https://wallpapercave.com/wp/wp4410880.jpg").get();
imageView.setImageBitmap(myImage);
}catch (Exception e){
e.printStackTrace();
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = findViewById(R.id.imageView);
}
public class ImageDownloader extends AsyncTask<String, Void, Bitmap>{
@Override
protected Bitmap doInBackground(String... urls) {
try {
URL url = new URL(urls[0]);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream in = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(in);
return myBitmap;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
}