将图像从FilePicker

将图像从FilePicker

本文介绍了将图像从FilePicker / Intent复制到另一个目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图将Image i从Intent复制到另一个目录。但我不能得到它的工作。需要帮助。



我的Logcat:

  56:22.778 31620-31620 / com.example.krupal.sqlitetest I /编舞:跳过42帧!应用程序可能在其主线程上做太多的工作。 
04-29 14:56:24.944 31620-31633 / com.example.krupal.sqlitetest W / EGL_emulation:eglSurfaceAttrib not implemented
04-29 14:56:24.944 31620-31633 / com.example。 krupal.sqlitetest W / OpenGLRenderer:无法在表面0x7f5170636740上设置EGL_SWAP_BEHAVIOR,错误= EGL_SUCCESS
04-29 14:56:26.370 31620-31633 / com.example.krupal.sqlitetest E /表面:getSlotFromBufferLocked:未知缓冲区: 0x7f517631a550
04-29 14:56:26.381 31620-31620 / com.example.krupal.sqlitetest W / InputEventReceiver:尝试完成输入事件,但输入事件接收器已处理。
04-29 14:56:26.381 31620-31620 / com.example.krupal.sqlitetest W / ViewRootImpl:删除根视图时删除事件:MotionEvent {action = ACTION_HOVER_ENTER,actionButton = 0,id [0] = 0,flags [0] = 322.27295,y [0] = 447.5,toolType [0] = TOOL_TYPE_FINGER,buttonState = 0,metaState = 0,flags = 0x0,edgeFlags = 0x0,pointerCount = 1,historySize = 4168947,downTime = 4168760,deviceId = 0,source = 0x1002}
04-29 14:56:26.381 31620-31620 / com.example.krupal.sqlitetest W / InputEventReceiver:尝试完成输入事件,事件接收器已经被处理。
04-29 14:56:26.381 31620-31620 / com.example.krupal.sqlitetest W / ViewRootImpl:删除根视图时删除事件:MotionEvent {action = ACTION_HOVER_ENTER,actionButton = 0,id [0] = 0,flags [0] = 322.27295,y [0] = 447.5,toolType [0] = TOOL_TYPE_FINGER,buttonState = 0,metaState = 0,flags = 0x0,edgeFlags = 0x0,pointerCount = 1,historySize = 4168947,downTime = 4168760,deviceId = 0,source = 0x1002}
04-29 14:56:26.381 31620-31620 / com.example.krupal.sqlitetest W / InputEventReceiver:尝试完成输入事件,事件接收器已经被处理。
04-29 14:56:26.381 31620-31620 / com.example.krupal.sqlitetest W / ViewRootImpl:删除根视图时删除事件:MotionEvent {action = ACTION_HOVER_MOVE,actionButton = 0,id [0] = 0,flags [0] = 322.27295,y [0] = 447.5,toolType [0] = TOOL_TYPE_FINGER,buttonState = 0,metaState = 0,flags = 0x0,edgeFlags = 0x0,pointerCount = 1,historySize = 4168947,downTime = 4168760,deviceId = 0,source = 0x1002}
04-29 14:56:26.381 31620-31620 / com.example.krupal.sqlitetest W / InputEventReceiver:尝试完成输入事件,事件接收器已经被处理。
04-29 14:56:27.652 31620-31633 / com.example.krupal.sqlitetest E / Surface:getSlotFromBufferLocked:unknown buffer:0x7f517631a710
04-29 14:56:29.935 31620-31630 / com .example.krupal.sqlitetest I / art:后台粘性并发标记扫描GC释放7247(862KB)AllocSpace对象,0(0B)LOS对象,0%免费,10MB / 10MB,暂停10.778ms总计53.218ms
04 -29 14:56:30.051 31620-31620 / com.example.krupal.sqlitetest D / BuildVersion:Build version> = 19
04-29 14:56:30.070 31620-31620 / com.example.krupal。 sqlitetest D / AndroidRuntime:关闭VM


