ユーザーからデータを取得し、データベースから結果を表示するアプリがあります。そのデータベースから、データを ArrayList にプッシュします。たとえば、ユーザーが文 (例: "Hello world") を入力すると、アプリはデータベースからレコードをループし、何かを見つけると、単語が見つかったことをユーザーに表示します。このような:
あいまいな単語: 世界 意味: 世界の意味。
ここに私が取り組んでいるコードがあります:
private DBHelper dbHelper;
Cursor cursor;
ArrayList<String> colWords = new ArrayList<String>();
ArrayList<String> colMeanings = new ArrayList<String>();
String[] words;
String[] meanings;
ok = (Button) findViewById (R.id.button1);
ok.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
//checkAmbiguousWord();
dbHelper = new DBHelper(MainActivity.this);
try {
dbHelper.createDataBase();
} catch (IOException ioe) {
throw new Error("Unable to create database");
}
try {
dbHelper.openDataBase();
} catch (SQLException sqle) {
throw sqle;
}
cursor = dbHelper.getAllWords();
for(cursor.moveToFirst(); cursor.moveToNext(); cursor.isAfterLast()) {
colWords.add(cursor.getString(1));
colMeanings.add(cursor.getString(2));
}
checkAmbiguousWord();
}
});
}
private void checkAmbiguousWord(){
final String textToCheck = text.getText().toString();
List<Integer> ambiguousIndexes = findAmbiguousWordIndexes(textToCheck);
view.setText(!ambiguousIndexes.isEmpty() ?
ambigousIndexesToMessage(ambiguousIndexes) : "No ambiguous word/s found.");
}
/**
* @param text checked for ambiguous words
* @return the list of indexes of the ambiguous words in the {@code words} array
*/
private List<Integer> findAmbiguousWordIndexes(String text) {
final String lowerCasedText = text.toLowerCase();
final List<Integer> ambiguousWordIndexList = new ArrayList<Integer>();
words = (String[]) colWords.toArray(new String[colWords.size()]);
meanings = (String[]) colMeanings.toArray(new String[colMeanings.size()]);
for (int i = 0; i < words.length; i++) {
if (lowerCasedText.contains(words[i].toLowerCase())) {
ambiguousWordIndexList.add(i);
}
}
return ambiguousWordIndexList;
}
public String ambigousIndexesToMessage(List<Integer> ambiguousIndexes) {
// create the text using the indexes
// this is an example implementation
StringBuilder sb = new StringBuilder();
for (Integer index : ambiguousIndexes) {
sb.append("Ambiguous words: ");
sb.append(words[index] + "\nMeaning: " + meanings[index] + "\n");
sb.append(" ");
}
return sb.toString();
}
しかし、私の問題は、同じ Hello World を入力するたびに結果が追加されることです。
あいまいな単語: 世界 意味: 世界の意味 あいまいな単語: 世界 意味: 世界の意味
私のコードで間違っているのは何ですか? 私はJavaが初めてなので、間違っているコード行を見つけるためにあなたの助けが必要です. どんな助けでも大歓迎です。前もって感謝します。