i want to build an app that provide full-text search for images in android smartphones using android studio and java, so what I'm doing is take all the paths of images with this method
private ArrayList<String> getAllImagesPath(){
Uri uri;
Cursor cursor;
int columIndexData;
ArrayList<String> imagesPath=new ArrayList<>();
uri= MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
String[] projection ={MediaStore.MediaColumns.DATA, MediaStore.Images.Media.BUCKET_DISPLAY_NAME};
cursor=MainActivity.this.getContentResolver().query(uri,projection,null,null,null);
columIndexData=cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
try {
while (cursor.moveToNext()) {
String imagePath = cursor.getString(columIndexData);
File imgFile = new File(imagePath);
if (imgFile.exists()) {
// Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
imagesPath.add(imagePath);
Log.d("ImagePath", imagePath);
//getTextFromImage(myBitmap);
//Bitmap.relase
// AddToDataBase(myBitmap.toString(), getTextFromImage(myBitmap));
}
}
Log.d("ImagePath", String.valueOf(cursor.getCount()));
} catch (Exception e) {
// Handle any exceptions gracefully
e.printStackTrace();
} finally {
cursor.close();
}
return imagesPath;
}
and i extract text from each image with this method
private String getTextFromImage(Bitmap bitmap){
TextRecognizer recognizer=new TextRecognizer.Builder(MainActivity.this).build();
if (!recognizer.isOperational()){
Log.d("ImagePath", "Error getTextFromImage");
return null;
}
else {
Frame frame=new Frame.Builder().setBitmap(bitmap).build();
SparseArray<TextBlock> textBlockSparseArray=recognizer.detect(frame);
StringBuilder stringBuilder=new StringBuilder();
for (int i=0; i<textBlockSparseArray.size();i++){
TextBlock textBlock=textBlockSparseArray.valueAt(i);
stringBuilder.append(textBlock.getValue());
stringBuilder.append("\n");
}
Log.d("ImagePath", stringBuilder.toString());
return stringBuilder.toString();
}
}
and i use ExecutorService to to avoid blocking the main UI thread.
ExecutorService executor = Executors.newSingleThreadExecutor();
ArrayList<String> imagesPaths = getAllImagesPath();
executor.submit(new Runnable() {
@Override
public void run() {
for (String imagePath : imagesPaths) {
Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
String text = getTextFromImage(bitmap);
bitmap.recycle();
AddToDataBase(imagePath, text);
}
}
});
that will work fine when i make it run on limited images, like 200 image, if it is more the app stop and shows (PROCESS ENDED)
so how can i optimize the code to make it run without stopping and take the time it needs