Java 不推荐使用的ManagedQuery()问题
我有这个方法:Java 不推荐使用的ManagedQuery()问题,java,android,deprecated,Java,Android,Deprecated,我有这个方法: public String getRealPathFromURI(Uri contentUri) { String[] proj = { MediaStore.Images.Media.DATA }; Cursor cursor = managedQuery(contentUri, proj, null, null, null); int column_index = cursor.getColumnIndexOrThrow(MediaStore.Imag
public String getRealPathFromURI(Uri contentUri) {
String[] proj = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
不幸的是,编译器在以下方面向我显示了一个问题:
Cursor cursor = managedQuery(contentUri, proj, null, null, null);
因为不推荐使用managedQuery()
如果不使用
managedQuery()
,我如何重写此方法?您可以用context.getContentResolver().query
和LoaderManager
(在API版本11之前,您需要使用兼容包来支持设备)
但是,看起来您只使用了一次查询:您可能根本不需要它。也许这样行吗
public String getRealPathFromURI(Uri contentUri) {
String res = null;
String[] proj = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(contentUri, proj, null, null, null);
if(cursor.moveToFirst()){;
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
res = cursor.getString(column_index);
}
cursor.close();
return res;
}
您可以将其替换为
context.getContentResolver().query
和LoaderManager
(您需要使用兼容包来支持API版本11之前的设备)
但是,看起来您只使用了一次查询:您可能根本不需要它。也许这样行吗
public String getRealPathFromURI(Uri contentUri) {
String res = null;
String[] proj = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(contentUri, proj, null, null, null);
if(cursor.moveToFirst()){;
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
res = cursor.getString(column_index);
}
cursor.close();
return res;
}
您需要初始化游标,因为它将在方法启动之前关闭,或者在其他地方关闭
cursor = null;
public void method(){
// do your stuff here
cursor.close();
}
您需要初始化游标,因为它将在方法启动之前关闭,或者在其他地方关闭
cursor = null;
public void method(){
// do your stuff here
cursor.close();
}
行动。。。“不”在任何情况下都不起作用。。。如果以“file://”开头的uri没有返回正确的路径
file://
uri通常无法使用contentUri
解析:如果您有一个文件uri,那么您已经有了真实的路径。您能给我更多详细信息吗?我有一个“Uri”,我的问题是获取真正的绝对路径,而不包含file://、/content:/和其他属性。对于内容Uri,您需要一个解析器来获取文件Uri,一旦有了文件Uri,您就可以执行新建文件(new Uri(Uri.getPath())
.Ah,当然:新文件(新URI(URI.getPath()).getAbsolutePath()代码>是你需要的,不是吗?行动。。。“不”在任何情况下都不起作用。。。如果以“file://”开头的uri没有返回正确的路径file://
uri通常无法使用contentUri
解析:如果您有一个文件uri,那么您已经有了真实的路径。您能给我更多详细信息吗?我有一个“Uri”,我的问题是获取真正的绝对路径,而不包含file://、/content:/和其他属性。对于内容Uri,您需要一个解析器来获取文件Uri,一旦有了文件Uri,您就可以执行新建文件(new Uri(Uri.getPath())
.Ah,当然:新文件(新URI(URI.getPath()).getAbsolutePath()代码>是您需要的,不是吗?初始化游标有助于使用不推荐的方法,真的吗?初始化游标有助于使用不推荐的方法,真的吗?