Android to get list of All images using java | Full project

Here is the full project to get the list of all images in Android using java

MainActivity.java

package tech.softbinarycrunch.realvideoeditor;

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

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
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.List;

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 listoffile(){
    String path = Environment.getExternalStorageDirectory().toString();
    File directory = new File(path);
    File[] files = directory.listFiles();
String ex;
    for (int i = 0; i < files.length; i++)
    {
        System.out.println("list of dir"+files[i].getName());
        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();
            }
        });
    }
}

Leave a Comment