In my app, I am trying to decode bitmaps Asynchronously, therefore I am using CompletableFuture.runAsync(() -> {});
method to run it Asynchronously, but it seems bitmap decoding is still not running Asynchronously because I am having a lagging in my UIs every time I run my app (I am running spinKitLayout to indicate the user, process is still going on, but spinKitLayout is the one which is lagging in my main thread), I don’t understand why it is still having a lag although I am running it Asynchronously. I am still a newbie to Asynchronous programming, Can anyone point me out where the problem is in my code and what can be the possible solution to this?
private void createBitmapDatabase() {
currentBitmapIndex = 0;
createNextBitMapFile(bitmapDataList);
}
private void createNextBitMapFile(List<BitmapData> bitmapDataList) {
if (currentBitmapIndex < bitmapDataList.size()){
CompletableFuture.runAsync(() -> {
createBitmapAsync(bitmapDataList.get(currentBitmapIndex).getBitmapUri(),bitmapDataList.get(currentBitmapIndex).getBitmapName(),currentBitmapIndex, new BitmapCreationListener() {
@Override
public void onBitmapCreated(int index, String bitmapName, Bitmap bitmap) {
runOnUiThread(() -> {
augmentedImageDatabase.addImage(bitmapName,bitmap);
currentBitmapIndex++;
createNextBitMapFile(bitmapDataList);
});
}
@Override
public void onBitmapCreationFailed(int index, String bitmapName, String errorMessage) {
runOnUiThread(() -> {
Toast.makeText(MainActivity.this, "Bitmap for "+bitmapName+" "+errorMessage, Toast.LENGTH_SHORT).show();
bitmapFailedCount++;
currentBitmapIndex++;
createNextBitMapFile(bitmapDataList);
});
}
});
});
}else {
if (bitmapFailedCount != 0){
runOnUiThread(() -> Toast.makeText(this, bitmapDataList.size()-bitmapFailedCount+" bitmaps created and "+bitmapFailedCount+" Failed!", Toast.LENGTH_SHORT).show());
}else {
runOnUiThread(() -> Toast.makeText(this, "All bitmaps created", Toast.LENGTH_SHORT).show());
}
backgroundBlurView.setVisibility(View.GONE);
spinKitLayout.setVisibility(View.GONE);
if (augmentedImageDatabase != null){
Toast.makeText(this, "Database created with "+augmentedImageDatabase.getNumImages()+" images", Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(this, "Database is Empty", Toast.LENGTH_SHORT).show();
}
}
}
private void createBitmapAsync(Uri bitmapUri,String bitmapName, int index, BitmapCreationListener bitmapCreationListener) {
//CompletableFuture.runAsync(() -> {
try (InputStream inputStream = getContentResolver().openInputStream(bitmapUri)) {
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
if (bitmap != null) {
bitmapCreationListener.onBitmapCreated(index, bitmapName, bitmap);
} else {
bitmapCreationListener.onBitmapCreationFailed(index, bitmapName, "Failed to decode bitmap!");
}
} catch (IOException e) {
bitmapCreationListener.onBitmapCreationFailed(index, bitmapName, "Error loading bitmap: " + e.getMessage());
}
//});
}