안녕하세요.
간단하게 file path를 가지고 해당 파일의 content id 값을 가져오고 싶어 이리 저리 찾아보았는데, 잘되지 않아 문의 드립니다.
제가 찾은 코드는 아래와 같은데 잘 안됩니다. ㅠㅠ
int id =0;
String fileStr = "file://" + gFilePath;
Uri fileUri = Uri.parse(fileStr);
String filePath = fileUri.getPath();
Cursor c = getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,null, "_data = '" + filePath + "'", null,null);
c.moveToNext();
id = c.getInt(0); // <-- 이부분에서 에러가 납니다
Uri uri = ContentUris.withAppendedId(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, id);
file 저장이 MediaStore 에 저장이 되지 않았다면 다른 것으로 반환이 되어서 나와야 된다고 생각하는데, 동작을 하지 않네요 ㅠㅠ
gFilePath 를 가지고 query해 보시겠어요?
그리고 query이전에 실제 파일이 존재하는지 검사해 보시고요,
File f= new File(gFilePath);
if(null != f && f.exists()){
// 미디어 스토어 찾기
}
그리고 파일은 있는데 미디어 스토어에 등록이 안되어 있을 수도 있습니다.
해당 파일을 미디어 스캔도 해 보셔요.
아래 메소드를 한 번 사용해 보실래요?
private int getMediaImageId(Context cxt, String filePath){
int result = -1;
if(null == cxt || null == filePath){
return result;
}
Cursor c = cxt.getContentResolver().query(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
null,
MediaStore.Images.ImageColumns.DATA + "=?",
new String[]{filePath}, null);
if(null != c){
if(true == c.moveToFirst()){
result = c.getInt(0);
}
c.close();
}
return result;
}




1. 커서가 null인지 검사
2. 커서를 맨 앞으로 이동 c.moveToFirst() => return 값 확인
3. c.getInt(0);