Read the database files directly in Android

Recommended for you: Get network issues from WhatsUp Gold. Not end users.

public class Dictionary extends Activity  implements OnClickListener, TextWatcher{ 

private final String DATABASE_PATH = android.os.Environment 


+ "/dictionary"; 

private final String DATABASE_FILENAME = "dictionary.db3"; 

SQLiteDatabase database; 

Button btnSelectWord; 

AutoCompleteTextView actvWord; 


public void onCreate(Bundle savedInstanceState) { 



// Open the database, database is a variable of type SQLiteDatabase defined in the Main class. 

database = openDatabase(); 

// The following code loading the related components, and set the corresponding event 

btnSelectWord = (Button) findViewById(; 

actvWord = (AutoCompleteTextView) findViewById(; 




public void onClick(View view) 


//  The SQL statement to find words 

String sql = "select chinese from t_words where english=?";   

Cursor cursor = database.rawQuery(sql, new String[] 

{ actvWord.getText().toString() }); 

String result = "The word is not found."; 

//  If you find the word, to show its Chinese information 

if (cursor.getCount() > 0) 


//  You must use the moveToFirst method to record the pointer moves to the first recording position 


result = cursor.getString(cursor.getColumnIndex("chinese")); 

Log.i("tran", "success"+result); 


//  Show query result dialog 

new AlertDialog.Builder(this).setTitle("Query results").setMessage(result) 

.setPositiveButton("Close", null).show(); 


private SQLiteDatabase openDatabase() { 

try { 

// The absolute path to the dictionary.db file access 

String databaseFilename = DATABASE_PATH + "/" + DATABASE_FILENAME; 

File dir = new File(DATABASE_PATH); 

// If in the /sdcard/dictionary directory, create this directory 

if (!dir.exists()) 


// If it does not exist in the /sdcard/dictionary directory 

// Dictionary.db files from the res\raw directory, copy this file to the 

// SD card catalog(/sdcard/dictionary) 

if (!(new File(databaseFilename)).exists()) { 

// Get the package dictionary.db file of the InputStream object 

InputStream is = getResources().openRawResource( 


FileOutputStream fos = new FileOutputStream(databaseFilename); 

byte[] buffer = new byte[8192]; 

int count = 0; 

// To copy the dictionary.db file 

while ((count = > 0) { 

fos.write(buffer, 0, count); 





// Open the dictionary.db file in the /sdcard/dictionary directory 

SQLiteDatabase database = SQLiteDatabase.openOrCreateDatabase( 

databaseFilename, null); 

return database; 

} catch (Exception e) { 


return null; 



public void afterTextChanged(Editable s) { 



public void beforeTextChanged(CharSequence s, int start, int count, 

int after) { 



public void onTextChanged(CharSequence s, int start, int before, int count) { 



Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download

Posted by Pauline at November 16, 2013 - 1:06 PM