我使用ACTION_PICK来调用默认的Android图库和EXTRA_ALLOW_MULTIPLE来选择多个图像。现在我尝试将所有选定的图像复制到另一个文件夹,但是当选择多个(3个或更多)图像然后继续复制时,只复制了两个图像。
抱歉,我是初学Android编程。
将多个所选图像从Gallery复制到另一个文件夹的正确方法是什么?
这是我的代码:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == PICK_IMAGE_MULTIPLE) {
switch (requestCode) {
case PICK_IMAGE_MULTIPLE:
if(data!=null){
ClipData clipdata = data.getClipData();
if(clipdata!=null){
for (int i = 0; i < clipdata.getItemCount(); i++) {
ClipData.Item item = clipdata.getItemAt(i);
Uri uri = item.getUri();
String root = Environment.getExternalStorageDirectory().getAbsolutePath()+ "/";
File f = new File(root + "New Folder" + File.separator);
f.mkdir();
String PictureName = getPicturename();
try {
if (f.exists()&&uri!=null) {
File file = new File(root + "New Folder" + File.separator + PictureName);
file.createNewFile();
path = getPath(getApplicationContext(), uri);
File src = new File(path);
copyFile(src,file);
Toast.makeText(this, "Copy File" + path, Toast.LENGTH_SHORT).show();
}
}catch (IOException e){
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(this, "Directory not create", Toast.LENGTH_SHORT).show();
}
}
}
}
break;
}
}
}
}
public String getPath(Context context,Uri contentUri) {
Cursor cursor = null;
try {
String[] proj = {MediaStore.Images.Media.DATA};
cursor = context.getContentResolver().query(contentUri, proj, null,
null, null);
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} finally {
if (cursor != null) {
cursor.close();
}
}
}
public void copyFile(File sourceFile , File destFile)
throws IOException {
InputStream in = new FileInputStream(sourceFile);
OutputStream out = new FileOutputStream(destFile);
// Transfer bytes from in to out
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
}
private String getPicturename() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
String timestamp = sdf.format(new Date());
return "Img" + timestamp + ".jpg";
}
}