无法解析自定义路径目录以保存捕获的图像

时间:2018-04-14 10:19:00

标签: java android android-studio local-storage

我有下面的代码来选择打开对话框的目录,其中包含选择自定义目录路径的选项

   DirectoryChooserDialog directoryChooserDialog =
                new DirectoryChooserDialog(MainActivity.this,
                        new DirectoryChooserDialog.ChosenDirectoryListener()
                        {
                            @Override
                            public void onChosenDir(String chosenDir)
                            {
                                m_chosenDir = chosenDir;
                                Toast.makeText(
                                        MainActivity.this, "Chosen directory: " +
                                                chosenDir, Toast.LENGTH_LONG).show();


                            }
                        });
        // Toggle new folder button enabling
        directoryChooserDialog.setNewFolderEnabled(m_newFolderEnabled);
        // Load directory chooser dialog for initial 'm_chosenDir' directory.
        // The registered callback will be called upon final directory selection.
        directoryChooserDialog.chooseDirectory(m_chosenDir);
        m_newFolderEnabled = ! m_newFolderEnabled;

及以下是将文件保存在外部存储器中的代码

 public void takePicture(View view) {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        file = Uri.fromFile(getOutputMediaFile());
        intent.putExtra(MediaStore.EXTRA_OUTPUT, file);

        startActivityForResult(intent, 100);
    }

    private static File getOutputMediaFile() {
        File mediaStorageDir  = new File(m_chosenDir);

        if (!mediaStorageDir.exists()) {
            if (!mediaStorageDir.mkdirs()) {
                Log.d("CameraDemo", "failed to create directory");
                return null;
            }
        }

        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        return new File(mediaStorageDir.getPath() + File.separator +
                "IMG_" + timeStamp + ".jpg");
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 100) {
            if (resultCode == RESULT_OK) {
                imageView.setImageURI(file);
            }
        }

但它突出了

中的错误
File mediaStorageDir = new File(m_chosenDir);

以下是图像文件, Error Image

我该如何解决这个问题?在哪一步我做错了...请好好建议。

提前致谢。

1 个答案:

答案 0 :(得分:0)

请尝试以下代码:

1)MainActivity.class:----------------

public class MainActivity extends AppCompatActivity {

private Button b;
private ImageView iv;

private final int PICTURE_ACTIVITY_CODE = 1;
private File captured_image_file;
private boolean flag = false;
private boolean flag_1 = false;
private String file_name = "myphoto";
private String file_extension = "png";



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

    iv = (ImageView) findViewById(R.id.iv);

    b = (Button) findViewById(R.id.b);

    b.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            createDirectoryChooserDialog();
        }
    });

}

private void createDirectoryChooserDialog() {

    File mPath = new File(Environment.getExternalStorageDirectory() + "//DIR//");
    FileDialog fileDialog = new FileDialog(this, mPath, "." + "png");

    fileDialog.addDirectoryListener(new FileDialog.DirectorySelectedListener() {
        public void directorySelected(File directory) {
            Log.e(getClass().getName(), "*********selected dir " + directory.toString());

            if (!directory.toString().isEmpty()) {
                if (directory.exists()) {

                    captured_image_file = new File(directory.getAbsolutePath() + "/" + file_name + "." + file_extension);

                    flag = true;

                } else {

                    flag = false; // directory doesn't exits.
                }
            }

            if (flag) {
                if (!captured_image_file.exists()) { // file doesn't exist
                    Log.e("File doesn't exists", "Creating File");
                    try {
                        flag_1 = captured_image_file.createNewFile();
                    } catch (IOException e) {
                        e.printStackTrace();
                        flag_1 = false;
                    }
                } else {
                    flag_1 = true; // file will be over-written
                }
                if (flag_1) {
                    Log.e("Creation", "Succeeded");
                    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    Uri outputFileUri = Uri.fromFile(captured_image_file);
                    intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
                    startActivityForResult(intent, PICTURE_ACTIVITY_CODE);
                }
            }
        }
    });
    fileDialog.setSelectDirectoryOption(true);
    fileDialog.showDialog();

}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == PICTURE_ACTIVITY_CODE) {
        if (resultCode == RESULT_OK) {
            Uri inputFileUri = Uri.fromFile(captured_image_file);
            Bitmap image = BitmapFactory.decodeFile(inputFileUri.getPath());
            iv.setImageBitmap(image);
        } else {
            // handle partially created file
        }
    }
}

}

2)FileDialog.class:------------

public class FileDialog {
    private static final String PARENT_DIR = "..";
    private final String TAG = getClass().getName();
    private String[] fileList;
    private File currentPath;
    public interface FileSelectedListener {
        void fileSelected(File file);
    }
    public interface DirectorySelectedListener {
        void directorySelected(File directory);
    }
    private ListenerList<FileSelectedListener> fileListenerList = new ListenerList<FileSelectedListener>();
    private ListenerList<DirectorySelectedListener> dirListenerList = new ListenerList<DirectorySelectedListener>();
    private final Activity activity;
    private boolean selectDirectoryOption;
    private String fileEndsWith;