---------崩溃开始
04-29 14:56:30.071 31620-31620 / com。 example.krupal.sqlitetest E / AndroidRuntime:FATAL EXCEPTION:main
进程:com.example.krupal.sqlitetest,PID:31620
** java.lang.RuntimeException:传递结果失败ResultInfo {who = null ,request = 1,result = -1,data = Intent {dat = content://com.android.externalstorage.documents/document/primary:Download / 2015-09-09.jpg flg = 0x1}} to activity {com .example.krupal.sqlitetest / com.example.krupal.sqlitetest.MainActivity}:java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法'char [] java.lang.String.toCharArray()'
at android.app.ActivityThread.deliverResults(ActivityThread.java:3699)
在android.app.ActivityThread.handleSendResult(ActivityThread.java:3742)
在android.app.ActivityThread.- wrap16(ActivityThread.java)
在android.app.ActivityThread $ H.handleMessage(ActivityThread.java:1393)
在android.os.Handler.dispatchMessage(Handler.java:102)
在android.os.Looper.loop(Looper.java:148)
在android.app.ActivityThread.main(ActivityThread.java:5417)
在java.lang.reflect.Method.invoke(Native方法)
at com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by:java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法'char [] java.lang.String.toCharArray()'
at java.io.File.fixSlashes File.java:183)
at java.io.File。< init>(File.java:130)
at com.example.krupal.sqlitetest.MainActivity.onActivityResult(MainActivity.java:160 )
at android.app.Activity.dispatchActivityResult(Activity.java:6428)
在android.app.ActivityThread.deliverResults(ActivityThread.java:3695)
在android.app.ActivityThread。 handleSendResult(ActivityThread.java:3742)
在android.app.ActivityThread.-wrap16(ActivityThread.java)
在android.app.ActivityThread $ H.handleMessage(ActivityThread.java:1393)
在android.os.Handler.dispatchMessage(Handler.java:102)
在android.os.Looper.loop(Looper.java:148)
在android.app.ActivityThread.main(ActivityThread。 java:5417)
在java.lang.reflect.Method.invoke(本地方法)
at com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
04-29 14:56:32.316 31620-31620 / com.example.krupal.sqlitetest I /过程:发送信号。 PID:31620 SIG:9

资料来源:

  protected void onActivityResult(int requestCode,int resultCode,Intent data){
super.onActivityResult(requestCode,resultCode,data);
if(resultCode == Activity.RESULT_OK){
switch(requestCode){
case SELECT_PICTURE:{
Uri selectedImageURI = data.getData();
if(Build.VERSION.SDK_INT< 19){
String selectedImagePath = getPath(selectedImageURI);
Bitmap bitmap = BitmapFactory.decodeFile(selectedImagePath);
avatar.setImageBitmap(bitmap);
copyImageToInternalStorage(new File(getPath(selectedImageURI)));
Log.d(BuildVersion,Build version< 19);

} else {
ParcelFileDescriptor parcelFileDescriptor;
try {
parcelFileDescriptor = getContentResolver()。openFileDescriptor(selectedImageURI,r);
FileDescriptor fileDescriptor = null;
if(parcelFileDescriptor!= null){
fileDescriptor = parcelFileDescriptor.getFileDescriptor();
}
Bitmap image = BitmapFactory.decodeFileDescriptor(fileDescriptor);
avatar.setImageBitmap(image);
Log.d(BuildVersion,Build version> = 19);
copyImageToInternalStorage(new File(getPath(selectedImageURI)));

} catch(FileNotFoundException e){
e.printStackTrace();
}
}
break;
}
(其他)
}

复制方法:

  private void copyImageToInternalStorage(File sourcefile){
String timeStamp = new SimpleDateFormat(ddMMyyyy_HHmmss)。format日期());
文件夹= getExternalFilesDir(ImageDatabase);
文件file =新文件(文件夹,IMG _+ timeStamp +。jpg);

if(!sourcefile.exists()){
return;
}
FileChannel source = null;
FileChannel dest = null;

try {
source = new FileInputStream(sourcefile).getChannel();
dest = new FileOutputStream(file).getChannel();
if(source!= null&& dest!= null){
dest.transferFrom(source,0,source.size());
}
if(source!= null){
source.close();
}
if(dest!= null){
dest.close();
}
} catch(FileNotFoundException e){
e.printStackTrace();
} catch(IOException e){
e.printStackTrace();
}
}

GetPath方法:

  public String getPath(Uri uri){
String [] projection = {MediaStore.Images.Media.DATA};

//游标cursor = managedQuery(uri,projection,null,null,null);
@SuppressWarnings(deprecation)
Cursor cursor = managedQuery(uri,projection,null,null,null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}

但这是给我NullPointerException。需要改变什么?

解决方案

这是一个工作代码,我已经用于点击图像后复制文件。您必须先为其创建目录结构。

  @Override 
protected void onActivityResult(int requestCode,int resultCode ,Intent data){
super.onActivityResult(requestCode,resultCode,data);
if(resultCode == RESULT_OK){

switch(requestCode){
case CLICK_PHOTO:
imageUri = data.getData();
path = Utils.getRealPathFromURI(Photos.this,imageUri);
picturePath = path.toString();

fileName = picturePath.substring(picturePath.lastIndexOf(/)+ 1);


mFile = new File(Utils.getPath(getDIR),fileName);

try {
copyFile(new File(picturePath),mFile);
} catch(IOException e){
e.printStackTrace();
}

saveBitmapToFile(mFile);

PhotoBeans bean = new PhotoBeans();
bean.setThumbImageUrl(mFile.getAbsolutePath());
bean.setIsImageSelected(false);

arrayListPhoto.add(bean);
adapter.notifyDataSetChanged(); //这将尝试加载您的新图像

gvImages.invalidateViews(); // then you are refreshing views and setting the adapter again below

gvImages.setAdapter(adapter);
//初始化适配器

break;

case SELECT_PHOTO:
imageUri = data.getData();
path = Utils.getRealPathFromURI(Photos.this,imageUri);
picturePath = path.toString();

fileName = picturePath.substring(picturePath.lastIndexOf(/)+ 1);

mFile = new File(Utils.getPath(getDIR),fileName);

try {
copyFile(new File(picturePath),mFile);
} catch(IOException e){
e.printStackTrace();
}

saveBitmapToFile(mFile);

PhotoBeans beans = new PhotoBeans();
beans.setThumbImageUrl(mFile.getAbsolutePath());
beans.setIsImageSelected(false);

arrayListPhoto.add(beans);
adapter.notifyDataSetChanged(); //这将尝试加载您的新图像

gvImages.invalidateViews(); // then you are refreshing views and setting the adapter again below

gvImages.setAdapter(adapter);
//初始化适配器
break;

}
}
}

CopyFile )

  private void copyFile(File sourceFile,File destFile)throws IOException {
//创建现有文件
if(!sourceFile.exists()){
return;
}

FileChannel source = null;
FileChannel destination = null;
source = new FileInputStream(sourceFile).getChannel();
destination = new FileOutputStream(destFile).getChannel();
if(destination!= null&& source!= null){
destination.transferFrom(source,0,source.size());
}
if(source!= null){
source.close();
}
if(destination!= null){
destination.close();
}
}

目录结构

  private void createDirectoryStructure(){
try {
createDirectory(Environment.getExternalStorageDirectory()+,YourDirecrtoryName);
createDirectory(Environment.getExternalStorageDirectory()+/+YourDirecrtoryName,FolderInsideDirectory);
} catch(Exception e){
e.printStackTrace();
}
}

private void createDirectory(String filePath,String directoryName){
try {
File mfile = new File(filePath,directoryName);
if(!mfile.exists()){
mfile.mkdirs();
Log.e(In error,createDirectory);
} else {
Log.e(In nottt error,createDirectory);
}
} catch(Exception e){
e.printStackTrace();
}
}

Utils.getPath()

  public static String getPath(String getDIR){
String path =;
if(Environment.getExternalStorageState()。equals(
Environment.MEDIA_MOUNTED)){
path = Environment.getExternalStorageDirectory()。getAbsolutePath();
}
if(getDIR.equalsIgnoreCase(images)){
return path +/ YourDirectoryName / YourDirectoryName Images;
} else if(getDIR.equalsIgnoreCase(videos)){
return path +/ YourDirectoryName / YourDirectoryName Videos;
} else {
return path +/ YourDirectoryName / YourDirectoryName Documents;
}
}

从Uri获取图像的路径。 / p>

  public static String getRealPathFromURI(Context context,Uri contentUri){
Cursor cursor = null;
try {
String [] proj = {MediaStore.Images.Media.DATA};
cursor = context.getContentResolver()。query(contentUri,proj,null,null,null);
Log.e(Cursor,+ cursor);
if(cursor!= null){
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
else {
返回null;
}

} finally {
if(cursor!= null){
cursor.close();
}
}
}

希望这有助于: / p>

I am trying to copy Image i receive from Intent to another directory. But I am unable to get it working yet. Need Help.

My Logcat:

04-29 14:56:22.778 31620-31620/com.example.krupal.sqlitetest I/Choreographer: Skipped 42 frames!  The application may be doing too much work on its main thread.
04-29 14:56:24.944 31620-31633/com.example.krupal.sqlitetest W/EGL_emulation: eglSurfaceAttrib not implemented
04-29 14:56:24.944 31620-31633/com.example.krupal.sqlitetest W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0x7f5170636740, error=EGL_SUCCESS
04-29 14:56:26.370 31620-31633/com.example.krupal.sqlitetest E/Surface: getSlotFromBufferLocked: unknown buffer: 0x7f517631a550
04-29 14:56:26.381 31620-31620/com.example.krupal.sqlitetest W/InputEventReceiver: Attempted to finish an input event but the input event receiver has already been disposed.
04-29 14:56:26.381 31620-31620/com.example.krupal.sqlitetest W/ViewRootImpl: Dropping event due to root view being removed: MotionEvent { action=ACTION_HOVER_ENTER, actionButton=0, id[0]=0, x[0]=322.27295, y[0]=447.5, toolType[0]=TOOL_TYPE_FINGER, buttonState=0, metaState=0, flags=0x0, edgeFlags=0x0, pointerCount=1, historySize=0, eventTime=4168947, downTime=4168760, deviceId=0, source=0x1002 }
04-29 14:56:26.381 31620-31620/com.example.krupal.sqlitetest W/InputEventReceiver: Attempted to finish an input event but the input event receiver has already been disposed.
04-29 14:56:26.381 31620-31620/com.example.krupal.sqlitetest W/ViewRootImpl: Dropping event due to root view being removed: MotionEvent { action=ACTION_HOVER_ENTER, actionButton=0, id[0]=0, x[0]=322.27295, y[0]=447.5, toolType[0]=TOOL_TYPE_FINGER, buttonState=0, metaState=0, flags=0x0, edgeFlags=0x0, pointerCount=1, historySize=0, eventTime=4168947, downTime=4168760, deviceId=0, source=0x1002 }
04-29 14:56:26.381 31620-31620/com.example.krupal.sqlitetest W/InputEventReceiver: Attempted to finish an input event but the input event receiver has already been disposed.
04-29 14:56:26.381 31620-31620/com.example.krupal.sqlitetest W/ViewRootImpl: Dropping event due to root view being removed: MotionEvent { action=ACTION_HOVER_MOVE, actionButton=0, id[0]=0, x[0]=322.27295, y[0]=447.5, toolType[0]=TOOL_TYPE_FINGER, buttonState=0, metaState=0, flags=0x0, edgeFlags=0x0, pointerCount=1, historySize=0, eventTime=4168947, downTime=4168760, deviceId=0, source=0x1002 }
04-29 14:56:26.381 31620-31620/com.example.krupal.sqlitetest W/InputEventReceiver: Attempted to finish an input event but the input event receiver has already been disposed.
04-29 14:56:27.652 31620-31633/com.example.krupal.sqlitetest E/Surface: getSlotFromBufferLocked: unknown buffer: 0x7f517631a710
04-29 14:56:29.935 31620-31630/com.example.krupal.sqlitetest I/art: Background sticky concurrent mark sweep GC freed 7247(862KB) AllocSpace objects, 0(0B) LOS objects, 0% free, 10MB/10MB, paused 10.778ms total 53.218ms
04-29 14:56:30.051 31620-31620/com.example.krupal.sqlitetest D/BuildVersion: Build version >=19
04-29 14:56:30.070 31620-31620/com.example.krupal.sqlitetest D/AndroidRuntime: Shutting down VM


                                                                           --------- beginning of crash
04-29 14:56:30.071 31620-31620/com.example.krupal.sqlitetest E/AndroidRuntime: FATAL EXCEPTION: main
                                                                           Process: com.example.krupal.sqlitetest, PID: 31620
                                                                           ** java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=-1, data=Intent { dat=content://com.android.externalstorage.documents/document/primary:Download/2015-09-09.jpg flg=0x1 }} to activity {com.example.krupal.sqlitetest/com.example.krupal.sqlitetest.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'char[] java.lang.String.toCharArray()' on a null object reference **
                                                                               at android.app.ActivityThread.deliverResults(ActivityThread.java:3699)
                                                                               at android.app.ActivityThread.handleSendResult(ActivityThread.java:3742)
                                                                               at android.app.ActivityThread.-wrap16(ActivityThread.java)
                                                                               at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1393)
                                                                               at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                               at android.os.Looper.loop(Looper.java:148)
                                                                               at android.app.ActivityThread.main(ActivityThread.java:5417)
                                                                               at java.lang.reflect.Method.invoke(Native Method)
                                                                               at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                                                                               at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
                                                                            Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'char[] java.lang.String.toCharArray()' on a null object reference
                                                                               at java.io.File.fixSlashes(File.java:183)
                                                                               at java.io.File.<init>(File.java:130)
                                                                               at com.example.krupal.sqlitetest.MainActivity.onActivityResult(MainActivity.java:160)
                                                                               at android.app.Activity.dispatchActivityResult(Activity.java:6428)
                                                                               at android.app.ActivityThread.deliverResults(ActivityThread.java:3695)
                                                                               at android.app.ActivityThread.handleSendResult(ActivityThread.java:3742) 
                                                                               at android.app.ActivityThread.-wrap16(ActivityThread.java) 
                                                                               at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1393) 
                                                                               at android.os.Handler.dispatchMessage(Handler.java:102) 
                                                                               at android.os.Looper.loop(Looper.java:148) 
                                                                               at android.app.ActivityThread.main(ActivityThread.java:5417) 
                                                                               at java.lang.reflect.Method.invoke(Native Method) 
                                                                               at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
                                                                               at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 
04-29 14:56:32.316 31620-31620/com.example.krupal.sqlitetest I/Process: Sending signal. PID: 31620 SIG: 9

Source:

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == Activity.RESULT_OK) {
        switch (requestCode) {
            case SELECT_PICTURE: {
                Uri selectedImageURI = data.getData();
                if (Build.VERSION.SDK_INT < 19) {
                    String selectedImagePath = getPath(selectedImageURI);
                    Bitmap bitmap = BitmapFactory.decodeFile(selectedImagePath);
                    avatar.setImageBitmap(bitmap);
                    copyImageToInternalStorage(new File(getPath(selectedImageURI)));
                    Log.d("BuildVersion","Build version <19");

                } else {
                    ParcelFileDescriptor parcelFileDescriptor;
                    try {
                        parcelFileDescriptor = getContentResolver().openFileDescriptor(selectedImageURI, "r");
                        FileDescriptor fileDescriptor = null;
                        if (parcelFileDescriptor != null) {
                            fileDescriptor = parcelFileDescriptor.getFileDescriptor();
                        }
                        Bitmap image = BitmapFactory.decodeFileDescriptor(fileDescriptor);
                        avatar.setImageBitmap(image);
                        Log.d("BuildVersion","Build version >=19");
                        copyImageToInternalStorage(new File(getPath(selectedImageURI)));

                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }
                }
                break;
            }
            (everything else)
}

Copy Method:

    private void copyImageToInternalStorage(File sourcefile) {
    String timeStamp = new SimpleDateFormat("ddMMyyyy_HHmmss").format(new Date());
    File folder = getExternalFilesDir("ImageDatabase");
    File file = new File(folder, "IMG_"+timeStamp+".jpg");

    if(!sourcefile.exists()){
        return;
    }
    FileChannel source = null;
    FileChannel dest = null;

    try {
        source = new FileInputStream(sourcefile).getChannel();
        dest = new FileOutputStream(file).getChannel();
        if(source != null && dest != null){
            dest.transferFrom(source,0,source.size());
        }
        if(source != null){
            source.close();
        }
        if(dest != null){
            dest.close();
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

GetPath Method:

public String getPath(Uri uri) {
    String[] projection = {MediaStore.Images.Media.DATA};

    //  Cursor cursor=managedQuery(uri, projection, null, null, null);
    @SuppressWarnings("deprecation")
    Cursor cursor = managedQuery(uri, projection, null, null, null);
    int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
    cursor.moveToFirst();
    return cursor.getString(column_index);
}

But this is giving me NullPointerException. What needs to be changed?

解决方案

This is a working code which i Have used to copy the file after clicking an image. You have to create a directory structure for it before.

 @Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == RESULT_OK) {

        switch (requestCode) {
            case CLICK_PHOTO:
                imageUri = data.getData();
                path = Utils.getRealPathFromURI(Photos.this, imageUri);
                picturePath = path.toString();

                fileName = picturePath.substring(picturePath.lastIndexOf("/") + 1);


                mFile = new File(Utils.getPath(getDIR), fileName);

                try {
                    copyFile(new File(picturePath), mFile);
                } catch (IOException e) {
                    e.printStackTrace();
                }

                saveBitmapToFile(mFile);

                PhotoBeans bean = new PhotoBeans();
                bean.setThumbImageUrl(mFile.getAbsolutePath());
                bean.setIsImageSelected(false);

                arrayListPhoto.add(bean);
                adapter.notifyDataSetChanged(); //  This will try to load your new Image

                gvImages.invalidateViews(); // then you are refreshing views and setting the adapter again below

                gvImages.setAdapter(adapter);
                //Initialize Adapter

                break;

            case SELECT_PHOTO:
                imageUri = data.getData();
                path = Utils.getRealPathFromURI(Photos.this, imageUri);
                picturePath = path.toString();

                fileName = picturePath.substring(picturePath.lastIndexOf("/") + 1);

                mFile = new File(Utils.getPath(getDIR), fileName);

                try {
                    copyFile(new File(picturePath), mFile);
                } catch (IOException e) {
                    e.printStackTrace();
                }

                saveBitmapToFile(mFile);

                PhotoBeans beans = new PhotoBeans();
                beans.setThumbImageUrl(mFile.getAbsolutePath());
                beans.setIsImageSelected(false);

                arrayListPhoto.add(beans);
                adapter.notifyDataSetChanged(); //  This will try to load your new Image

                gvImages.invalidateViews(); // then you are refreshing views and setting the adapter again below

                gvImages.setAdapter(adapter);
                //Initialize Adapter
                break;

        }
    }
}

CopyFile()

 private void copyFile(File sourceFile, File destFile) throws IOException {
    //Creates a copy of the existing file
    if (!sourceFile.exists()) {
        return;
    }

    FileChannel source = null;
    FileChannel destination = null;
    source = new FileInputStream(sourceFile).getChannel();
    destination = new FileOutputStream(destFile).getChannel();
    if (destination != null && source != null) {
        destination.transferFrom(source, 0, source.size());
    }
    if (source != null) {
        source.close();
    }
    if (destination != null) {
        destination.close();
    }
}

Directory Structure

   private void createDirectoryStructure() {
    try {
        createDirectory(Environment.getExternalStorageDirectory() + "", "YourDirecrtoryName");
        createDirectory(Environment.getExternalStorageDirectory() + "/" + "YourDirecrtoryName", "FolderInsideDirectory");
    } catch (Exception e) {
        e.printStackTrace();
    }
}

private void createDirectory(String filePath, String directoryName) {
    try {
        File mfile= new File(filePath, directoryName);
        if (!mfile.exists()) {
            mfile.mkdirs();
            Log.e("In error", "createDirectory");
        } else {
            Log.e("In nottt error", "createDirectory");
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

Utils.getPath()

  public static String getPath(String getDIR) {
    String path = "";
    if (Environment.getExternalStorageState().equals(
            Environment.MEDIA_MOUNTED)) {
        path = Environment.getExternalStorageDirectory().getAbsolutePath();
    }
    if(getDIR.equalsIgnoreCase("images")) {
        return path + "/YourDirectoryName/YourDirectoryName Images";
    }else if(getDIR.equalsIgnoreCase("videos")){
        return path + "/YourDirectoryName/YourDirectoryName Videos";
    }else {
        return path + "/YourDirectoryName/YourDirectoryName Documents";
    }
}

To get the path of the image from Uri.

   public static String getRealPathFromURI(Context context, Uri contentUri) {
    Cursor cursor = null;
    try {
        String[] proj = {MediaStore.Images.Media.DATA};
        cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
        Log.e("Cursor", "" + cursor);
        if (cursor != null) {
            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            cursor.moveToFirst();
            return cursor.getString(column_index);
        }
        else {
            return null;
        }

    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }
}

Hope this Helps :)

这篇关于将图像从FilePicker / Intent复制到另一个目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-30 22:52