从android文件系统中选择多个文件

时间:2018-01-04 09:47:12

标签: java android

在尝试从android文件系统中选择图像时,我目前正在使用以下代码:

MariaDB [sandbox]> INSERT ignore INTO T (DT,MEETING) VALUES ('2018-01-10',NULL);
Query OK, 1 row affected, 1 warning (0.02 sec)

MariaDB [sandbox]> select * from t;
+----+------------+---------+
| id | dt         | meeting |
+----+------------+---------+
|  1 | 2017-12-20 |       1 |
|  2 | 2017-12-20 |       1 |
|  3 | 2017-12-20 |       1 |
|  4 | 2017-12-22 |       1 |
|  5 | 2017-12-25 |       1 |
| 13 | 2018-01-01 |       0 |
| 14 | 2018-01-02 |       0 |
| 15 | 2018-01-10 |       0 |
+----+------------+---------+
8 rows in set (0.00 sec)

遵循以下方法:

public void getPhotoFromSystem(View v) //implement selecting multiple files
{
    Intent intent = new Intent();
    intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
    intent.setAction(Intent.ACTION_GET_CONTENT);
    intent.setType("image/*)");
    startActivityForResult(intent, READ_REQUEST_CODE);
}

这样可行,但实际上并不允许我一次选择多个文件,也不允许我在默认照片库之外抓取照片。我已经尝试了一些我见过的其他建议,但没有任何效果。

2 个答案:

答案 0 :(得分:4)

我从你身上了解到的问题是你需要一次性选择多个图像。

请注意,Android的选择器在某些设备上提供了照片和图库。照片允许选择多个图像。图库一次只允许一个。

Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*"); //allows any image file type. Change * to specific extension to limit it
//**These following line is the important one!
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), SELECT_PICTURES); //SELECT_PICTURES is simply a global int used to check the calling intent in onActivityResult

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if(requestCode == SELECT_PICTURES) {
        if(resultCode == Activity.RESULT_OK) {
            if(data.getClipData() != null) {
                int count = data.getClipData().getItemCount();
                int currentItem = 0;
                while(currentItem < count) {
                    Uri imageUri = data.getClipData().getItemAt(currentItem).getUri();
                    //do something with the image (save it to some directory or whatever you need to do with it here)
                    currentItem = currentItem + 1;
                }
            } else if(data.getData() != null) {
                String imagePath = data.getData().getPath();
                //do something with the image (save it to some directory or whatever you need to do with it here)
            }
        }
    }
}

答案 1 :(得分:0)

当我们选择多个文件时,结果会出现在ClipData下,因此我们需要从数据中获取 ClipData ,然后遍历其他人以获得Uri的数量。

 if (data.getClipData()!=null){
        //multiple data received
        ClipData clipData = data.getClipData();
        for (int count =0; count<clipData.getItemCount(); count++){
            Uri uri = clipData.getItemAt(count).getUri());
            //do something 
        }
    }

注意:这适用于API级别16及以上版本。