Untitled

mail@pastecode.io avatar
unknown
plain_text
2 months ago
2.4 kB
2
Indexable
Never
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;

import androidx.appcompat.app.AppCompatActivity;

public class YourActivity extends AppCompatActivity {

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

        listAllFilesFromExternalLibrary();
    }

    private void listAllFilesFromExternalLibrary() {
        ContentResolver contentResolver = getContentResolver();
        Uri uri = MediaStore.Files.getContentUri("external");

        // Define the columns you want to retrieve
        String[] projection = {
                MediaStore.Files.FileColumns._ID,
                MediaStore.Files.FileColumns.DATA,
                MediaStore.Files.FileColumns.DISPLAY_NAME,
                MediaStore.Files.FileColumns.DATE_MODIFIED
        };

        // Optionally, you can add a selection (WHERE) clause
        String selection = null;
        String[] selectionArgs = null;

        // Sorting order
        String sortOrder = MediaStore.Files.FileColumns.DATE_MODIFIED + " DESC";

        // Query the external media store
        try (Cursor cursor = contentResolver.query(uri, projection, selection, selectionArgs, sortOrder)) {
            if (cursor != null) {
                while (cursor.moveToNext()) {
                    // Retrieve file details
                    long fileId = cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Files.FileColumns._ID));
                    String filePath = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Files.FileColumns.DATA));
                    String displayName = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Files.FileColumns.DISPLAY_NAME));
                    long dateModified = cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Files.FileColumns.DATE_MODIFIED));

                    // You can use these details as needed
                    Log.d("FileDetails", "ID: " + fileId + ", Path: " + filePath + ", Name: " + displayName + ", Modified: " + dateModified);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
Leave a Comment