0

I am trying to create an app that searches my Download folder for the most current version of a specific file and then returns the path to that file. I keep getting a NullPointerException when I try looking at either the file array or string array with the file names. The null point comes when I call downloadList.length;. I have also tried while(download[i] != null) { but I still get NullPointerException. I am fairly new to app programming and have build a few apps, but none of them access public files. Any help is greatly appreciated.

public class MainActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        String dlDir = Environment.DIRECTORY_DOWNLOADS;
        Log.d("Dir", dlDir);
        File downloadDir = new File(dlDir);
        Log.d("Dir", "Found the Directory");
        String[] downloadList = downloadDir.list();
        // File[] downloadList = downloadDir.listFiles();
        Log.d("Dir", "Created the list");
        int len = downloadList.length;
        while (int i = 0; i < len; i++) {
            DoStuff
        }
    }
}
  • What are you testing on? Its possible that the directory does not exists. Try checking the return value of `downloadDir.exists()` to make sure it exists. You can always create it yourself by calling `downloadDir.mkDir()` if it doesn't exist (granted you have write permissions) – Naveed Mar 11 '14 at 01:08

2 Answers2

1

You can't use

File downloadDir = new File(Environment.DIRECTORY_DOWNLOADS);

directly. It's error. Because Environment.DIRECTORY_DOWNLOADS is the name of the dictionary , not the path.You can use

getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS);

instead in your activity.

Zebulon Li
  • 540
  • 4
  • 21
  • Thank you for the clarification of the `Environment.DIRECTORY_DOWNLOADS` Clarification: I would like to access the downloads folder on my internal storage, not my SD Card. Does getExternalFilesDir work for the internal storage? – Android Amature Mar 11 '14 at 02:09
  • @AndroidAmature Where is your download dir? You can use getDir( dirname, Context.MODE_PRIVATE) to get a dir in the internal storage for your app. It's path is /data/data/your package/app_dirname . Is this you want? – Zebulon Li Mar 11 '14 at 07:20
  • UPDATE: I used `Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)` but I forgot the `` in the Manifest file – Android Amature Mar 16 '14 at 23:55
0

Because File.length return to size of file.
Try to this.

String[] filelist = downloadDir.list();
filelist.length;

or

ArrayList<String> fileList = new ArrayList( Arrays.asList( downloadDir.list() ) );
flieList.size();

or

ArrayList<String> fileList;
Collections.addAll( fileList, downloadDir.list() );
fileList.size();

You can help this page. http://developer.android.com/reference/java/io/File.html

Amadas
  • 703
  • 1
  • 5
  • 10