升级方法被调用,但数据未加载。

huangapple 未分类评论43阅读模式
英文:

On Upgrade method is called but data not loading

问题

以下是代码部分的翻译内容:

// 在ListViewActivity的onCreate方法中
// 初始化用于存储布尔值的SharedPreferences键
INITIALIZED = "initialized_database_" + class_name;

// 初始化SharedPreferences以避免空指针异常
sharedPreferences = getSharedPreferences(INITIALIZED, MODE_PRIVATE);

myDictionaryDatabaseHelper = new DictionaryDatabaseHelper(this, db_name);
allWordDefinitions = new ArrayList<>();

initialized = sharedPreferences.getBoolean(INITIALIZED, false);

// 如果未初始化数据库,则进行初始化
if (!initialized) {
    // 初始化数据库
    initializeDatabase();
}
else {
    //Log.e(logTagString, myDictionaryDatabaseHelper.getDatabaseName() + " 已经初始化。");
}

// initializeDatabase方法
// 初始化数据库
private void initializeDatabase() {
    editor = sharedPreferences.edit();

    try {
        InputStream inputStream = getResources().openRawResource(db_resource);
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
        DictionaryLoader.loadData(bufferedReader, myDictionaryDatabaseHelper);

        Toast.makeText(this, "正在初始化数据库...", Toast.LENGTH_SHORT).show();

        // 更改SharedPreferences编辑器中的布尔值
        editor.putBoolean(INITIALIZED, true);
        editor.apply();
    } catch (Resources.NotFoundException e) {
        e.printStackTrace();

        // 弹出消息提示
        Toast.makeText(this, "找不到数据库资源!", Toast.LENGTH_SHORT).show();
        Toast.makeText(this, "数据库初始化失败!", Toast.LENGTH_SHORT).show();

        // 将初始化布尔值设置为false,以便重新初始化数据库
        editor.putBoolean(INITIALIZED, false);
        editor.apply();
    }
}

// DictionaryDatabaseHelper类
class DictionaryDatabaseHelper extends SQLiteOpenHelper {

    private static String DB_NAME = "db_name";
    private final static int DB_VERSION = 2;

    private final static String ID_COLUMN = "_id";
    private final static String WORD_COLUMN = "word";
    private final static String DEFINITION_COLUMN = "definition";

    private final String CREATE_DATABASE_QUERY = "CREATE TABLE "
            + getDatabaseName() + " ("
            + ID_COLUMN + " INTEGER PRIMARY KEY AUTOINCREMENT, "
            + WORD_COLUMN + " TEXT, "
            + DEFINITION_COLUMN + " TEXT)";

    private final String UPGRADE_QUERY = "DROP TABLE IF EXISTS " + getDatabaseName();

    // 构造函数用于创建具有不同名称的数据库
    DictionaryDatabaseHelper(Context context, String db_name) {
        super(context, db_name, null, DB_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(CREATE_DATABASE_QUERY);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // 将数据库初始化变量设置为false,以便重新初始化数据库
        WordListActivity.editor.putBoolean(WordListActivity.INITIALIZED, false);
        WordListActivity.editor.apply();

        db.execSQL(UPGRADE_QUERY);
        onCreate(db);
    }

    // 第一次初始化数据库
    void initializeDatabaseForTheFirstTime(ArrayList<WordDefinition> wordDefinitions) {
        SQLiteDatabase db = this.getWritableDatabase();
        db.execSQL("BEGIN");

        ContentValues contentValues = new ContentValues();

        for (WordDefinition wordDefinition : wordDefinitions) {
            contentValues.put(WORD_COLUMN, wordDefinition.word);
            contentValues.put(DEFINITION_COLUMN, wordDefinition.definition);

            db.insert(getDatabaseName(), null, contentValues);
        }

        db.execSQL("COMMIT");
        db.close();
    }
}

以上是您提供的代码部分的翻译内容。如果您有任何问题或需要进一步帮助,请随时提问。

英文:

I have my first activity (MainActivity) having different letters (like A, B, C...). When click on a letter it opens a new activity (LIstViewActivity) having a listView of words starting with that letter. This list is created from a text file inside raw folder and stored in a database named suppose database_a. In LIstViewActivity I am storing a boolean in SharedPreferenceswhich checks whether database of that particular letter is created or not. If it is not created it runs the initializeDatabase method otherwise not. These are working fine. But if I increase the database version then onUpgrade method is called but the list is not populating. I also tried to change the boolean value inside onUpgrade method. In this case on my first attempt data is not populating, when I go back and come again then the data are loading. I think the problem might be due to the boolean value. How can I overcome the problem? Any help will be appreciated. Thanks...

This is inside onCreate of ListViewActivity

 //initialize key for the boolean in sharedPreference
    INITIALIZED = &quot;initialized_database_&quot;+class_name;

