簡體   English   中英

如何訪問Android Studio中的特定文件夾?

[英]How to access to the specific Folder in Android Studio?

我需要根據創建的項目的名稱訪問特定的文件夾。 在 Main_Activity 中填寫該項目的名稱並創建新文件夾。 因此,Camera_Activity 將拍攝的照片保存在該文件夾中。 接下來我訪問 Gallery_Activity,但它永遠不會轉到創建的項目的文件夾。 我怎樣才能訪問那個文件夾?

舉個例子:創建的文件夾名稱:Proj_1,但是用戶select默認打開的是另外一個的照片,出來的uri是:content://com.android.externalstorage.documents/document/primary%3APictures%2FCaptures_Camera2 %2F Proj_aa %2Fpic_040621_110254.jpeg

AndroidManifest.xml 的一部分

...
<uses-feature android:name="android.hardware.camera2.full" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.CAMERA" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
    <uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
...

MainActivity.java

...
createNewProject.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // Coge el nombre de EditText, crea nueva carpeta y empieza la captura de las imagenes
                if(newName.getText().toString().isEmpty()){
                    Toast.makeText(getApplicationContext(), "Please, fill in the field.", Toast.LENGTH_LONG).show();
                } else {
                    name = newName.getText().toString();
                    GlobalVariables.ProjectName = name;
                    Intent intent = new Intent(MainActivity.this, Camera_Activity.class);
                    startActivity(intent);
                }
            }
        });
...

Camera_Activity.java 拍攝必要的照片,保存它們並有一個按鈕進入畫廊:

...

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

        mTextureView = findViewById(R.id.camera_preview);
        btn_take_pic = findViewById(R.id.button_take_photo);
        acceptButton = findViewById(R.id.btn_ok);
        cancelButton = findViewById(R.id.btn_cancel);
        btn_gallery = findViewById(R.id.go_to_gallery);
        imagePreview = findViewById(R.id.image_view_photo_preview);

        ...

        // File name to save the picture
        // First is getting the new project name from previous Activity:
        String newProjName = GlobalVariables.ProjectName;
        // Creating part of the name for image: timestamp. That will be: pic_tamestamp.jpeg
        @SuppressLint("SimpleDateFormat") String timestamp = new SimpleDateFormat("ddMMyy_HHmmss").format(new Date());
        directory = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "Captures_Camera2/Proj_" + newProjName);

        GlobalVariables.MyDirectoryPath = directory.getPath();

        if (!directory.exists() || !directory.isDirectory())
            directory.mkdirs();

        mFile = new File(directory, "pic_" + timestamp + ".jpeg");
        pathToFile = mFile.getPath();

        ....

        // ------------ GO TO GALLERY ---------
        btn_gallery.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.d(TAG, "You are going to Gallery...");
                Intent GalleryIntent = new Intent(context, Gallery_Activity.class);
                startActivity(GalleryIntent);
            }
        });

        // ------------ SAVE PHOTO TO THE GALLERY ---------
        acceptButton.setOnClickListener(new View.OnClickListener() {//26
            @Override
            public void onClick(View v) {
                Toast.makeText(context, "Image saved to " + pathToFile, Toast.LENGTH_LONG).show();
                // Recreating the activity with a new instance
                recreate();
            }
        });
        
        ...

圖庫_活動.java

public class Gallery_Activity extends AppCompatActivity implements View.OnClickListener, View.OnLongClickListener {

    private static final String TAG = "GalleryActivity";
    private final Context context = this;

    private ImageView imageView1, imageView2;

    private final int CODE_IMAGE_GALLERY_FIRST = 1;
    private final int CODE_IMAGE_GALLERY_SECOND = 2;
    private final int CODE_MULTIPLE_IMAGES_GALLERY = 3;
    // Variables to check the name
    private String directoryPath;
    private String MyPath1 = null;
    private String MyPath2 = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Keeping the screen on even when there is no touch interaction
        final Window window = getWindow();
        window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

        setContentView(R.layout.activity_gallery);


        imageView1 = findViewById(R.id.imageView1);
        // If you make a short click in the ImageView, you can choose only one image, if it is long click, you can choose two images
        imageView1.setOnClickListener(this);
        imageView1.setOnLongClickListener(this);
        imageView2 = findViewById(R.id.imageView2);
        imageView2.setOnClickListener(this);
        imageView2.setOnLongClickListener(this);

        directoryPath = GlobalVariables.MyDirectoryPath;
        Log.d(TAG, " The path from Camera_Activity is: " + directoryPath); // /storage/emulated/0/Pictures/Captures_Camera2/Proj_*

