其实我正在尝试实现简单的SQLiteDatabase程序。 MainActivity类没有任何问题。当我试图调用DBUserAdapter类方法时,我的应用程序正在终止。
MainActivity
btninsert = (Button)findViewById(R.id.insertbtn);
btninsert.setOnClickListener(insertListener);
OnClickListener insertListener = new OnClickListener() {
@Override
public void onClick(View v) {
username = txtUserName.getText().toString();
password = txtPassword.getText().toString();
DBUserAdapter dbUser = new DBUserAdapter(getApplicationContext());
dbUser.open();
if(username.length()>0||password.length()>0){
if(dbUser.AddUser(username, password)){
Toast.makeText(getApplicationContext(), "User Successfully Inserted", Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(getApplicationContext(), "User Already Existed in Records", Toast.LENGTH_SHORT).show();
}
}else {
Toast.makeText(getApplicationContext(), "Enter The Values", Toast.LENGTH_SHORT).show();
}
}
};
DBUserAdapter类:
public class DBUserAdapter {
public static final String KEY_ROWID = "_id";
public static final String KEY_USERNAME = "username";
public static final String KEY_PASSWORD = "password";
public static final String TAG = "DBAdapter";
public static final String DATABASE_TABLE = "users";
public static final String DATABASE_NAME = "userdb";
public static final int DATABASE_VERSION = 1;
public static final String DATABASE_CREATE = "CREATE TABLE "+DATABASE_TABLE+" ("+KEY_ROWID+ " INTEGER PRIMARY KEY , "+
KEY_USERNAME+ " TEXT,"+KEY_PASSWORD+"TEXT)";
private Context context;
private static SQLiteDatabase db;
private static DatabaseHelper DBHelper;
public DBUserAdapter(Context c){
this.context = c;
DBHelper = new DatabaseHelper(context);
}
private static class DatabaseHelper extends SQLiteOpenHelper{
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(DATABASE_CREATE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrading the Database from Version"+oldVersion+"to"+newVersion+",which will gestroy all old data");
db.execSQL("DROP TABLE IF EXISTS"+DATABASE_TABLE);
onCreate(db);
}
}
public void open() throws SQLException{
db = DBHelper.getWritableDatabase();
}
public void close(){
DBHelper.close();
}
public boolean AddUser(String username, String password){
Cursor mCursor = db.rawQuery("SELECT * FROM"+DATABASE_TABLE+"WHERE username = ?", new String[]{username});
if(mCursor != null){
if(mCursor.getCount()>0){
return false;
}
}
ContentValues values = new ContentValues();
values.put(KEY_USERNAME, username);
values.put(KEY_PASSWORD, password);
db.insert(DATABASE_TABLE, null, values);
return true;
}
}
我们将不胜感激。感谢...
这是LogCat ..
02-11 01:17:39.484: I/Process(1085): Sending signal. PID: 1085 SIG: 9
02-11 01:18:49.554: D/gralloc_goldfish(1138): Emulator without GPU emulation detected.
02-11 01:18:53.444: D/AndroidRuntime(1138): Shutting down VM
02-11 01:18:53.444: W/dalvikvm(1138): threadid=1: thread exiting with uncaught exception (group=0xb4a2cba8)
02-11 01:18:53.464: E/AndroidRuntime(1138): FATAL EXCEPTION: main
02-11 01:18:53.464: E/AndroidRuntime(1138): Process: com.siva.sqlite_app, PID: 1138
02-11 01:18:53.464: E/AndroidRuntime(1138): java.lang.NullPointerException
02-11 01:18:53.464: E/AndroidRuntime(1138): at com.siva.sqlite_app.MainActivity$5.onClick(MainActivity.java:142)
02-11 01:18:53.464: E/AndroidRuntime(1138): at android.view.View.performClick(View.java:4438)
02-11 01:18:53.464: E/AndroidRuntime(1138): at android.view.View$PerformClick.run(View.java:18422)
02-11 01:18:53.464: E/AndroidRuntime(1138): at android.os.Handler.handleCallback(Handler.java:733)
02-11 01:18:53.464: E/AndroidRuntime(1138): at android.os.Handler.dispatchMessage(Handler.java:95)
02-11 01:18:53.464: E/AndroidRuntime(1138): at android.os.Looper.loop(Looper.java:136)
02-11 01:18:53.464: E/AndroidRuntime(1138): at android.app.ActivityThread.main(ActivityThread.java:5017)
02-11 01:18:53.464: E/AndroidRuntime(1138): at java.lang.reflect.Method.invokeNative(Native Method)
02-11 01:18:53.464: E/AndroidRuntime(1138): at java.lang.reflect.Method.invoke(Method.java:515)
02-11 01:18:53.464: E/AndroidRuntime(1138): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
02-11 01:18:53.464: E/AndroidRuntime(1138): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
02-11 01:18:53.464: E/AndroidRuntime(1138): at dalvik.system.NativeStart.main(Native Method)
02-11 01:18:56.244: I/Process(1138): Sending signal. PID: 1138 SIG: 9
答案 0 :(得分:0)
我已经发布了我之前使用过的DbAdapter,它工作得很好只是看看你会对如何使用SQLITE数据库有所了解
/ ** *简单说明数据库访问助手类。定义基本的CRUD操作 *用于记事本示例,并且能够列出所有音符以及 *检索或修改特定注释。 * *从本教程的第一个版本开始,这已经改进了 *添加更好的错误处理,并使用返回Cursor而不是 *使用内部类的集合(可扩展性较低而不是 * 推荐的)。 * /
public class DbAdapter {
public static final String KEY_ID = "uid";
public static final String USER_NAME = "username";
public static final String USER_TYPE = "usertype";
public static final String KEY_ACCESSKEY = "accesskey";
private static final String TAG = "DbAdapter";
private DatabaseHelper mDbHelper;
private SQLiteDatabase mDb;
/**
* Database creation sql statement
*/
private static final String DATABASE_CREATE =
"create table login (uid integer primary key, " + "username varchar(30) not null,"
+ "usertype integer not null, accesskey varchar(10) not null);";
private static final String DATABASE_NAME = "routetracker";
private static final String DATABASE_TABLE = "login";
private static final int DATABASE_VERSION = 4;
private final Context mCtx;
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(DATABASE_CREATE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS login");
onCreate(db);
}
}
/**
* Constructor - takes the context to allow the database to be
* opened/created
*
* @param ctx the Context within which to work
*/
public DbAdapter(Context ctx) {
this.mCtx = ctx;
}
/**
* Open the notes database. If it cannot be opened, try to create a new
* instance of the database. If it cannot be created, throw an exception to
* signal the failure
*
* @return this (self reference, allowing this to be chained in an
* initialization call)
* @throws SQLException if the database could be neither opened or created
*/
public DbAdapter open() throws SQLException {
mDbHelper = new DatabaseHelper(mCtx);
mDb = mDbHelper.getWritableDatabase();
Log.i(TAG, "Database Opened");
return this;
}
public void close() {
Log.i(TAG, "Database Closed");
mDbHelper.close();
}
/**
* Create a new note using the title and body provided. If the note is
* successfully created return the new rowId for that note, otherwise return
* a -1 to indicate failure.
*
* @param title the title of the note
* @param body the body of the note
* @return rowId or -1 if failed
*/
public long createLogin(int uid,String userName,int userType,String accessKey) {
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_ID, uid);
initialValues.put(USER_NAME, userName);
initialValues.put(USER_TYPE, userType);
initialValues.put(KEY_ACCESSKEY, accessKey);
return mDb.insert(DATABASE_TABLE, null, initialValues);
}
/**
* Delete the note with the given rowId
*
* @param rowId id of note to delete
* @return true if deleted, false otherwise
*/
public boolean deleteRow(long rowId) {
return mDb.delete(DATABASE_TABLE, KEY_ID + "=" + rowId, null) > 0;
}
/**
* Delete all the Rows
*
* @return true if deleted, false otherwise
*/
public boolean deleteAllRow() {
mDb.delete(DATABASE_TABLE, null, null);
return true;
}
/**
* Return a Cursor over the list of all notes in the database
*
* @return Cursor over all notes
*/
public Cursor fetchAllRow() {
return mDb.query(DATABASE_TABLE, new String[] {KEY_ID,USER_NAME,USER_TYPE,KEY_ACCESSKEY}, null, null, null, null, null);
}
/**
* Return a Cursor positioned at the note that matches the given rowId
*
* @param rowId id of note to retrieve
* @return Cursor positioned to matching note, if found
* @throws SQLException if note could not be found/retrieved
*/
public Cursor fetchRow(long rowId) throws SQLException {
Cursor mCursor =
mDb.query(true, DATABASE_TABLE, new String[] {KEY_ID, USER_NAME, USER_TYPE,
KEY_ACCESSKEY}, KEY_ID + "=" + rowId, null,
null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
/**
* Update the Login using the details provided. The note to be updated is
* specified using the rowId, and it is altered to use the accessKey
* values passed in
*
* @param rowId id of note to update
* @param accessKey value to set note title to
* @return true if the note was successfully updated, false otherwise
*/
public boolean updateRow(int uid,String userName,int userType,String accessKey) {
ContentValues args = new ContentValues();
args.put(KEY_ID, uid);
args.put(USER_NAME, userName);
args.put(USER_TYPE, userType);
args.put(KEY_ACCESSKEY, accessKey);
return mDb.update(DATABASE_TABLE, args, KEY_ID + "=" + uid, null) > 0;
}
}