onCreate()在调用getWritableDatabase()时没有收到回调

时间:2012-12-08 18:15:34

标签: android sqlite nullpointerexception

当我期待对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.main(ActivityThread.java:3683) 12-08 22:05:47.193:D / @ gaurav(417):at java.lang.reflect.Method.invokeNative(Native Method) 12-08 22:05:47.193:D / @gaurav(417):at java.lang.reflect.Method.invoke(Method.java:507) 12-08 22:05:47.193:D / @gaurav(417):at com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:839) 12-08 22:05:47.193:D / @ gaurav(417):at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597) 12-08 22:05:47.193:D / @ gaurav(417):at dalvik.system.NativeStart.main(Native Method)

代码: 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为null,因为不会自动调用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());
    } 

1 个答案:

答案 0 :(得分:0)

  

这是第63行:

Log.d(ContactManagerUtil.TAG_ENTER, 
      ContactManagerUtil.getInstance().getMehtodName());

Logcat声明ContactManagerUtil.getInstance()返回null ...您应该在getInstance()方法内部开始调试。此外,您在此方法的名称中输入了拼写错误:getMehtodName()

(如果您仍需要帮助,请发布ContactManagerUtil.getInstance()。)