現在、アンドロイドの簡単な単語検索プログラムを作成しようとしています。ユーザーが検索した各文字と一致し、すべての一致をローカル辞書から表示するはずです。リストビューやループを文字列配列で更新する方が効率的ですか
小さな辞書ではすべて機能していますが、大きな辞書を使用しようとするとプログラムが崩壊します。私の推測では、各単語をループする検索機能は非効率的です。
私のプロジェクトのコードは次のとおりです。前述したように
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)
のループが呼び出されるとクラッシュします。
多くのありがとうございました!
AsyncTaskを見てください。あなたはバックグラウンドスレッドで検索したいと思う。 – ElDuderino
検索を開始するのが遅れているハンドラーを使うと、より良い結果が得られます。 –