To load several images from a website, the following code was written.
public void connectImgtoView(final int max) {
new Thread(new Runnable() {
@Override
public void run() {
URL url = null;
for (int i = 0; i < max; i++) {
try {
url = new URL(postImgUrl.get(i));
} catch (MalformedURLException e) {
e.printStackTrace();
}
try {
final BufferedInputStream bufferedInputStream
= new BufferedInputStream(url.openStream());
Bitmap bitmap = BitmapFactory.decodeStream(bufferedInputStream);
bufferedInputStream.close();
final Bitmap scaledBitmap = Bitmap.createScaledBitmap(
bitmap,
(int) (992),
(int) (1403),
true
);
final int finalI = i;
runOnUiThread(new Runnable() {
@Override
public void run() {
postImg[finalI].setImageBitmap(scaledBitmap);
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
progressOFF();
}
}).start();
}
Although this method is performed successfully, there is a problem that the performance speed is too slow.
So I want to know what is faster than this method.
Please help me.
Variable description
postImgUrl : type is ArrayList, this is url that has image i want
postImg : type is ImageView Array, this is ImageView that exists in the layout.
Try placing the for loop out side of Thread
so that you can instantiate and work multiple Threads
simultaneously.
public void connectImgtoView(final int max) {
for (int i = 0; i < max; i++) {
new Thread(new Runnable() {
@Override
public void run() {
URL url = null;
try {
url = new URL(postImgUrl.get(i));
} catch (MalformedURLException e) {
e.printStackTrace();
}
try {
final BufferedInputStream bufferedInputStream
= new BufferedInputStream(url.openStream());
Bitmap bitmap = BitmapFactory.decodeStream(bufferedInputStream);
bufferedInputStream.close();
final Bitmap scaledBitmap = Bitmap.createScaledBitmap(
bitmap,
(int) (992),
(int) (1403),
true
);
final int finalI = i;
runOnUiThread(new Runnable() {
@Override
public void run() {
postImg[finalI].setImageBitmap(scaledBitmap);
}
});
} catch (IOException e) {
e.printStackTrace();
}
progressOFF();
}
}).start();
}
}