public class MainActivity extends AppCompatActivity {
ImageView imageview;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageview = (ImageView)findViewById(R.id.imageview);
Uri uri = pickRandomImage();
ArrayList<Uri> allImageUri;
allImageUri = getAllImage();
int total = allImageUri.size();
int randomIndex = (int)(Math.random()*total);
Uri randomUri = allImageUri.get(randomIndex);
try {
Bitmap bm = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
imageview.setImageBitmap(bm);
} } catch (FileNotFoundException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), "No files", 0).show();
} } catch (IOException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Error", 0).show();
}
}
ArrayList<Uri> getAllImage() {
String[] projection = {MediaStore.Images.Media.DATA};
Cursor c = getApplicationContext().getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
projection,
null,
null,
null);
ArrayList<Uri> result = new ArrayList<>(c.getCount());
int dataColumnIndex = c.getColumnIndex(projection[0]);
if (c == null) {
Toast.makeText(getApplicationContext(), "No pictures.", 0);
} } else if (c.moveToFirst()) {
do {
String filepath = c.getString(dataColumnIndex);
Uri imageUri = Uri.parse(filepath);
result.add(imageUri);
}while(c.moveToNext());
}else{
Toast.makeText(getApplicationContext(), "Cursor is empty", 0);
}
c.close();
return result;
}
Get all uri of the pictures on the device and save them as arrays I tried to generate a random number and use that random number to get a random uri and print it out in the image view as a bitmap, but the picture doesn't come out. If I check the toast message, there is no file, so I think there is a problem with printing it in the image view with a bitmap, so how should I implement it?
android
MediaStore.Images.Media.getBitmap()
's second parameter, uri, must hand over the file scheme. Try changing the code as follows.
MediaStore.Images.Media.getBitmap(getContentResolver(), Uri.parse("file://" + uri));
Or
MediaStore.Images.Media.getBitmap(getContentResolver(), Uri.fromFile(new File(uri)));
© 2024 OneMinuteCode. All rights reserved.