Android : How to check File Exists in MediaStore via URI

อีกวิธีการในการตรวจสอบไฟล์หากว่าเรามีไฟล์ในรูปแบบ URI (content://…) เราสามารถใช้ URI มาค้นหาว่ามีไฟล์ตาม URI นี้จริงหรือไม่ โดยในตัวอย่างเป็นฟังก์ชันที่ส่งค่า content uri เข้ามาแล้วตอบกลับด้วยผลลัพธ์ตรรกะ (Boolean) ดังนี้

private boolean chkImgUri(Uri in_imgUri) {

boolean res;

ContentResolver cr = getContentResolver();
String[] projection = {MediaStore.MediaColumns.DATA};
Cursor cur = cr.query(Uri.parse(in_imgUri.toString()), projection, null, null, null);
if (cur != null) {
if (cur.moveToFirst()) {
String filePath = cur.getString(0);
// true= if it exists
// false= File was not found
res = new File(filePath).exists();

} else {
// Uri was ok but no entry found.
res = false;
}
cur.close();
} else {
// content Uri was invalid or some other error occurred
res = false;
}

return res;
}

จากตัวอย่างใช้การค้นหาจาก input uri (in_imguri) แล้วจะได้ filePath ถ้ามีอยู่จริงก็จะตอบกลับด้วย Boolean true;

You may also like...