java - Android 模拟器因 Db 崩溃(找不到错误 - 新手)

标签 java android database sqlite

很抱歉问这个问题,但我真的找不到我的数据库抛出异常的原因。这是代码,请看一下。整个想法是制作一个刽子手游戏作为一个学校项目,我想创建一个地方,用户可以看到所有当前的单词,并根据需要添加更多单词或删除现有单词(这是在要求中)。我认为我在 populateListView 方法中犯了一个错误,因为我认为我以前没有使用过光标,但查看了一些在线 Material ,所以我尝试进行相应的调整。如果有更简单的方法 -> 我全力以赴。提前致谢 !

这是 DBAdapter 文件:

public class DBAdapter {

private static final String TAG = "DBAdapter"; //used for logging database version changes

// Field Names:
public static final String KEY_ROWID = "_id";
public static final String KEY_WORD = "word";

public static final String[] ALL_KEYS = new String[] {KEY_ROWID, KEY_WORD};

// Column Numbers for each Field Name:
public static final int COL_ROWID = 0;
public static final int COL_WORD = 1;


// DataBase info:
public static final String DATABASE_NAME = "dbToDo";
public static final String DATABASE_TABLE = "mainToDo";
public static final int DATABASE_VERSION = 2; // The version number must be incremented each time a change to DB structure occurs.

//SQL statement to create database
private static final String DATABASE_CREATE_SQL =
        "CREATE TABLE " + DATABASE_TABLE
                + " (" + KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
                + KEY_WORD + " TEXT NOT NULL"
                + ");";

private final Context context;
private DatabaseHelper myDBHelper;
private SQLiteDatabase db;


public DBAdapter(Context ctx) {
    this.context = ctx;
    myDBHelper = new DatabaseHelper(context);
}

// Open the database connection.
public DBAdapter open() {
    db = myDBHelper.getWritableDatabase();
    return this;
}

// Close the database connection.
public void close() {
    myDBHelper.close();
}

// Add a new set of values to be inserted into the database.
public long insertRow(String word) {
    ContentValues initialValues = new ContentValues();
    initialValues.put(KEY_WORD, word);


    // Insert the data into the database.
    return db.insert(DATABASE_TABLE, null, initialValues);
}

// Delete a row from the database, by rowId (primary key)
public boolean deleteRow(long rowId) {
    String where = KEY_ROWID + "=" + rowId;
    return db.delete(DATABASE_TABLE, where, null) != 0;
}

public void deleteAll() {
    Cursor c = getAllRows();
    long rowId = c.getColumnIndexOrThrow(KEY_ROWID);
    if (c.moveToFirst()) {
        do {
            deleteRow(c.getLong((int) rowId));
        } while (c.moveToNext());
    }
    c.close();
}

// Return all data in the database.
public Cursor getAllRows() {
    String where = null;
    Cursor c =  db.query(true, DATABASE_TABLE, ALL_KEYS, where, null, null, null, null, null);
    if (c != null) {
        c.moveToFirst();
    }
    return c;
}

// Get a specific row (by rowId)
public Cursor getRow(long rowId) {
    String where = KEY_ROWID + "=" + rowId;
    Cursor c =  db.query(true, DATABASE_TABLE, ALL_KEYS,
            where, null, null, null, null, null);
    if (c != null) {
        c.moveToFirst();
    }
    return c;
}

// Change an existing row to be equal to new data.
public boolean updateRow(long rowId, String word) {
    String where = KEY_ROWID + "=" + rowId;
    ContentValues newValues = new ContentValues();
    newValues.put(KEY_WORD, word);
    // Insert it into the database.
    return db.update(DATABASE_TABLE, newValues, where, null) != 0;
}


private static class DatabaseHelper extends SQLiteOpenHelper
{
    DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase _db) {
        _db.execSQL(DATABASE_CREATE_SQL);
    }

    @Override
    public void onUpgrade(SQLiteDatabase _db, int oldVersion, int newVersion) {
        Log.w(TAG, "Upgrading application's database from version " + oldVersion
                + " to " + newVersion + ", which will destroy all old data!");

        // Destroy old database:
        _db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);

        // Recreate new database:
        onCreate(_db);
    }
}

这是另一个崩溃的地方:

public class EditWords extends Activity {
ListView listViewWords;
EditText editTextNewWord;
Button buttonAddWord;
Button buttonDeleteWord;

DBAdapter myDb;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_edit_words);
    listViewWords = (ListView) findViewById(R.id.listViewWords);
    editTextNewWord = (EditText) findViewById(R.id.editTextNewWord);
    buttonAddWord = (Button) findViewById(R.id.buttonAddWord);
    buttonDeleteWord = (Button) findViewById(R.id.buttonDeleteWord);
    populateListView();
    openDB();

}
private void openDB(){
    myDb = new DBAdapter(this);
    myDb.open();
}

