我目前正在尝试为Android编写一个简单的单词搜索程序。它应该匹配用户搜索的每个字母,并显示本地词典中的所有匹配项。
一切对于一个较小的字典都是有效的,但是当我尝试使用较大的字典时,该程序崩溃了。我的猜测是,遍历每个单词的搜索功能效率很低。
以下是我的项目的代码。
public class MainActivity extends ActionBarActivity {
String[] items;
int length;
ArrayList<String> listItems;
ArrayAdapter<String> adapter;
ListView listView;
EditText editText;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView=(ListView)findViewById(R.id.listview);
editText=(EditText)findViewById(R.id.txtsearch);
items = readFile().split("\\n");
initList();
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
length=s.toString().length();
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (s.toString().equals("")) {
initList();
}
else {
searchItem(s.toString());
}
}
@Override
public void afterTextChanged(Editable s) {
if (s.toString().length() < length) {
initList();
for (String item:items) {
if (!item.toLowerCase().contains(s.toString().toLowerCase())) {
listItems.remove(item);
}
}
}
}
});
}
public String readFile(){
InputStream input = getResources().openRawResource(getResources().getIdentifier("words","raw", getPackageName()));
BufferedReader br = null;
StringBuilder sb = new StringBuilder();
String finalstring = "";
try {
String line;
br = new BufferedReader(new InputStreamReader(input));
while ((line = br.readLine()) != null) {
// finalstring += line + "\n";
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return sb.toString();
}
public void searchItem (String searchword) {
for(String item:items){
if(!item.contains(searchword)){
listItems.remove(item);
}
}
adapter.notifyDataSetChanged();
}
public void initList(){
listItems=new ArrayList<>(Arrays.asList(items));
adapter=new ArrayAdapter<String>(this, R.layout.list_item, R.id.txtitem, listItems);
listView.setAdapter(adapter);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
如前所述,我相信我的
SearchItem(String SearchWord)
是问题所在,但是适配器的数据更新是否可能出了问题?注意:我使用过断点,并且在
SearchItem(String SearchWord)
中的循环被调用时会崩溃。非常感谢你们!
最佳答案
我更改了editText并改用searchView。那解决了问题!