    //initialize sharedPreference to avoid NullPointerException
    sharedPreferences = getSharedPreferences(INITIALIZED, MODE_PRIVATE);

    myDictionaryDatabaseHelper = new DictionaryDatabaseHelper(this, db_name);
    allWordDefinitions = new ArrayList&lt;&gt;();

    initialized = sharedPreferences.getBoolean(INITIALIZED, false);

    //initialize database
    if (!initialized) {

        //initialize database
        initializeDatabase();
    }
    else {
        //Log.e(logTagString, myDictionaryDatabaseHelper.getDatabaseName() +&quot; already initialized.&quot;);
    }

This is initializeDatabase method

//initialize the database
private void initializeDatabase() {

    editor = sharedPreferences.edit();

    try {
        InputStream inputStream = getResources().openRawResource(db_resource);
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
        DictionaryLoader.loadData(bufferedReader, myDictionaryDatabaseHelper);

        Toast.makeText(this, &quot;Initializing database...&quot;, Toast.LENGTH_SHORT).show();
        //Log.e(logTagString, &quot;Initializing &quot; + myDictionaryDatabaseHelper.getDatabaseName());

        //change boolean value in sharedPreference editor
        editor.putBoolean(INITIALIZED, true);
        editor.apply();
    } catch (Resources.NotFoundException e) {
        e.printStackTrace();
        //Log.e(logTagString, myDictionaryDatabaseHelper.getDatabaseName() +&quot; resource not found!&quot;);
        //Log.e(logTagString, myDictionaryDatabaseHelper.getDatabaseName() +&quot; initialization failed!&quot;);

        //toast a message
        Toast.makeText(this, &quot;Database resource not found!&quot;, Toast.LENGTH_SHORT).show();
        Toast.makeText(this, &quot;Database initialization failed!&quot;, Toast.LENGTH_SHORT).show();

        //keep the initialized boolean false to reinitialize the database
        editor.putBoolean(INITIALIZED, false);
        editor.apply();
    }
}

This is my DictionaryDatabaseHelper class

class DictionaryDatabaseHelper extends SQLiteOpenHelper {

private static String DB_NAME = &quot;db_name&quot;;
private final static int DB_VERSION = 2;


private final static String ID_COLUMN = &quot;_id&quot;;
private final static String WORD_COLUMN = &quot;word&quot;;
private final static String DEFINITION_COLUMN = &quot;definition&quot;;

private final String CREATE_DATABASE_QUERY = &quot;CREATE TABLE &quot;
        +getDatabaseName()+ &quot; (&quot;
        +ID_COLUMN+ &quot; INTEGER PRIMARY KEY AUTOINCREMENT, &quot;
        +WORD_COLUMN+ &quot; TEXT, &quot;
        +DEFINITION_COLUMN+ &quot; TEXT)&quot;;

private final String UPGRADE_QUERY = &quot;DROP TABLE IF EXISTS &quot; +getDatabaseName();

//constructor to create different named database
DictionaryDatabaseHelper(Context context, String db_name) {
    super(context, db_name, null, DB_VERSION);
}

@Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL(CREATE_DATABASE_QUERY);
    //Log.e(&quot;DICTIONARY&quot;, &quot;DatabaseHelper onCreate Initializing database...&quot;);
    //Log.e(&quot;DICTIONARY&quot;, &quot;Database name is: &quot; +getDatabaseName());
    //Log.e(&quot;DICTIONARY&quot;, &quot;Database version is &quot;+db.getVersion());
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    //make the database initialization variable false to reinitialize the database
    WordListActivity.editor.putBoolean(WordListActivity.INITIALIZED, false);
    WordListActivity.editor.apply();
    //Log.e(&quot;DICTIONARY&quot;, &quot;Initialized value is: &quot; +WordListActivity.initialized);



    db.execSQL(UPGRADE_QUERY);
    onCreate(db);

    //Log.e(&quot;DICTIONARY&quot;, &quot;Upgrading database form version &quot; +oldVersion+ &quot; to &quot; +newVersion);
}

//Initialize database for the first time
void initializeDatabaseForTheFirstTime(ArrayList&lt;WordDefinition&gt; wordDefinitions) {

    //Log.e(&quot;DICTIONARY&quot;, &quot;Initializing database for the first time.&quot;);

    SQLiteDatabase db = this.getWritableDatabase();
    db.execSQL(&quot;BEGIN&quot;);

    ContentValues contentValues = new ContentValues();

    for (WordDefinition wordDefinition : wordDefinitions) {
        contentValues.put(WORD_COLUMN, wordDefinition.word);
        contentValues.put(DEFINITION_COLUMN, wordDefinition.definition);

        db.insert(getDatabaseName(), null, contentValues);
    }

    db.execSQL(&quot;COMMIT&quot;);
    db.close();
}

}

huangapple
  • 本文由 发表于 2020年7月26日 00:42:56
  • 转载请务必保留本文链接:https://java.coder-hub.com/63090897.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定