0

我试图将以下字符串保存到数据库中:类别、标题、正文,但是每当我尝试执行saveState()方法时都会收到 NullPointerException。谁能帮助我?

//exectued when I press Save button
public void onClickSave(View v) {
    saveState();
}

// fire up creation

private void saveState() {
    String title = mJokeTitle.getText().toString();
    String body = mJokeBody.getText().toString();

    long id = mDbHelper.createJoke(enteredCat, title, body);

}

我的数据库架构

public class NotesDbAdapter {

public static final String KEY_TITLE = "title";
public static final String KEY_BODY = "body";
public static final String KEY_CATEGORY = "category";

public static final String KEY_ROW_ID = "_id";

private static final String TAG = "NotesDbAdapter";
private DatabaseHelper mDbHelper;
private SQLiteDatabase mDb;

private static final String DATABASE_NAME = "my_database";
private static final String DATABASE_TABLE = "jokes";
private static final int DATABASE_VERSION = 3;

private static final String DATABASE_CREATE =
        "create table " + DATABASE_TABLE + " (_id integer primary key autoincrement, "
        + "title text not null, body text not null, category text not null unique);";

public long createJoke(String category, String title, String body) {
    ContentValues initialValues = new ContentValues();
    initialValues.put(KEY_CATEGORY, category);
    initialValues.put(KEY_TITLE, title);
    initialValues.put(KEY_BODY, body);

    // return rowId if successful, otherwise -1
    return mDb.insert(DATABASE_TABLE, null, initialValues);
}
4

3 回答 3

0

mDbHelper 是 null 就是这种情况

于 2013-09-04T10:53:49.833 回答
0
private void saveState() {
    String title ="";
    String body="";
   if(mJokeTitle.getText()!=nll){
      title = mJokeTitle.getText().toString();
   }else{
       System.out.println("mJokeTitle.getText() value is null you need to look into  why this value is Null");  
   }

   if( mJokeBody.getText()!=nll){
      body = mJokeBody.getText().toString();
   }else{
       System.out.println(" mJokeBody.getText() value is null you need to look into why this value is Null");  
   }       
    if(mDbHelper!=null){
        long id = mDbHelper.createJoke(enteredCat, title, body);
    }else{
            System.out.println("mDbHelper value is null you need to look into why this value is Null");  
    }

}

于 2013-09-04T10:46:50.023 回答
0

您应该提供更多代码,其中提供的代码未初始化您的 saveState() 方法中的变量“mDbHelper”。如果存在第二个变量“enteredCat”,我们无法知道它是否已初始化。

于 2013-09-04T10:47:46.580 回答