-3

I have below code to choose the Directory which opens an Dialog box with options to choose custom directory path

   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;

and below is the code to save the file in external storage

 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);
            }
        }

But it highlights error in

File mediaStorageDir = new File(m_chosenDir);

and below is image file, Error Image

How can I solve this? In which step I'm doing wrong...Please kindly suggest.

Thanks in advance.

Raj Lama
  • 23
  • 7
  • Where is m_choosenDir declared in your code? Shouldn't you use m_chosedDir instead of m_choosenDir? – Brainnovo Apr 14 '18 at 10:40
  • @Rabee I was suggested by someone to use m_chosenDir but it didn't help...but as you have suggested to use m_chosedDir....but I haven't declared anywhere in the code the m_chosedDir but instead I have m_chosenDir on first code declared..but it is also not helping either. what should I or what can I do now? – Raj Lama Apr 14 '18 at 10:45
  • @Rabee ok I have edited my quesiton, it should have m_chosen instead of m_choosen. typing error. – Raj Lama Apr 14 '18 at 10:49
  • What error are you getting now or is your problem solved? – Brainnovo Apr 14 '18 at 10:51
  • @Rabee No Rabee it hasn't been solved, I am still banging my head around...Here is the image file of error I'm getting https://ibb.co/ejZSbn and here is my whole mainactivity code https://drive.google.com/file/d/1DhxQL4A4-I3fzpfLwU7P1DGqcNygOqaw/view?usp=sharing Please have a look...I'm totally frustrated over it. – Raj Lama Apr 14 '18 at 10:56
  • Remove the static keyword from method getOutputMediaFile(). – Brainnovo Apr 14 '18 at 11:06
  • @Rabee how do I remove this...I have no idea on this...everything I did was from a tutorial based on youtube. please help me on this. – Raj Lama Apr 14 '18 at 11:21
  • How does one remove a word from a text? – greenapps Apr 14 '18 at 11:34
  • @greenapps, there are plenty of ways I guess...but what am I supposed to do here?? – Raj Lama Apr 14 '18 at 11:36
  • Can you post the code for DirectoryChooserDialog class? – Brainnovo Apr 14 '18 at 12:12
  • `...but what am I supposed to do here??`. That has been told to you: `Remove the static keyword from method getOutputMediaFile().`. – greenapps Apr 14 '18 at 12:20
  • Check my answer below. – Brainnovo Apr 14 '18 at 12:46

1 Answers1

0

Try the following code:

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

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) Note: FileDialog class and ListenerList interface are from : Choose File Dialog

Brainnovo
  • 1,749
  • 2
  • 12
  • 17
  • yes Rabee this is exactly what I want...can you please make few changes in code like option to create directory also and allow users to select directory only once when app starts and then will take pic continuously ( skip the save and cancel page ) untill he press back button and then click on button and select another directory or create of his own. and then again he would be able to take photo continuously. Thanks again..you can make a Tutorial on same...as I notice there is none similar to this. – Raj Lama Apr 14 '18 at 14:00
  • I gave you a basic answer to your question. You must handle anything else on your own. Their are plenty of available resources that can aid you in adding what ever features you like in your app. If after doing your research, you are still stuck at some point, you can always ask another question. Please accept this answer. Thank you. – Brainnovo Apr 14 '18 at 14:40
  • Done...!! Thanks for your help. – Raj Lama Apr 14 '18 at 15:07