如何将图像加载到游标中?

时间:2018-09-30 10:07:33

标签: java android

因此,以下是GridActivity类中的整个代码。我一直在尝试使用其他线程将图像从外部存储加载到光标中,但是我的应用程序每次都会停止/崩溃。我发现加载图像'cursor = getContentResolver()...'的行是崩溃的地方。我已经尝试了所有我知道的事情,但似乎无法进步。有什么想法吗?

public class GridActivity extends Activity
{

Uri uri;
Cursor cursor;
int column_index;
String path = null,sortOrder;
String[] projection;
ArrayList<String> imageList = new ArrayList<>();


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_grid);


    uri = android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
    projection = new String[]{MediaStore.MediaColumns.DATA};
    //DATA is the path to the corresponding image. We only need this for loading //image into a recyclerview

    sortOrder = MediaStore.Images.ImageColumns.DATE_ADDED + "DESC";
    //This sorts all images such that recent ones appear first

    LoadRunnable loadRunnable = new LoadRunnable();
    new Thread(loadRunnable).start();

}

private class LoadRunnable implements Runnable
{

    @Override
    public void run() {

        cursor = getContentResolver().query(uri, projection, null,null, sortOrder);

        try {
            if (null != cursor) {
                column_index = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
                while (cursor.moveToNext()) {
                    path = cursor.getString(column_index);
                    imageList.add(path);
                }
                cursor.close();
                //imageList gets populated with paths to images by here
            }
        }catch (Exception e){

            e.printStackTrace();
        }
    }
}
}

0 个答案:

没有答案