Android to access Audio files from shared storage using java

Here is full project to get the Audio files from shared storage using java

package tech.softbinarycrunch.realvideoeditor;

import static android.os.Environment.DIRECTORY_DCIM;
import static android.os.Environment.DIRECTORY_DOWNLOADS;
import static android.os.Environment.DIRECTORY_MUSIC;
import static android.os.Environment.MEDIA_MOUNTED_READ_ONLY;

import android.Manifest;
import android.app.Activity;
import android.content.ContentUris;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Build.VERSION;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.provider.OpenableColumns;
import android.view.View;
import android.webkit.MimeTypeMap;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.Toast;

import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AppCompatActivity;
import androidx.navigation.ui.AppBarConfiguration;

import com.karumi.dexter.Dexter;
import com.karumi.dexter.MultiplePermissionsReport;
import com.karumi.dexter.PermissionToken;
import com.karumi.dexter.listener.DexterError;
import com.karumi.dexter.listener.PermissionRequest;
import com.karumi.dexter.listener.PermissionRequestErrorListener;
import com.karumi.dexter.listener.multi.MultiplePermissionsListener;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import tech.softbinarycrunch.realvideoeditor.databinding.ActivityMainBinding;

public class MainActivity extends AppCompatActivity {
    public static final int REQUEST_CODE = 1;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        RelativeLayout rl=new RelativeLayout(getApplicationContext());
        RelativeLayout.LayoutParams rlp=new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT,RelativeLayout.LayoutParams.MATCH_PARENT);
        rl.setLayoutParams(rlp);
        setContentView(rl);
        Button bt=new Button(getApplicationContext());
        bt.setText("Choose video");
        RelativeLayout.LayoutParams rlpbtn=new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,RelativeLayout.LayoutParams.WRAP_CONTENT);
        rlpbtn.addRule(RelativeLayout.CENTER_IN_PARENT);
        bt.setLayoutParams(rlpbtn);
        rl.addView(bt);
        listener(bt);
        requestMultiplePermissions();
    }
    private void  requestMultiplePermissions(){
        Dexter.withActivity(this)
                .withPermissions(

                        Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.READ_EXTERNAL_STORAGE)
                .withListener(new MultiplePermissionsListener() {
                    @Override
                    public void onPermissionsChecked(MultiplePermissionsReport report) {
                        if (report.areAllPermissionsGranted()) {
                            Toast.makeText(getApplicationContext(), "All permissions are granted by user!", Toast.LENGTH_SHORT).show();
                        }
                        if (report.isAnyPermissionPermanentlyDenied()) {

                        }
                    }

                    @Override
                    public void onPermissionRationaleShouldBeShown(List<PermissionRequest> permissions, PermissionToken token) {
                        token.continuePermissionRequest();
                    }
                }).
                withErrorListener(new PermissionRequestErrorListener() {
                    @Override
                    public void onError(DexterError error) {
                        Toast.makeText(getApplicationContext(), "Some Error! ", Toast.LENGTH_SHORT).show();
                    }
                })
                .onSameThread()
                .check();
    }
    private void message(String s){
        new Handler(getApplicationContext().getMainLooper()).post(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(getApplicationContext(),s,Toast.LENGTH_LONG).show();
            }
        });
    }
    private void filepicker(){
        Uri selectedUri = Uri.parse(Environment.getExternalStorageDirectory() +  File.separator +  DIRECTORY_DOWNLOADS + File.separator);
        System.out.println("working"+selectedUri.getPath());
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        //intent.setType("video/* image/*");
        intent.setDataAndType(selectedUri, "video/* image/*");
        if (intent.resolveActivityInfo(getPackageManager(), 0) != null)
        {
            mStartForResult.launch(intent);
        }
        else
        {
            message("Not working");
        }
    }
    ActivityResultLauncher<Intent> mStartForResult = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(),
            new ActivityResultCallback<ActivityResult>() {
                @Override
                public void onActivityResult(ActivityResult result) {
                    if (result.getResultCode() == Activity.RESULT_OK) {
                        Intent intent = result.getData();
                        message("working");
                    }
                }
            });
    private String extension(File file){
        return MimeTypeMap.getFileExtensionFromUrl(file.toString());
    }
    private void musiclist(){


    }

    private void listoffile(){
        audio();
        // videoinfo();
        // image();
        String path = Environment.getExternalStorageDirectory().toString() ;
        File directory = new File(path);
        File[] files = directory.listFiles();
        String ex;
        for (int i = 0; i < files.length; i++)
        {
            File[] files1;

            File dir2=new File(files[i].getAbsolutePath());
            if(dir2.exists()) {
                files1 = dir2.listFiles();
            }
            else{
                continue;
            }
            if(files1==null){
                continue;
            }

            for(int j=0;j<files1.length;j++){
                Uri file = Uri.fromFile(new File(files1[j].getAbsolutePath()));
                ex=extension(files1[j]);
          /*  if(ex.equals("png") || ex.equals("jpg") || ex.equals("jpeg")
                    || ex.equals("gif")){
                System.out.println("file names are"+files1[j].getName());
            }*/
                if(ex.equals("mp4") || ex.equals("MOV") || ex.equals("WMV")
                        || ex.equals("AVI") || ex.equals("MKV") || ex.equals("MPEG-2")
                        || ex.equals("WEBM ") || ex.equals("HTML5")){
                    System.out.println("file names are"+files1[j].getName());
                }
            }
        }
    }
    private void listener(Button bt){
        bt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                listoffile();
            }
        });
    }
    class Video {
        private final Uri uri;
        private final String name;
        private final int duration;
        private final int size;

        public Video(Uri uri, String name, int duration, int size) {
            this.uri = uri;
            this.name = name;
            this.duration = duration;
            this.size = size;
        }
    }
    /* private void videoinfo(){
         List<Video> videoList = new ArrayList<Video>();

         Uri collection;
         if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
             collection = MediaStore.Video.Media.getContentUri(MediaStore.VOLUME_EXTERNAL);
         } else {
             collection = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
         }

         String[] projection = new String[] {
                 MediaStore.Video.Media._ID,
                 MediaStore.Video.Media.DISPLAY_NAME,
                 MediaStore.Video.Media.DURATION,
                 MediaStore.Video.Media.SIZE
         };
         String selection = MediaStore.Video.Media.DURATION +
                 " >= ?";
         String[] selectionArgs = new String[] {
                 String.valueOf(TimeUnit.MILLISECONDS.convert(5, TimeUnit.MINUTES))
 };
         String sortOrder = MediaStore.Video.Media.DISPLAY_NAME + " ASC";

         try (Cursor cursor = getApplicationContext().getContentResolver().query(
                 collection,
                 projection,
                 null,
                 null,
                 sortOrder
         )) {

             int idColumn = cursor.getColumnIndexOrThrow(MediaStore.Video.Media._ID);
             int nameColumn =
                     cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DISPLAY_NAME);
             int durationColumn =
                     cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DURATION);
             int sizeColumn = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.SIZE);

             while (cursor.moveToNext()) {

                 long id = cursor.getLong(idColumn);
                 String name = cursor.getString(nameColumn);
                 int duration = cursor.getInt(durationColumn);
                 int size = cursor.getInt(sizeColumn);

                 Uri contentUri = ContentUris.withAppendedId(
                         MediaStore.Video.Media.EXTERNAL_CONTENT_URI, id);


                 videoList.add(new Video(contentUri, name, duration, size));
             }
             System.out.println("datasize"+videoList.size());
         }
     }*/
    private void video2(){
        Uri collection;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            collection = MediaStore.Video.Media.getContentUri(MediaStore.VOLUME_EXTERNAL);
        } else {
            collection = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
        }
        String[] projection = new String[] {
                MediaStore.Video.Media._ID,
                MediaStore.Video.Media.DISPLAY_NAME,
                MediaStore.Video.Media.DURATION,
                MediaStore.Video.Media.SIZE
        };
        String sortOrder = MediaStore.Video.Media.DISPLAY_NAME + " ASC";;
        try (Cursor cursor = getApplicationContext().getContentResolver().query(
                collection,
                projection,
                null,
                null,
                sortOrder
        )){
            int idColumn = cursor.getColumnIndexOrThrow(MediaStore.Video.Media._ID);
            int nameColumn =
                    cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DISPLAY_NAME);
            int durationColumn =
                    cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DURATION);
            int sizeColumn = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.SIZE);
            while ((cursor.moveToNext())){
                String path = cursor.getString(cursor.getColumnIndex(MediaStore.Video.Media.ARTIST));
                System.out.println("data"+path);
            }
        }
    }
    private void image(){
        Uri collection;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            collection = MediaStore.Images.Media.getContentUri(MediaStore.VOLUME_EXTERNAL);
        } else {
            collection = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
        }
        String[] projection = new String[] {
                MediaStore.Images.Media.DATA,
                MediaStore.Images.Media.DATE_ADDED,
                MediaStore.Images.Media.BUCKET_ID,
                MediaStore.Images.Media.BUCKET_DISPLAY_NAME
        };
        String sortOrder = MediaStore.Images.Media.DISPLAY_NAME + " ASC";
        try (Cursor cursor = getApplicationContext().getContentResolver().query(
                collection,
                projection,
                null,
                null,
                sortOrder
        )){
            while ((cursor.moveToNext())){
                String path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
                System.out.println("data"+path);
            }
        }
    }
    private void audio(){
        Uri collection;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            collection = MediaStore.Audio.Media.getContentUri(MediaStore.VOLUME_EXTERNAL);
        } else {
            collection = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
        }
        String[] projection = new String[] {
                MediaStore.Video.Media._ID,
                MediaStore.Video.Media.DISPLAY_NAME,
                MediaStore.Video.Media.DURATION,
                MediaStore.Video.Media.SIZE
        };
        String sortOrder = MediaStore.Audio.Media.DISPLAY_NAME + " ASC";
        try (Cursor cursor = getApplicationContext().getContentResolver().query(
                collection,
                projection,
                null,
                null,
                sortOrder
        )){
            while ((cursor.moveToNext())){
                String path = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DISPLAY_NAME));
                System.out.println("data"+path);
            }
        }
    }

}

Leave a Comment