显示特定目录中的所有图像

时间:2019-10-24 17:57:48

标签: java android gridview

我是Android新手。试图创建一个允许用户下载图片然后存储在外部存储器中的应用程序,我的代码工作正常,但它显示了所有外部存储器的图像。我将这些图片存储在设备上的特定文件夹中,但是我不知道如何显示该文件夹中所有图片的列表。

  

/ storage / emulated / 0 / due / image /之类的图片仅显示此位置图片。

     

如果我写一个图像路径,应用程序将崩溃。

我的代码

public class mainActivity extends AppCompatActivity  {
GridView gridView;
ArrayList<File> list;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);




        checkPermissions();

        list = getImageFiles(new File(Environment.getExternalStorageDirectory().getPath() + " /storage/emulated/0/due/image/"));

        gridView = (GridView) findViewById(R.id.gridView);
        gridView.setAdapter(new GridAdapter());

        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
              //  startActivity(new Intent(getApplicationContext(), ViewImage.class).putExtra("img", list.get(i).toString()));
            }
        });

    }

    class GridAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return list.size();
        }

        @Override
        public Object getItem(int i) {
            return list.get(i);
        }

        @Override
        public long getItemId(int i) {
            return 0;
        }

        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {
            view = getLayoutInflater().inflate(R.layout.image_loader_list_item, viewGroup, false);
            ImageView imageView = (ImageView) view.findViewById(R.id.imageView);
            //imageview.setImageURI(Uri.parse(getItem(i).toString()));

            //Loading image from below url into imageView
            Glide.with(getApplicationContext())
                    .load(getItem(i).toString())
                    .into(imageView);
            return view;
        }
    }

    ArrayList<File> getImageFiles(File root) {
        ArrayList<File> list = new ArrayList();
        File[] files = root.listFiles();
        for (int i = 0; i < files.length; i++) {
            if(files[i].isDirectory()) {
                list.addAll(getImageFiles(files[i]));
            } else {
                if(files[i].getName().endsWith(".jpg") || files[i].getName().endsWith(".png") || files[i].getName().endsWith(".gif")) {
                    list.add(files[i]);
                }
            }
        }
        return  list;
    }

    private void checkPermissions(){
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if(checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED){
                //Requesting permission.
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
            }
        }
    }

    @Override //Override from ActivityCompat.OnRequestPermissionsResultCallback Interface
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        switch (requestCode) {
            case 1: {
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // permission granted
                }
                return;
            }
        }
    }

    private ActivityManager.MemoryInfo getMemoryInfo() {
        ActivityManager activityManager = (ActivityManager) this.getSystemService(ACTIVITY_SERVICE);
        ActivityManager.MemoryInfo memoryInfo = new ActivityManager.MemoryInfo();
        activityManager.getMemoryInfo(memoryInfo);
        return memoryInfo;
    }


}

logcat

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.dueaoinfo.dueao_job/com.dueaoinfo.dueao_job.MainActivity}: java.lang.NullPointerException: Attempt to get length of null array
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2946)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3081)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1831)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:201)
        at android.app.ActivityThread.main(ActivityThread.java:6823)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:873)
     Caused by: java.lang.NullPointerException: Attempt to get length of null array
        at com.dueaoinfo.dueao_job.MainActivity.getImageFiles(MainActivity.java:91)
        at com.dueaoinfo.dueao_job.MainActivity.onCreate(MainActivity.java:43)
        at android.app.Activity.performCreate(Activity.java:7224)
        at android.app.Activity.performCreate(Activity.java:7213)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1272)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2926)

1 个答案:

答案 0 :(得分:0)

您的代码:

list = getImageFiles(Environment.getExternalStorageDirectory());

可以替换为:

  list = getImageFiles(Environment.getExternalStorageDirectory(),"/storage/emulated/0/due/image/");

以便它指向您要提取的文件夹。

参考:Environment.getExternalStorageDirectory()

希望这会有所帮助。