我正在尝试创建一个应用程序,该应用程序在我的下载文件夹中搜索特定文件的最新版本,然后返回该文件的路径。当我尝试查看带有文件名的文件数组或字符串数组时,我不断收到 NullPointerException
。当我调用 downloadList.length; 时,就会出现空点。我也尝试过 while(download[i] != null) {
但我仍然得到 NullPointerException
。我对应用程序编程相当陌生,并且已经构建了一些应用程序,但它们都没有访问公共(public)文件。非常感谢任何帮助。
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
}
}
}
最佳答案
你不能使用
File downloadDir = new File(Environment.DIRECTORY_DOWNLOADS);
直接。这是错误。 因为Environment.DIRECTORY_DOWNLOADS是字典的名称,而不是路径。您可以使用
getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS);
而不是在您的 Activity 中。
关于java - Android应用程序搜索下载文件夹中的特定文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22314327/