public class Dictionary extends Activity implements OnClickListener, TextWatcher{
private final String DATABASE_PATH = android.os.Environment
.getExternalStorageDirectory().getAbsolutePath()
+ "/dictionary";
private final String DATABASE_FILENAME = "dictionary.db3";
SQLiteDatabase database;
Button btnSelectWord;
AutoCompleteTextView actvWord;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// 打開數據庫,database是在Main類中定義的一個SQLiteDatabase類型的變量
database = openDatabase();
// 下面的代碼裝載了相關組件,並設置了相應的事件
btnSelectWord = (Button) findViewById(R.id.btnSelectWord);
actvWord = (AutoCompleteTextView) findViewById(R.id.actvWord);
btnSelectWord.setOnClickListener(this);
actvWord.addTextChangedListener(this);
}
public void onClick(View view)
{
// 查找單詞的SQL語句
String sql = "select chinese from t_words where english=?";
Cursor cursor = database.rawQuery(sql, new String[]
{ actvWord.getText().toString() });
String result = "未找到該單詞.";
// 如果查找單詞,顯示其中文信息
if (cursor.getCount() > 0)
{
// 必須使用moveToFirst方法將記錄指針移動到第1條記錄的位置
cursor.moveToFirst();
result = cursor.getString(cursor.getColumnIndex("chinese"));
Log.i("tran", "success"+result);
}
// 顯示查詢結果對話框
new AlertDialog.Builder(this).setTitle("查詢結果").setMessage(result)
.setPositiveButton("關閉", null).show();
}
private SQLiteDatabase openDatabase() {
try {
// 獲得dictionary.db文件的絕對路徑
String databaseFilename = DATABASE_PATH + "/" + DATABASE_FILENAME;
File dir = new File(DATABASE_PATH);
// 如果/sdcard/dictionary目錄中存在,創建這個目錄
if (!dir.exists())
dir.mkdir();
// 如果在/sdcard/dictionary目錄中不存在
// dictionary.db文件,則從res\raw目錄中復制這個文件到
// SD卡的目錄(/sdcard/dictionary)
if (!(new File(databaseFilename)).exists()) {
// 獲得封裝dictionary.db文件的InputStream對象
InputStream is = getResources().openRawResource(
R.raw.dictionary);
FileOutputStream fos = new FileOutputStream(databaseFilename);
byte[] buffer = new byte[8192];
int count = 0;
// 開始復制dictionary.db文件
while ((count = is.read(buffer)) > 0) {
fos.write(buffer, 0, count);
}
fos.close();
is.close();
}
// 打開/sdcard/dictionary目錄中的dictionary.db文件
SQLiteDatabase database = SQLiteDatabase.openOrCreateDatabase(
databaseFilename, null);
return database;
} catch (Exception e) {
}
return null;
}
@Override
public void afterTextChanged(Editable s) {
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
}