以前は外部ストレージのpathは
Environment.getExternalStorageDirectory().getPath()
によって取得できましたが、API29以上からは非推奨になりました。
したがって、Context#getExternalFilesDir(String)を
代わりに使用しました。
しかし、実行すると
java.lang.NullPointerException: Attempt to get length of null array
のエラーが発生します。
ご教授よろしくお願いいたします。
これは、
GAlleryFragment
Java
1 private void init(){ 2 ROOT_DIR = getActivity().getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS); 3 4 PICTURES = ROOT_DIR+"/Pictures"; 5 CAMERA = ROOT_DIR +"/DCIM/camera"; 6 //check for other folders inside "/storage/emulated/0/pictures" 7 if(FileSearch.getDirectoryPaths(PICTURES)!=null){ 8 directories = FileSearch.getDirectoryPaths(PICTURES); 9 10 } 11 directories.add(CAMERA); 12 13 ArrayAdapter<String>adapter= new ArrayAdapter<String>(getActivity(), 14 android.R.layout.simple_spinner_item,directories); 15 adapter.setDropDownViewResource(android.R.layout.simple_spinner_item); 16 directorySpinner.setAdapter(adapter); 17 18 directorySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { 19 @Override 20 public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { 21 Log.d(TAG, "onItemSelected: "+directories.get(position)); 22 23 //setup our image grid for the directory chosen 24 } 25 26 @Override 27 public void onNothingSelected(AdapterView<?> parent) { 28 29 } 30 }); 31 }
FileSearch
Java
1public class FileSearch { 2 3 /** 4 * Search a directory and return a list of all **directories** contained inside 5 * @param directory 6 * @return 7 */ 8 public static ArrayList<String> getDirectoryPaths(String directory){ 9 ArrayList<String> pathArray = new ArrayList<>(); 10 File file = new File(directory); 11 File[] listfiles = file.listFiles(); 12 for(int i = 0; i < listfiles.length; i++){ 13 if(listfiles[i].isDirectory()){ 14 pathArray.add(listfiles[i].getAbsolutePath()); 15 } 16 } 17 return pathArray; 18 } 19 20 /** 21 * Search a directory and return a list of all **files** contained inside 22 * @param directory 23 * @return 24 */ 25 public static ArrayList<String> getFilePaths(String directory){ 26 ArrayList<String> pathArray = new ArrayList<>(); 27 File file = new File(directory); 28 File[] listfiles = file.listFiles(); 29 for(int i = 0; i < listfiles.length; i++){ 30 if(listfiles[i].isFile()){ 31 pathArray.add(listfiles[i].getAbsolutePath()); 32 } 33 } 34 return pathArray; 35 } 36}
あなたの回答
tips
プレビュー