Android开发 - 数据库插入的空指针异常

时间:2011-03-16 02:34:05

标签: java android sql sqlite

好的,我一直在开发一个简单的应用程序,允许用户将笔记保存到联系人。它列出了手机中的联系人。用户单击联系人,并显示基于联系人ID与联系人相关的备注条目。然后,用户可以通过菜单>添加备注添加新备忘。我可以通过应用程序获得所有内容,但它不会将表单中输入的数据保存到数据库中。当我尝试保存时,我得到一个空指针异常。什么都没有崩溃,它只是返回到之前的活动,并没有做任何事情。我对编程很陌生,并且在过去的一周半里一直在教自己的android,所以它可能非常简单。我一直在网上挖掘,经常来到Stack Overflow来检查答案,但似乎无法找到任何关于这个的东西。此外,我不确定需要什么代码,所以我只是发布我的表单活动和我的dbadapter的代码。在此先感谢您的帮助!

这是用于输入数据的活动:

package com.onyx.formapp23;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.onyx.formapp23.MyDbAdapter;

public class FormsNewNote extends Activity {
    String mIntentString;
    int contactId;
    EditText contactIdEdit, titleEdit, bodyEdit;
    long dateTimeValue;
    Button submitBtn, discardBtn;
    private MyDbAdapter db = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.forms_newnote);
        Bundle extras = getIntent().getExtras();
        mIntentString = extras.getString("contactId");
        db = new MyDbAdapter(this);
        contactIdEdit = (EditText) findViewById(R.id.noteFormContactId);
        contactIdEdit.setText(mIntentString);
        contactId = Integer.parseInt(mIntentString);
        titleEdit = (EditText) findViewById(R.id.noteFormTitle);
        bodyEdit = (EditText) findViewById(R.id.noteFormBody);
        dateTimeValue = java.lang.System.currentTimeMillis();
        submitBtn = (Button) findViewById(R.id.noteFormSave);
        discardBtn = (Button) findViewById(R.id.noteFormDiscard);
        submitBtn.setOnClickListener(new OnClickListener(){
            @Override
            public void onClick(View v) {
                try{
                    String titleInsert = titleEdit.getText().toString();
                    String bodyInsert = bodyEdit.getText().toString();
                    db.createNote(contactId, titleInsert, bodyInsert,  dateTimeValue);
                } catch (Exception e) {
                    String titleInsert = titleEdit.getText().toString();
                    String bodyInsert = bodyEdit.getText().toString();
                    e.printStackTrace();
                    Context context = getApplicationContext();
                    CharSequence text = "SQL Exception Thrown: " + e + "\nTitle: " + titleInsert + "\nBody: " + bodyInsert;
                    int duration = Toast.LENGTH_SHORT;
                    Toast toast = Toast.makeText(context, text, duration);
                    toast.show();
                }
                finish();
            }
        });
    }


}

这是我的Db适配器类:

package com.onyx.formapp23;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class MyDbAdapter {
    private DatabaseHelper mDbHelper;
    private SQLiteDatabase mDb;

    public static final String KEY_TITLE = "title";
    public static final String KEY_BODY = "body";
    public static final String KEY_CONTACTID = "contactId";
    public static final String KEY_ROWID = "_id";
    public static final String KEY_DATETIME = "datetime";
    private static final String TAG = "MyDbAdapter";
    private static final String DATABASE_CREATE =
        "create table contactNotes (_id integer primary key autoincrement, contactId integer, title text not null, body text not null, datetime long);";

    private static final String DATABASE_NAME = "OnyxDatabase";
    private static final String DATABASE_TABLE = "contactNotes";
    private static final int DATABASE_VERSION = 1;

    private final Context mCtx;

    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);
        }
        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
                    + newVersion + ", which will destroy all old data");
            db.execSQL("DROP TABLE IF EXISTS notes");
            onCreate(db);
        }
    }
    public MyDbAdapter(Context ctx) {
        this.mCtx = ctx;
    }
    public MyDbAdapter open() throws SQLException {
        mDbHelper = new DatabaseHelper(mCtx);
        mDb = mDbHelper.getWritableDatabase();
        return this;
    }
    public void close() {
        mDbHelper.close();
    }
    public long createNote(int contactId, String title, String body, long datetime) {
        ContentValues initialValues = new ContentValues();
        initialValues.put(KEY_CONTACTID, contactId);
        initialValues.put(KEY_TITLE, title);
        initialValues.put(KEY_BODY, body);
        initialValues.put(KEY_DATETIME, datetime);
        return mDb.insertOrThrow(DATABASE_TABLE, null, initialValues);
    }

    public void createNote2(int contactId, String title, String body) {
        mDb.execSQL("insert into " + DATABASE_TABLE + " (" + KEY_CONTACTID + ", " + KEY_TITLE + ", " + KEY_BODY + ", " + KEY_DATETIME + ") values(" + contactId + ", " +
                title + ", " + body + ", " + java.lang.System.currentTimeMillis() + ");");
    }

    public boolean deleteNote(long rowId) {
        return mDb.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0;
    }
    public Cursor fetchAllNotes() {
        return mDb.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_TITLE, KEY_CONTACTID,
                KEY_BODY, KEY_DATETIME}, null, null, null, null, null);
    }
    public Cursor fetchNotesForContact(String contactId) {
        return mDb.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_CONTACTID, KEY_TITLE, KEY_BODY, KEY_DATETIME}, KEY_CONTACTID + " = " + contactId, null, null, null, new String (KEY_DATETIME + 
                " COLLATE LOCALIZED ASC"));
    }
    public Cursor fetchNote(long rowId) throws SQLException {
        Cursor mCursor =
            mDb.query(true, DATABASE_TABLE, new String[] {KEY_ROWID,
                    KEY_TITLE, KEY_BODY}, KEY_ROWID + "=" + rowId, null,
                    null, null, null, null);
        if (mCursor != null) {
            mCursor.moveToFirst();
        }
        return mCursor;
    }
    public boolean updateNote(long rowId, String title, String body) {
        ContentValues args = new ContentValues();
        args.put(KEY_TITLE, title);
        args.put(KEY_BODY, body);

        return mDb.update(DATABASE_TABLE, args, KEY_ROWID + "=" + rowId, null) > 0;
    }
}

这是来自Eclipse Debug的跟踪:

Thread [<1> main] (Suspended (entry into method createNote in MyDbAdapter)) 
    MyDbAdapter.createNote(int, String, String, long) line: 58  
    FormsNewNote$1.onClick(View) line: 43   
    Button(View).performClick() line: 2447  
    View$PerformClick.run() line: 9025  
    ViewRoot(Handler).handleCallback(Message) line: 587 
    ViewRoot(Handler).dispatchMessage(Message) line: 92 
    Looper.loop() line: 123 
    ActivityThread.main(String[]) line: 4628    
    Method.invokeNative(Object, Object[], Class, Class[], Class, int, boolean) line: not available [native method]  
    Method.invoke(Object, Object...) line: 521  
    ZygoteInit$MethodAndArgsCaller.run() line: 870  
    ZygoteInit.main(String[]) line: 628 
    NativeStart.main(String[]) line: not available [native method]  

1 个答案:

答案 0 :(得分:11)

看起来你不是在调用MyDbAdapter.open(),因此在createNote()中mDb为null。