【发布时间】:2013-06-19 07:31:50
【问题描述】:
异常发生在 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();
它的空指针异常.. 我无法解决问题。 请提出解决方案 这是上下文的一些错误 如何解决?
【问题讨论】:
-
可能是数据库名不全。尝试更改“chat.dat”(文件结尾)..它解决了问题吗?
-
只是为了澄清......你的 getWritableDatabase() 方法在哪里?
-
他/她指的是SQLiteOpenHelper.getWritableDatabase()。您是否尝试过获取所获得的 NullPointerException 的堆栈跟踪?
try { /*problem code*/ } catch (Exception e) { e.printStackTrace(); /*or you can log the stacktrace*/ } -
请加入完整的堆栈跟踪。
标签: android sqlite nullpointerexception