简体   繁体   中英

Android Development - Null Pointer Exception on Database Insert

OK, well I've been working on a simple app that allows users to save notes to contacts. It lists the contacts from the phone. User clicks on a contact and the notes entries that are related to the contact based on the contact ID are shown. The user can then add a new note by Menu>Add note. I can get all the way through the app but it wont save the data entered in the form to the database. When I try to save, I get a Null Pointer Exception. Nothing crashes, it just returns to the previous activity and doesn't do anything. I am kind of new to programming and have been teaching myself android for the past week and a half, so it could be something really simple. I have been digging around the web and frequently come to Stack Overflow to check for answers but cant seem to find anything on this one. Also, I'm not sure what code is needed so I'm just going to post the code for my form activity and my dbadapter. Thanks in advance for any help!

This is the activity used to enter the data:

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();
            }
        });
    }


}

This is my Db adapter class:

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;
    }
}

And here is the Trace from the 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]  

看起来您在任何地方都没有调用MyDbAdapter.open(),因此在createNote()中mDb为null。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM