বাংলায় অ্যান্ড্রয়েড সহায়িকা - Bangla Android Guide

ভার্চুয়াল টেবিল পূর্ণ করা

টেবিলের জন্য এখন স্টোর করতে ডাটা প্রয়োজন। নিচের কোডটি আপনাকে দেখাবে কীভাবে একটি টেক্সট ফাইল (res/raw/definitions.txt এ অবস্থিত) পাঠ করতে হয় যা শব্দ এবং এর সংজ্ঞা রাখে, কীভাবে ওই ফাইল পার্স (parse) করতে হয়, এবং কীভাবে ভার্চুয়াল টেবিলে একটি রো হিসাবে ওই ফাইলের প্রতিটা লাইন প্রবেশ করাতে হয়। ইউআইকে লক হওয়া থেকে বিরত রাখতে এইসবগুলো অন্য থ্রেডে হয়ে থাকে। আপনার DatabaseOpenHelper ইনার ক্লাসে নিচের কোড যোগ করুন:

টিপ: এছাড়াও আপনি এই থ্রেডের সমাপ্তির আপনার ইউআই একটিভিটি নোটিফাই (জ্ঞাপন) করতে একটি কলব্যাক সেটআপ করতে চাইতে পারেন।

private void loadDictionary() {
        new Thread(new Runnable() {
            public void run() {
                try {
                    loadWords();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }).start();
    }

private void loadWords() throws IOException {
    final Resources resources = mHelperContext.getResources();
    InputStream inputStream = resources.openRawResource(R.raw.definitions);
    BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));

    try {
        String line;
        while ((line = reader.readLine()) != null) {
            String[] strings = TextUtils.split(line, "-");
            if (strings.length < 2) continue;
            long id = addWord(strings[0].trim(), strings[1].trim());
            if (id < 0) {
                Log.e(TAG, "unable to add word: " + strings[0].trim());
            }
        }
    } finally {
        reader.close();
    }
}

public long addWord(String word, String definition) {
    ContentValues initialValues = new ContentValues();
    initialValues.put(COL_WORD, word);
    initialValues.put(COL_DEFINITION, definition);

    return mDatabase.insert(FTS_VIRTUAL_TABLE, null, initialValues);
}

Call the loadDictionary() method wherever appropriate to populate the table. A good place would be in the onCreate() method of the DatabaseOpenHelper class, right after you create the table:

@Override
public void onCreate(SQLiteDatabase db) {
    mDatabase = db;
    mDatabase.execSQL(FTS_TABLE_CREATE);
    loadDictionary();
}