        chooseMultipleImages();
    }

    private void chooseMultipleImages() {
        // TODO: here it does NOT enter the giving folder although using the path
        startActivityForResult(Intent.createChooser(new Intent()
                        .putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true)
                        .setAction(Intent.ACTION_GET_CONTENT)
                        .setType("image/*")
                ,"Selecting two images.."), CODE_MULTIPLE_IMAGES_GALLERY);
    }

    ....

   
    public void processImages(View view) {
        //Toast.makeText(context, "Going to detect features...", Toast.LENGTH_SHORT).show();
        Intent processIntent = new Intent(context, ImageProcessing.class);
        startActivity(processIntent);
        finish();
    }

    @Override
    public boolean onLongClick(View v) {
        recreate();
        return false;
    }
    @Override
    public void onClick(View v) {
        if(v.getId() == R.id.imageView1){
            startActivityForResult(Intent.createChooser(new Intent()
                            .putExtra(Intent.EXTRA_ALLOW_MULTIPLE, false)
                            .setAction(Intent.ACTION_GET_CONTENT)
                            .setType("image/*")
                    ,"Selecting first image.."), CODE_IMAGE_GALLERY_FIRST);
        }
        else if(v.getId() == R.id.imageView2){
            startActivityForResult(Intent.createChooser(new Intent()
                            .putExtra(Intent.EXTRA_ALLOW_MULTIPLE, false)
                            .setAction(Intent.ACTION_GET_CONTENT)
                            .setType("image/*")
                    ,"Selecting second image.."), CODE_IMAGE_GALLERY_SECOND);
        }
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        ContentResolver resolver = this.getContentResolver();

        // Get data from the folder
        assert data != null;
        Uri MyData = data.getData(); // for simple image
        ClipData MultiImg = data.getClipData(); // for multiple images
        GlobalVariables.countImg = MultiImg.getItemCount();
        /*     ******************************************
                  To pick multiples images from Gallery
               ******************************************
        */
        if (requestCode == CODE_MULTIPLE_IMAGES_GALLERY && resultCode == RESULT_OK ){
            /*
            // TODO: For multiple images, more than 2 change this
            int count = data.getClipData().getItemCount(); //evaluate the count before the for loop --- otherwise, the count is evaluated every loop.
            for(int i = 0; i < count; i++)
                Uri imageUri = data.getClipData().getItemAt(i).getUri();*/

            // MultiImg != null was simplifyed since you cannot continue without any selection -> data never be null
            if(GlobalVariables.countImg == 2){
                // Getting name of the picture and print it
                MyPath1 = MultiImg.getItemAt(0).getUri().toString();
                MyPath2 = MultiImg.getItemAt(1).getUri().toString();
                String Name1 = StringUtils.right(MyPath1,22);
                String Name2 = StringUtils.right(MyPath2,22);
                //String Proj_name = StringUtils.
                GlobalVariables.PictureName1 = Name1;
                GlobalVariables.PictureName2 = Name2;
                Log.d(TAG, "--- First data name: " + StringUtils.right(MyPath1,22));
                Log.d(TAG, "--- Second data name: " + StringUtils.right(MyPath2,22));
                //Log.d(TAG, "Selected Items: " + clipData.getItemCount());
                Log.d(TAG, "The full path is: " + MultiImg.getItemAt(0).getUri().toString());
                // Showing images in the imageView
                imageView1.setImageURI(MultiImg.getItemAt(0).getUri());
                imageView2.setImageURI(MultiImg.getItemAt(1).getUri());


            } else if (MyData != null ){
                Log.d(TAG, "Only one image selected..");
                Toast.makeText(context, "You should select 2 images and not only one", Toast.LENGTH_LONG).show();
                recreate();
            }
            // MultiImg != null was simplifyed since you cannot continue without any selection -> data never be null
            else if (GlobalVariables.countImg > 2){
                //Log.d(TAG, "More than two selected images...");
                Toast.makeText(context, "You should select 2 images and not ..." + GlobalVariables.countImg, Toast.LENGTH_LONG).show();
                recreate();
            }
        }
        /*     ******************************************
                  To pick only one image fom Gallery for
                  each of ImageView and check that they
                  are different.
               ******************************************
        */
        // pick image to the imageView1
        else if(requestCode == CODE_IMAGE_GALLERY_FIRST && resultCode == RESULT_OK && MyData != null){
            MyPath1 = MyData.getPath();
            //Log.d(TAG, "\n ******** imageView1 has an image: \n" + StringUtils.right(MyPaths1,22) + "\n imageView2 has an image: \n" + StringUtils.right(MyPaths2,22));
            assert StringUtils.right(MyPath1, 22) != null;
            if(StringUtils.right(MyPath1,22).equals(StringUtils.right(MyPath2,22))){
                Toast.makeText(context, "The images have to be different. Choose other image." , Toast.LENGTH_LONG).show();
            }
            else{
                GlobalVariables.PictureName1 = StringUtils.right(MyPath1,22);
                imageView1.setImageURI(MyData);
            }
        }
        // pick image to the imageView2
        else if(requestCode == CODE_IMAGE_GALLERY_SECOND && resultCode == RESULT_OK && MyData != null) {
            MyPath2 = MyData.getPath();
            //Log.d(TAG, "\n ******** imageView1 has an image: \n" + StringUtils.right(MyPaths1,22) + "\n imageView1 has an image: \n" + StringUtils.right(MyPaths2,22));
            if(StringUtils.right(MyPath1,22).equals(StringUtils.right(MyPath2,22))){
                Toast.makeText(context, "The images have to be different. Choose other image." , Toast.LENGTH_LONG).show();
            }
            else{
                GlobalVariables.PictureName2 = StringUtils.right(MyPath2,22);
                imageView2.setImageURI(MyData);
            }
        }
    }

    ....

}

有人可以告訴我如何解決這個問題嗎? 很明顯,我可以保持原樣並告訴用戶檢查他選擇照片的文件夾。 但我希望它更流暢、更直觀。 提前致謝。

private ArrayList<File> m_list = new ArrayList<File>();

  String folderpath = Environment.getExternalStorageDirectory()
        + File.separator + "folder_name/";
     File dir = new File(folderpath);
     m_list.clear();
        if (dir.isDirectory()) {
            File[] files = dir.listFiles();
            for (File file : files) {
                if (!file.getPath().contains("Not_Found"))
                    m_list.add(file);
            }
         }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM