为什么我在this.getWritableDatabase();, android获取nullpointer异常?

时间:2013-06-19 07:31:50

标签: android sqlite nullpointerexception

SQLiteDatabase上发生异常db = this.getWritableDatabase(); 提供我的databasehandler类

public class DatabaseHandler extends SQLiteOpenHelper {

    // All Static variables
    // Database Version
    private static final int DATABASE_VERSION = 1;


    // Database Name
    private static final String DATABASE_NAME = "chat";

    // Contacts table name
    private static final String TABLE_CHAT = "chat_history";

    // Contacts Table Columns names
    private static final String KEY_ID = "id";
    private static final String KEY_TT = "tt";
    private static final String KEY_TYPE = "type";
    private static final String KEY_MSG = "message";

    public DatabaseHandler(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    // Creating Tables
    @Override
    public void onCreate(SQLiteDatabase db) {
        String CREATE_CHAT_TABLE = "CREATE TABLE " + TABLE_CHAT + "("
            + KEY_ID + " INTEGER PRIMARY KEY," + KEY_TT + " TEXT," + KEY_TYPE + " TEXT,"
            + KEY_MSG + " TEXT" + ")";
        db.execSQL(CREATE_CHAT_TABLE);
    }

    // Upgrading database
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // Drop older table if existed
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_CHAT);

        // Create tables again
        onCreate(db);
    }

    // Adding new contact

    public void addContact(String tt, String type, String msg) {
       SQLiteDatabase db = this.getWritableDatabase();
        System.out.println("tt "+tt);
        System.out.println("msg "+msg);
        System.out.println("type "+type);
        ContentValues values = new ContentValues();
        values.put(KEY_TT, tt); // Contact Name
        values.put(KEY_TYPE, type); // Contact Phone Number
        values.put(KEY_MSG, msg);

        // Inserting Row
        db.insert(TABLE_CHAT, null, values);
        db.close(); // Closing database connection
    }

    // Getting All Contacts
    public List<ChatHistory> getAllContacts(String T) {
        List<ChatHistory> contactList = new ArrayList<ChatHistory>();
        // Select All Query
        System.out.println("database T$$$$$$$$$$$"+T);

        String selectQuery = "SELECT  * FROM " + TABLE_CHAT + " WHERE "+ KEY_TT+"="+"'"+T+"'";

        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);

        // looping through all rows and adding to list
        if (cursor.moveToFirst()) {
            do {
                ChatHistory chatHistory = new ChatHistory();
            chatHistory.setID(Integer.parseInt(cursor.getString(0)));
                chatHistory.settt(cursor.getString(1));
            chatHistory.settype(cursor.getString(2));
            chatHistory.setmsg(cursor.getString(3));
                // Adding contact to list
                contactList.add(chatHistory);
            } while (cursor.moveToNext());
        }

        // return contact list
        return contactList;
    }
}

我一直在这条线上遇到异常  SQLiteDatabase db = this.getWritableDatabase();

其nullpointer异常.. 我无法解决这个问题。 请提出解决方案 这是上下文的一些错误 如何解决?

6 个答案:

答案 0 :(得分:1)

我认为您的数据库尚未创建,因为您正在执行错误的查询。你忘了在最后添加一个分号。

你在做什么:

String CREATE_CHAT_TABLE = "CREATE TABLE " + TABLE_CHAT + "("
        + KEY_ID + " INTEGER PRIMARY KEY," + KEY_TT + " TEXT," + KEY_TYPE + " TEXT,"
        + KEY_MSG + " TEXT" + ")";

使用此代替

String CREATE_CHAT_TABLE = "CREATE TABLE " + TABLE_CHAT + "("
        + KEY_ID + " INTEGER PRIMARY KEY," + KEY_TT + " TEXT," + KEY_TYPE + " TEXT,"
        + KEY_MSG + " TEXT" + ");";

然后卸载您的应用并重试。

答案 1 :(得分:1)

这个问题的两个可能原因,两者都主要是由于inCreate或onUpgrade中的代码使用不当而引起的。

1)在onCreate和onUpgrade两种方法中验证您的SQL查询(您可以通过SQLiteBrowser

使用任何虚拟测试sqlite数据库运行并验证您的书面查询

2)确保你使用与下面相同的方法(如果有的话,不使用外部SQLiteDatabase对象,只使用内部和传递的对象)

public class SqliteHelper extends SQLiteOpenHelper{
    SQLiteDatabase dbHelper;

    @Override
    public void onCreate(SQLiteDatabase db) {
       db.execSQL("YOUR CREATE QUERY"); //don't use dbHelper here 
    }

    @Override
    public void onUpgrade(SQLiteDatabase db) {
       db.execSQL("YOUR UPGRADE QUERY"); //don't use dbHelper here
    }

    public void open() throws SQLExceptions {
      dbHelper = this.getWritableDatabase();
    }

    public void close(){
      dbHelper.close();
    }

    public long insert(...){
      open();
      //your access is here through dbHelper
      close();
    }

}

答案 2 :(得分:1)

如果您正在使用Fragment,请将onCreate View内的上下文初始化为

DbProgram dbProgram;
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {    
        View view = inflater.inflate(R.layout.activity_main, container, false);
        **dbProgram = new DbProgram(getActivity());** // Context here solves your problem............
        return view;
    }

如果您不使用Fragment,请初始化context方法内的onCreate

MarketAppDbAdapter db;
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        **db = new MarketAppDbAdapter(MainActivity.this);**// Your problem solves here...........
    }

答案 3 :(得分:0)

不要在DatabaseHandler类中执行与查询相关的工作。保留它仅用于打开,关闭,升级,创建相关工作。使用synchronized方法调用并抛出显式异常。

作为线索尝试这样:

    /**
     * open the db
     * @return this
     * @throws SQLException
     * return type: DatabaseHandler
     */
    public synchronized DatabaseHandler open() throws SQLException 
    {
        if(db == null || !db.isOpen())
            this.db = getWritableDatabase();
        return this;
    }

然后为您的rawquery定义返回Cursor对象的方法:

public synchronized Cursor rawQuery(String sql, String[] args) throws SQLException{
        if(db == null || !db.isOpen())
            this.open();
        return db.rawQuery(sql, args);
    }

然后在您要执行选择查询相关工作的类中执行:

protected DatabaseHandler dbHandler;
dbHandler = DatabaseHandler.getInstance(activity.getApplicationContext());
String selectQuery = "SELECT  * FROM " + TABLE_CHAT + " WHERE "+ KEY_TT+"="+"'"+T+"'";
Cursor r = dbHandler.rawQuery(selectQuery, null);

相关的循环代码将低于它。

希望它会有所帮助!

答案 4 :(得分:0)

不是在addContact方法中创建数据库对象,而是在DatabaseHandler类的onCreate方法中创建它,

public class DatabaseHandler extends SQLiteOpenHelper {

    SQLiteDatabase db ;

    @Override
    public void onCreate(SQLiteDatabase db) {
        //write you code here..
         this.db=db;

        }


}

答案 5 :(得分:-1)

我认为并且请记住,我不是专家,你使用的是SQLiteopenhelper类,而不是实习。我认为它只应扩展为“帮助类来管理数据库创建和版本管理。”
所以我建议创建一个单独的类,使用您的databaseshandler类来获取可写数据库,并为您的数据库操作添加方法。
沿着相同的路线,您可以创建建议的类,但将当前类作为内部类放在其中。 (只需确保将CRUD方法移动到新的clas