当前位置: 首页 > 知识库问答 >
问题:

如何访问Android Studio中的特定文件夹?

王锐
2023-03-14

我需要根据创建的项目的名称访问特定的文件夹。在Main_Activity中,填充该项目的名称并创建新文件夹。因此,Camera_Activity将保存在该文件夹中拍摄的照片。接下来我访问Gallery_Activity,但它从未进入创建的项目的文件夹。我怎样才能访问那个文件夹?

例如:创建文件夹的名称:Proj_1,但用户从默认打开的另一个文件夹中选择了照片,显示出来的uri是:content:/com.android.externalstorage.documents/document/primary%3apictures%2fcaptures_camera2%2fproj_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();
            }
        });
        
        ...

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

    ....

}

有人能给我建议我如何解决这个问题吗?很明显,我可以让事情保持原样,并告诉用户检查他选择照片的文件夹。但我希望它是更流畅和直观的东西。提前道谢。

共有1个答案

呼延鹏云
2023-03-14
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);
            }
         }
 类似资料:
  • 我在WEB API中创建了一种身份验证方法,我得到了以下答案: 我使用下面的代码来阅读信息: 如何仅访问阵列中的令牌?如何使用java/android实现这一点?

  • 我试图通过操纵URL来拒绝用户访问文件夹。 我不知道我是否必须拒绝一切,并手动允许个别异常,如果我可以拒绝这一个文件夹,或者是否有一个可以使用的重写函数。 具体示例:我不想通过在URL中键入来查看目录文件。

  • 我正在AndroidStudio中使用java开发一个android应用程序。我有一张图像视图图片,我想把它的图像设置为。保存在可绘制文件夹中的png。我可以试试 但是,需要Drawable,而返回一个整数(图像的ID)。 如何解决此问题?

  • 我有一个zip文件“items.zip”。 在这个zip-File中有不同的类,其中一些对我有用,而另一些则不是。 圆圈类有一个construcor和一个paint方法。 圆圈ButYoucantDrawit。类具有损坏的构造函数。 在启动主程序之前,我想访问项目。zip,检查它们是否可用,然后尽可能地使用有用的。最好的方法是什么? 到目前为止,我已经尝试了9次,但没有一次有意义。我如何才能做到最

  • 我想访问application.properties中提供的值,例如: 我想在Spring Boot应用程序中访问主程序中的userBucket.path

  • 我创建了一个列表视图,在每个项目中我都放置了一个EditText。我需要阅读并添加每个ListView项中的每个文本。我不知道如何引用特定的列表项。如何从第一个或第二个或另一个项目列表的EditText中获取文本?