我正在创建一个在设备上搜索特定文件的应用
我使用以下代码。
但是当我运行这个应用程序时,它会给出nullpointer异常
我修改了代码..新代码如下
public class Display extends ListActivity {
List<String> fileslist;
static String searchtext;
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
Bundle bd= getIntent().getExtras();
searchtext= bd.getString("1");
fileslist= new ArrayList<String>();
new Display().listallfiles("/");
if(fileslist.isEmpty()){
Toast.makeText(this, "YO OY", 2200).show();
}
else{
ArrayAdapter<String> displaylist = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,fileslist);
setListAdapter(displaylist);
}
}
void listallfiles(String path){
try{
String files;
File folder = new File (path);
File [] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++)
{
if(listOfFiles[i].canRead()){
if (listOfFiles[i].isFile())
{
files = listOfFiles[i].getName();
if(listOfFiles[i].getName().contains(searchtext))
fileslist.add(listOfFiles[i].getName());
}
if(listOfFiles[i].isDirectory()) {
listallfiles(path+"\\"+listOfFiles[i].getName().toString()+"\\");
}
}
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
堆栈跟踪
12-13 19:35:27.072:W / System.err(513):java.lang.NullPointerException
12-13 19:35:27.082:W / System.err(513):at com.mypack.filesearch.Display.listallfiles(Display.java:56)
12-13 19:35:27.082:W / System.err(513):at com.mypack.filesearch.Display.listallfiles(Display.java:70)
12-13 19:35:27.082:W / System.err(513):at com.mypack.filesearch.Display.onCreate(Display.java:35)
12-13 19:35:27.082:W / System.err(513):在android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
12-13 19:35:27.082:W / System.err(513):在android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
这段代码运行得很好..如果你是wana测试你是否自己。
package com.mypack;
import java.util.*;
import java.io.*;
public class Main
{
List<String> listof;
public static void main(String [] args)
{
// Directory path here
String path = "d:\\Java\\Programs";
new Main().listallfiles(path);
}
void listallfiles(String path){
try{
listof= new ArrayList<String>();
String files;
File folder = new File (path);
File [] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++)
{
if (listOfFiles[i].isFile())
{
files = listOfFiles[i].getName();
if(listOfFiles[i].getName().contains(".class"))
listof.add(files);
}
else if(listOfFiles[i].isDirectory()) {
listallfiles(path+"\\"+listOfFiles[i].getName().toString()+"\\");
}
}
}
catch (Exception e)
{
e.printStackTrace();
}
for(int i=0;i<listof.size();i++)
System.out.println(listof.get(i).toString());
}
}