Android : How to query file name from MediaStore

MediaStore เป็นพื้นที่จัดเก็บข้อมูลมัลติมีเดีย เช่น รูปภาพ เสียง วิดิโอ เป็นต้น โดยจัดเก็บในรูปแบบ content URI (content://… ) ซึ่งจะไม่ได้อยู่ในชื่อไฟล์แบบทั่วๆไป หากเราต้องการจะค้นหาไฟล์ด้วยการใช้ MedisStore Query เราสามารถทำได้ดังนี้

ในตัวอย่างสร้างฟังก์ชันการค้นหา โดยการใส่ชื่อไฟล์ลงไป แล้วตอบกลับด้วยผลลัพธ์เป็นตรรกะ (Boolean) ดังนี้

private boolean chkFilefromMediaStore(String in_filename) {

String path, filename;
try (Cursor cursor = getApplicationContext().getContentResolver().query(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
null, null, null, null
)) {

assert cursor != null;
while (cursor.moveToNext()) {
// Use an ID column from the projection to get
// a URI representing the media item itself.
path = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA));
filename = path.substring(path.lastIndexOf('/') + 1);

if (filename.equals(in_filename)) {

return true;
}
}
}

return false;

}

โดยในฟังก์ชันจะเข้าไปค้นหาจาก External Storage ผ่าน MediaStore.Images.Media.EXTERNAL_CONTENT_URI แล้วจะได้ชื่อไฟล์ออกมา ถ้าตรงกับที่กำหนดก็จะตอบกลับด้วยผลลัพธ์ boolean true;

You may also like...