1

异常发生在 SQLiteDatabase db = this.getWritableDatabase(); 提供我的数据库处理程序类

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

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

4

6 回答 6

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" + ");";

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

于 2013-06-19T08:15:53.990 回答
1

这个问题的两个可能原因,它们都主要是因为 onCreate 或 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();
    }

}
于 2014-12-14T08:53:49.370 回答
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 初始化contextinsideonCreate方法

MarketAppDbAdapter db;
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        **db = new MarketAppDbAdapter(MainActivity.this);**// Your problem solves here...........
    }
于 2017-08-09T11:23:41.700 回答
0

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

作为线索尝试这样:

    /**
     * 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);

相关的循环代码将在其下方。

希望它会有所帮助!

于 2013-06-19T08:06:28.973 回答
0

与其在 addContact 方法中创建数据库对象,不如在 DatabaseHandler 类的 onCreate 方法中创建它,

public class DatabaseHandler extends SQLiteOpenHelper {

    SQLiteDatabase db ;

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

        }


}
于 2013-06-19T08:15:08.207 回答
-1

我认为并记住,我不是专家,您使用 SQLiteopenhelper 类的用途超过了它的实习用途。我相信它应该只扩展为“管理数据库创建和版本管理的辅助类”。
所以我建议创建一个单独的类,使用您的数据库处理程序类来获取您的可写数据库并将用于您的数据库操作的方法放在那里。
同样,您可以创建建议的类,但将当前类作为内部类放入其中。(只要确保将 CRUD 方法移动到新的类

于 2013-06-19T08:10:30.063 回答