简体   繁体   English

Android开发-数据库插入时出现空指针异常

[英]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. 用户单击联系人,将显示基于联系人ID与该联系人相关的注释条目。 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. 我是编程的新手,过去一个半星期一直在教自己使用android,所以这可能真的很简单。 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. 我一直在网上闲逛,经常来Stack Overflow检查答案,但似乎找不到任何东西。 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. 另外,我不确定需要什么代码,因此我将仅发布表单活动和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: 这是我的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;
    }
}

And here is the Trace from the Eclipse Debug: 这是Eclipse调试中的跟踪:

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。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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