【问题标题】:Cannot resolve the custom path directory to save the captured Images无法解析自定义路径目录以保存捕获的图像
【发布时间】:2018-09-24 14:26:58
【问题描述】:

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

   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

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

提前致谢。

【问题讨论】:

  • 您的代码中在哪里声明了 m_choosenDir?你不应该使用 m_chosedDir 代替 m_choosenDir 吗?
  • @Rabee 有人建议我使用 m_chosenDir 但它没有帮助...但是正如您建议使用 m_chosedDir ....但我没有在代码中的任何地方声明m_chosedDir 但我在第一个声明的代码上有 m_chosenDir ..但这也无济于事。我现在应该做什么或我能做什么?
  • @Rabee 好的,我已经编辑了我的问题,它应该有 m_chosen 而不是 m_choosen。输入错误。
  • 你现在遇到什么错误或者你的问题解决了吗?
  • @Rabee 不,Rabee 它还没有解决,我还在胡思乱想...这是我收到的错误图像文件ibb.co/ejZSbn,这是我的整个主要活动代码drive.google.com/file/d/1DhxQL4A4-I3fzpfLwU7P1DGqcNygOqaw/… 请看...我对此感到非常沮丧。

标签: java android android-studio local-storage


【解决方案1】:

试试下面的代码:

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

【讨论】:

  • 是的 Rabee 这正是我想要的...您能否对代码进行一些更改,例如创建目录的选项,并允许用户在应用程序启动时只选择一次目录,然后会连续拍照(跳过保存和取消页面)直到他按下返回按钮,然后单击按钮并选择另一个目录或创建他自己的目录。然后他又可以连续拍照了。再次感谢..您可以制作一个相同的教程...因为我注意到没有类似的。
  • 我给你一个基本的回答你的问题。您必须自己处理其他任何事情。他们有大量可用资源,可以帮助您在应用程序中添加您喜欢的任何功能。如果在做完研究之后,你仍然卡在某个点上,你可以随时问另一个问题。请接受这个答案。谢谢。
  • 完成...!!感谢您的帮助。
猜你喜欢
  • 2014-09-10
  • 2022-01-03
  • 1970-01-01
  • 1970-01-01
  • 2021-04-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-11
相关资源
最近更新 更多