【发布时间】:2021-07-02 10:40:09
【问题描述】:
我是 Android 开发新手,我正在尝试制作可显示手机中所有图像的应用。
我正在尝试使用 CursorAdapter 类来实现这一点。
我的代码是,
MainActivity.java
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
GridView gridView = findViewById(R.id.photo_list);
Cursor cursor = getContentResolver().query(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
null,
null,
null,
MediaStore.Images.ImageColumns.DATE_TAKEN + " DESC"
);
MyCursorAdapter myCursorAdapter = new MyCursorAdapter(this, cursor, 0);
gridView.setAdapter(myCursorAdapter);
MyCursorAdapter.java
public class MyCursorAdapter extends CursorAdapter {
public MyCursorAdapter(Context context, Cursor c, int flags) {
super(context, c, flags);
}
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return LayoutInflater.from(context).inflate(R.layout.item_photo, parent, false);
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
ImageView imageView = view.findViewById(R.id.photo_image);
String uri = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA));
Glide.with(context).load(uri).into(imageView);
}
}
应用程序正常运行。但让我烦恼的是这个。
String uri = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA));
不推荐使用常量 DATA 并且它的注释是这样的
* Absolute filesystem path to the media item on disk.
* <p>
* Note that apps may not have filesystem permissions to directly access
* this path. Instead of trying to open this path directly, apps should
* use {@link ContentResolver#openFileDescriptor(Uri, String)} to gain
* access.
*
* @deprecated Apps may not have filesystem permissions to directly
* access this path. Instead of trying to open this path
* directly, apps should use
* {@link ContentResolver#openFileDescriptor(Uri, String)}
* to gain access.
openFileDescriptor() 方法需要 Uri 和 String。但是,正如您在我的代码中看到的那样,我使用 DATA contant 来获取 Uri,因此我无法将 Uri 传递给 openFileDescriptor() 方法,也不知道要传递给 openFileDescriptor() 的字符串参数是什么。
这种情况下,不使用DATA常量怎么写?
感谢您阅读我的问题。
【问题讨论】:
-
But, as you can see in my code, I am using DATA contant to get Uri没有。没有uri,而是一个字符串。一条路径。要获取真正的 uri,请获取 ID 列并使用 uriWithAppendedPath 或 uriWithAppendedId 或无论如何调用它。 -
@blackapps,谢谢你的提示!我解决了这个问题。 XD
标签: java android android-cursor