    /**
     * @param activity
     * @param initialPath
     */
    public FileDialog(Activity activity, File initialPath) {
        this(activity, initialPath, null);
    }

    public FileDialog(Activity activity, File initialPath, String fileEndsWith) {
        this.activity = activity;
        setFileEndsWith(fileEndsWith);
        if (!initialPath.exists()) initialPath = Environment.getExternalStorageDirectory();
        loadFileList(initialPath);
    }

    /**
     * @return file dialog
     */
    public Dialog createFileDialog() {
        Dialog dialog = null;
        AlertDialog.Builder builder = new AlertDialog.Builder(activity , android.R.style.Theme_Translucent_NoTitleBar);
        //dialog.setContentView(R.layout.loading_screen);

        builder.setTitle(currentPath.getPath());
        if (selectDirectoryOption) {
            builder.setPositiveButton("Select directory", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    Log.e("pathname", currentPath.getPath());
                    fireDirectorySelectedEvent(currentPath);
                }
            });
        }

        builder.setItems(fileList, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                String fileChosen = fileList[which];
                File chosenFile = getChosenFile(fileChosen);
                if (chosenFile.isDirectory()) {
                    loadFileList(chosenFile);
                    dialog.cancel();
                    dialog.dismiss();
                    showDialog();
                } else fireFileSelectedEvent(chosenFile);
            }
        });

        dialog = builder.show();
        return dialog;
    }


    public void addFileListener(FileSelectedListener listener) {
        fileListenerList.add(listener);
    }

    public void removeFileListener(FileSelectedListener listener) {
        fileListenerList.remove(listener);
    }

    public void setSelectDirectoryOption(boolean selectDirectoryOption) {
        this.selectDirectoryOption = selectDirectoryOption;
    }

    public void addDirectoryListener(DirectorySelectedListener listener) {
        dirListenerList.add(listener);
    }

    public void removeDirectoryListener(DirectorySelectedListener listener) {
        dirListenerList.remove(listener);
    }

    /**
     * Show file dialog
     */
    public void showDialog() {
        createFileDialog().show();
    }

    private void fireFileSelectedEvent(final File file) {
        fileListenerList.fireEvent(new ListenerList.FireHandler<FileSelectedListener>() {
            public void fireEvent(FileSelectedListener listener) {
                listener.fileSelected(file);
            }
        });
    }

    private void fireDirectorySelectedEvent(final File directory) {
        dirListenerList.fireEvent(new ListenerList.FireHandler<DirectorySelectedListener>() {
            public void fireEvent(DirectorySelectedListener listener) {
                listener.directorySelected(directory);
            }
        });
    }

    private void loadFileList(File path) {
        this.currentPath = path;
        List<String> r = new ArrayList<String>();
        if (path.exists()) {
            if (path.getParentFile() != null) r.add(PARENT_DIR);
            FilenameFilter filter = new FilenameFilter() {
                public boolean accept(File dir, String filename) {
                    File sel = new File(dir, filename);
                    if (!sel.canRead()) return false;
                    if (selectDirectoryOption) return sel.isDirectory();
                    else {
                        boolean endsWith = fileEndsWith != null ? filename.toLowerCase().endsWith(fileEndsWith) : true;
                        return endsWith || sel.isDirectory();
                    }
                }
            };
            String[] fileList1 = path.list(filter);
            if (fileList1 == null) {

            } else {
                for (String file : fileList1) {
                    r.add(file);
                }
            }
        }
        fileList = (String[]) r.toArray(new String[]{});
    }

    private File getChosenFile(String fileChosen) {
        if (fileChosen.equals(PARENT_DIR)) return currentPath.getParentFile();
        else return new File(currentPath, fileChosen);
    }

    private void setFileEndsWith(String fileEndsWith) {
        this.fileEndsWith = fileEndsWith != null ? fileEndsWith.toLowerCase() : fileEndsWith;
    }
    }

3)ListenerList接口:------------

class ListenerList<L> {

private List<L> listenerList = new ArrayList<L>();

public interface FireHandler<L> {
    void fireEvent(L listener);
}

public void add(L listener) {
    listenerList.add(listener);
}

public void fireEvent(FireHandler<L> fireHandler) {
    List<L> copy = new ArrayList<L>(listenerList);
    for (L l : copy) {
        fireHandler.fireEvent(l);
    }
}

public void remove(L listener) {
    listenerList.remove(listener);
}

public List<L> getListenerList() {
    return listenerList;
}
}

4)activity_main.xml:----------

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:gravity="center">

    <ImageView
        android:layout_width="200dp"
        android:layout_height="200dp"
        tools:ignore="contentDescription"
        android:id="@+id/iv"/>

    <Button
        android:layout_width="200dp"
        android:layout_height="50dp"
        android:text="Take Pic"
        android:id="@+id/b"/>

    </LinearLayout>

5)注意:FileDialog类和ListenerList接口来自:Choose File Dialog