private void populateListView() {
    Cursor cursor = myDb.getAllRows();
    String[] fromFieldNames = new String[] {DBAdapter.KEY_ROWID,DBAdapter.KEY_WORD};
    int[] toViewIDs = new int[]{R.id.editTextNewWord};
    SimpleCursorAdapter myCursorAdapter;
    myCursorAdapter = new SimpleCursorAdapter(getBaseContext(),R.id.listViewWords,cursor,fromFieldNames,toViewIDs,0);
    listViewWords.setAdapter(myCursorAdapter);
}


    public void onClick_AddWord(View v) {
        if(!TextUtils.isEmpty(editTextNewWord.getText().toString())) {
            myDb.insertRow(editTextNewWord.getText().toString());
        }
        populateListView();

    }

}

堆栈跟踪:

03-30 12:13:39.603 8800-9926/com.example.daniel.hangman I/OpenGLRenderer: Initialized EGL, version 1.4
03-30 12:13:39.603 8800-9926/com.example.daniel.hangman W/OpenGLRenderer: Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED, retrying without...
03-30 12:13:42.570 8800-8800/com.example.daniel.hangman D/AndroidRuntime: Shutting down VM
03-30 12:13:42.571 8800-8800/com.example.daniel.hangman E/AndroidRuntime: FATAL EXCEPTION: main
                                                                          Process: com.example.daniel.hangman, PID: 8800
                                                                          android.content.res.Resources$NotFoundException: Resource ID #0x7f070009 type #0x12 is not valid
                                                                              at android.content.res.Resources.loadXmlResourceParser(Resources.java:2779)
                                                                              at android.content.res.Resources.getLayout(Resources.java:1165)
                                                                              at android.view.LayoutInflater.inflate(LayoutInflater.java:421)
                                                                              at android.widget.ResourceCursorAdapter.newView(ResourceCursorAdapter.java:135)
                                                                              at android.widget.CursorAdapter.getView(CursorAdapter.java:285)
                                                                              at android.widget.AbsListView.obtainView(AbsListView.java:2346)
                                                                              at android.widget.ListView.makeAndAddView(ListView.java:1875)
                                                                              at android.widget.ListView.fillDown(ListView.java:702)
                                                                              at android.widget.ListView.fillFromTop(ListView.java:763)
                                                                              at android.widget.ListView.layoutChildren(ListView.java:1684)
                                                                              at android.widget.AbsListView.onLayout(AbsListView.java:2148)
                                                                              at android.view.View.layout(View.java:16630)
                                                                              at android.view.ViewGroup.layout(ViewGroup.java:5437)
                                                                              at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1743)
                                                                              at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1586)
                                                                              at android.widget.LinearLayout.onLayout(LinearLayout.java:1495)
                                                                              at android.view.View.layout(View.java:16630)
                                                                              at android.view.ViewGroup.layout(ViewGroup.java:5437)
                                                                              at android.widget.FrameLayout.layoutChildren(FrameLayout.java:336)
                                                                              at android.widget.FrameLayout.onLayout(FrameLayout.java:273)
                                                                              at android.view.View.layout(View.java:16630)
                                                                              at android.view.ViewGroup.layout(ViewGroup.java:5437)
                                                                              at com.android.internal.widget.ActionBarOverlayLayout.onLayout(ActionBarOverlayLayout.java:493)
                                                                              at android.view.View.layout(View.java:16630)
                                                                              at android.view.ViewGroup.layout(ViewGroup.java:5437)
                                                                              at android.widget.FrameLayout.layoutChildren(FrameLayout.java:336)
                                                                              at android.widget.FrameLayout.onLayout(FrameLayout.java:273)
                                                                              at com.android.internal.policy.PhoneWindow$DecorView.onLayout(PhoneWindow.java:2678)
                                                                              at android.view.View.layout(View.java:16630)
                                                                              at android.view.ViewGroup.layout(ViewGroup.java:5437)
                                                                              at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:2171)
                                                                              at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1931)
                                                                              at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1107)
                                                                              at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6013)
                                                                              at android.view.Choreographer$CallbackRecord.run(Choreographer.java:858)
                                                                              at android.view.Choreographer.doCallbacks(Choreographer.java:670)
                                                                              at android.view.Choreographer.doFrame(Choreographer.java:606)
                                                                              at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:844)
                                                                              at android.os.Handler.handleCallback(Handler.java:739)
                                                                              at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                              at android.os.Looper.loop(Looper.java:148)
                                                                              at android.app.ActivityThread.main(ActivityThread.java:5417)
                                                                              at java.lang.reflect.Method.invoke(Native Method)
                                                                              at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                                                                              at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

最佳答案

您调用:

populateListView();

之前使用“myDb”:

openDB();

初始化“myDb”

关于java - Android 模拟器因 Db 崩溃(找不到错误 - 新手),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43117239/

相关文章:

java - 使用 camel jms 组件从 activemq 卡住消息消费

java - 安卓工作室错误 : cannot resolve symbol in Xml

java.lang.ArrayIndexOutOfBoundsException 对象数组

android - 小型 SVG ImageView 看起来模糊或 "curvy"

java - 内存数据库评估

java - Java 中的父类和子类应该有 2 个数据表吗?

java - 如何要求用户按任意键继续java中的条件?

android - Basic4android 中的启动画面自动移动

Android NDK-JNI-HAL

sql - 为什么查询多于每个实体与少于一些实体更难?