'How to read a file from internal storage or external storage and store the file in a arrayList in android

My requirement is the end-user must be able to upload files into the application from internal or external storage and finally display the name of the file in the page.

Actual result: Now I've fetched the file name from the storage and displayed the name in my page.

Expected Result: The end user must be able to load image or video files from external or internal storage to the application and finally display their name in the page.

But don't have any idea about how to load read the file from storage and store it in a arrayList.

Code for fetching the file name

public class ServiceDetails extends AppCompatActivity {
    
    private Button next, attachment_one;
    private ImageButton attach_file;

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

        next = findViewById(R.id.submit);
        attachment_one = findViewById(R.id.attachmentOne);
        attach_file = findViewById(R.id.attachFile);

        next.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(ServiceDetails.this, ServiceAddress.class);
                startActivity(intent);
            }
        });

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

                if(Build.VERSION.SDK_INT > Build.VERSION_CODES.M &&
                        checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                    requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 10001);
                }
                new MaterialFilePicker()
                        .withActivity(ServiceDetails.this)
                        .withRequestCode(1)
                        .withFilter(Pattern.compile(".*\\.(mkv|wmv|avi|mpeg|swf|mov|mp4|jpg|jpeg)$"))
                        .withHiddenFiles(true) // Show hidden files and folders
                        .start();
            }
        });

        attachment_one.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                attachment_one.setVisibility(View.INVISIBLE);
            }
        });

    }

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

        if (requestCode == 1 && resultCode == RESULT_OK) {
            String file_path = data.getStringExtra(FilePickerActivity.RESULT_FILE_PATH);
            String file_array[] = file_path.split("/");
            String file_name = file_array[file_array.length - 1];
            // Do anything with file

            if(attachment_one.getText().toString().isEmpty()) {
                attachment_one.setVisibility(View.VISIBLE);
                attachment_one.setText(file_name);
            } 
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case 10001: {
                if(grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    Toast.makeText(ServiceDetails.this, "Permission granted", Toast.LENGTH_LONG).show();
                }else {
                    Toast.makeText(ServiceDetails.this, "Permission not granted", Toast.LENGTH_LONG).show();
                    finish();
                }
            }
        }
    }
}

I'm new to android and kindly help me providing solution for this answer. Million thanks in advance!

Image showing file attachment optionenter image description here



Solution 1:[1]

As you are willing to load the title of video/images, and other file related information from the External Storage. You have to use this code and also make sure don't forget to create a Arraylist with model(required to extract information and find to the listview).

        //ContentResolver and contentProvider as well as cursor
        String[] projection = new String[]{
                MediaStore.Video.Media._ID,
                MediaStore.Video.Media.TITLE,
                MediaStore.Video.Media.SIZE,
                MediaStore.Video.Media.DATE_MODIFIED
        };
        String selection = null;
        String[] selectionargs = null;
        String orderBy = MediaStore.Video.Media.DISPLAY_NAME + " Desc";
        Uri content_uri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
        Cursor cursor = getContentResolver().query(content_uri, projection, selection, selectionargs, orderBy);
        if (cursor != null) {
            cursor.moveToPosition(0);
        }
        while (true) {
            long id = cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Video.Media._ID));
            Uri VideoUri = ContentUris.withAppendedId(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, id);
            Log.d("uri", "onCreate: video path " + VideoUri);
            String title = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.TITLE));
            float size = cursor.getFloat(cursor.getColumnIndexOrThrow(MediaStore.Video.Media.SIZE));
//          loading  a thumbnail from the content resolver
            // Load thumbnail of a specific media item.
            Bitmap thumbnail = null;
            try {
                thumbnail = getApplicationContext().getContentResolver().loadThumbnail(VideoUri, new Size(200, 200), null);
                Log.d("thumbnail", "onCreate: Lodaing a thumbnail");
            } catch (IOException e) {
                Log.d("thumbnail", "onCreate: Showing Error on thumbnail");
                e.printStackTrace();
            }
            videolist.add(new Video(thumbnail, VideoUri, title, size));
            if (!cursor.isLast()) {
                cursor.moveToNext();
            } else {
                Log.d("lastItem", "onCreate: last uri is encountered");
                break;
            }
        }
        cursor.close();

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Jitendra Kohar