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:
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 :)