我正在尝试创建一个搜索手机文件的Android应用程序,并在用户实时输入时在搜索框下列出它。请帮助纠正代码,我得到一个空指针异常。所有资源都已到位。
import java.io.File;
import java.io.FilenameFilter;
import java.util.ArrayList;
import android.os.Bundle;
import android.app.ListActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Menu;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.ProgressBar;
public class MainActivity extends ListActivity implements TextWatcher {
File[] myfiles;
FilenameFilter filter;
TextWatcher watcher;
String query;
static File file;
EditText eT;
ListView list;
ArrayList<String> myList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ProgressBar progressBar = new ProgressBar(this);
progressBar.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT));
progressBar.setIndeterminate(true);
list.setEmptyView(progressBar);
ViewGroup root = (ViewGroup) findViewById(android.R.id.content);
root.addView(progressBar);
list = (ListView) findViewById(android.R.id.list);
File file = new File("Environment.getExternalStorageDirectory().getPath()");
myfiles = file.listFiles(filter);
Log.d("tag", "files passed");
eT = (EditText) findViewById(R.id.editText1);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
query = ((EditText) s).getText().toString();
filter = new FilenameFilter() {
@Override
public boolean accept(File dir, String filename) {
String lcaseName = filename.toLowerCase();
if(lcaseName.contains(query)) {
return true;
}
else {
return false;
}
}
};
list.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, myList));
myList = new ArrayList<String>();
for(int i =0; i < myfiles.length; i++) {
myList.add(myfiles[i].getName());
}
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
}
}
答案 0 :(得分:2)
list.setEmptyView(progressBar);
// ...
list = (ListView) findViewById(android.R.id.list);
您在初始化之前使用list
。
从问题评论中提取的调试过程:
在代码中发布有关崩溃的问题时,请始终包含步骤1和2中的信息。
答案 1 :(得分:1)
变量list
未初始化。但修复此问题后,您将再次获得NullPointerException
,因为您使用的filter
也为空。
myfiles = file.listFiles(filter);