当我期待 SQLiteOpenHelper 的 onCreate() 回调时,我遇到了问题。我已经解决了许多相关问题,并尝试实施该建议,但问题仍然存在。
问题是:当我调用 getWritableDatabase() 时出现 NullPointerException。我试图把登录放在onOpen()、onUpgrade()、onCreate()。
我也使用了断点,但除了异常之外什么也没有。
日志如下。12-08 22:05:47.193: D/@gaurav(417): java.lang.NullPointerException 12-08 22:05:47.193: D/@gaurav(417): at com.gaurav.contactmanager.DataBaseHelper.addContact( DataBaseHelper.java:63) 12-08 22:05:47.193: D/@gaurav(417): at com.gaurav.contactmanager.ContactManager.onClick(ContactManager.java:95) 12-08 22:05:47.193: D /@gaurav(417): 在 android.view.View.performClick(View.java:2485) 12-08 22:05:47.193: D/@gaurav(417): 在 android.view.View$PerformClick.run( View.java:9080) 12-08 22:05:47.193: D/@gaurav(417): 在 android.os.Handler.handleCallback(Handler.java:587) 12-08 22:05:47.193: D/@ gaurav(417): 在 android.os.Handler.dispatchMessage(Handler.java:92) 12-08 22:05:47.193: D/@gaurav(417): 在 android.os.Looper.loop(Looper.java: 123) 12-08 22:05:47.193: D/@gaurav(417): 在 android.app.ActivityThread。
代码:DataBaseHelper.java
package com.gaurav.contactmanager;
import java.util.ArrayList;
import java.util.List;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DataBaseHelper extends SQLiteOpenHelper {
// All Static variables
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "contactsManager";
// Contacts table name
private static final String TABLE_CONTACTS = "contacts";
// Contacts Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_NAME = "name";
private static final String KEY_PH_NO = "phone_number";
public DataBaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
Log.d("@gaurav", "database object created but not database...");
}
// Creating Tables
@Override
public void onCreate(SQLiteDatabase db) {
Log.d("@gaurav", "database creating...");
String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("
+ KEY_ID + " INTEGER ," + KEY_NAME + " TEXT," + KEY_PH_NO
+ " TEXT PRIMARY KEY" + ")"; // TEXT PRIMARY KEY
db.execSQL(CREATE_CONTACTS_TABLE);
Log.d(ContactManagerUtil.TAG_EXIT, ContactManagerUtil.getInstance().getMehtodName());
}
// Upgrading database
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.d("@gaurav", "database upgrading...");
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);
// Create tables again
onCreate(db);
Log.d(ContactManagerUtil.TAG_EXIT, ContactManagerUtil.getInstance().getMehtodName());
}
/**
* All CRUD(Create, Read, Update, Delete) Operations
*/
SQLiteDatabase db;
// Adding new contact
void addContact(MyContact contact) {
Log.d(ContactManagerUtil.TAG_ENTER, ContactManagerUtil.getInstance().getMehtodName());
db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, contact.getName()); // Contact Name
values.put(KEY_PH_NO, contact.getNumber()); // Contact Phone
// Inserting Row
db.insert(TABLE_CONTACTS, null, values);
Log.d("@gaurav", "Insert completed..");
db.close(); // Closing database connection
}
public void onOpen(SQLiteDatabase db) {
Log.d("@gaurav", "onOpen database");
};
// Getting single contact
MyContact getContact(int id) {
Log.d("@gaurav", "getting contact");
db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID,
KEY_NAME, KEY_PH_NO }, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
MyContact contact = new MyContact(
Integer.parseInt(cursor.getString(0)), cursor.getString(1),
cursor.getString(2));
// return contact
Log.d("@gaurav", "got contact, now returning ...");
return contact;
}
// Getting All Contacts
public List<MyContact> getAllContacts() {
Log.d(ContactManagerUtil.TAG_ENTER, ContactManagerUtil.getInstance().getMehtodName());
List<MyContact> contactList = new ArrayList<MyContact>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_CONTACTS;
db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
MyContact contact = MyContact.getInstance();
contact.setId(Integer.parseInt(cursor.getString(0)));
contact.setName(cursor.getString(1));
contact.setNumber(cursor.getString(2));
// Adding contact to list
contactList.add(contact);
} while (cursor.moveToNext());
}
Log.d(ContactManagerUtil.TAG_EXIT, ContactManagerUtil.getInstance().getMehtodName());
// return contact list
return contactList;
}
// Updating single contact
public int updateContact(MyContact contact) {
Log.d(ContactManagerUtil.TAG_ENTER, ContactManagerUtil.getInstance().getMehtodName());
db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, contact.getName());
values.put(KEY_PH_NO, contact.getNumber());
Log.d(ContactManagerUtil.TAG_EXIT, ContactManagerUtil.getInstance().getMehtodName());
// updating row
return db.update(TABLE_CONTACTS, values, KEY_ID + " = ?",
new String[] { String.valueOf(contact.getId()) });
}
// Deleting single contact
public void deleteContact(MyContact contact) {
Log.d(ContactManagerUtil.TAG_ENTER, ContactManagerUtil.getInstance().getMehtodName());
db = this.getWritableDatabase();
db.delete(TABLE_CONTACTS, KEY_ID + " = ?",
new String[] { String.valueOf(contact.getId()) });
db.close();
Log.d(ContactManagerUtil.TAG_EXIT, ContactManagerUtil.getInstance().getMehtodName());
}
// Getting contacts Count
public int getContactsCount() {
Log.d(ContactManagerUtil.TAG_ENTER, ContactManagerUtil.getInstance().getMehtodName());
String countQuery = "SELECT * FROM " + TABLE_CONTACTS;
db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
cursor.close();
Log.d(ContactManagerUtil.TAG_EXIT, ContactManagerUtil.getInstance().getMehtodName());
// return count
return cursor.getCount();
}
}
这是发生异常的方法,可能是因为 db 为空,因为 onCreate() 没有自动调用。
调用完成的活动代码:
public void onClick(View v) {
Log.d(TAG_ENTER, getMehtodName());
switch (v.getId()) {
case R.id.submit:
try {
if (contact == null) {
contact = MyContact.getInstance();
}
contact.setId(id++);
contact.setName(name.getText().toString());
contact.setNumber(number.getText().toString());
if (dbHandler != null) {
dbHandler.addContact(contact);
} else {
dbHandler = new DataBaseHelper(getApplicationContext());
dbHandler.addContact();
}
} catch (Exception ex) {
Log.d("@gaurav", "Problem while cerating contact", ex);
Log.wtf("@gaurav", "what ...... :)");
} finally {
contact.flush();
name.setText("");
number.setText("");
}
break;
case R.id.view:
// Intent intent = new Intent(this, ContactView.class);
// startActivity(intent);
break;
default:
break;
}
Log.d(TAG_EXIT, getMehtodName());
}