我正在创建一个具有“用户登录”页面的Android应用程序。我尝试使用SQlite,这是我的代码:
package tsu.ccs.capstone;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DBUser {
public static final String KEY_ROWID = "_id";
public static final String KEY_USERNAME= "username";
public static final String KEY_PASSWORD = "password";
private static final String TAG = "DBAdapter";
private static final String DATABASE_NAME = "usersdb";
private static final String DATABASE_TABLE = "users";
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_CREATE =
"create table users (_id integer primary key autoincrement, "
+ "username text not null, "
+ "password text not null);";
private Context context = null;
private DatabaseHelper DBHelper;
private SQLiteDatabase db;
public DBUser(Context ctx)
{
this.context = ctx;
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 database from version " + oldVersion
+ " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS users");
onCreate(db);
}
}
public void open() throws SQLException
{
db = DBHelper.getWritableDatabase();
}
public void close()
{
DBHelper.close();
}
public long AddUser(String username, String password)
{
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_USERNAME, "p");
initialValues.put(KEY_PASSWORD, "p");
return db.insert(DATABASE_TABLE, null, initialValues);
}
public boolean Login(String username, String password) throws SQLException
{
Cursor mCursor = db.rawQuery("SELECT * FROM " + DATABASE_TABLE + " WHERE username=? AND password=?", new String[]{username,password});
if (mCursor != null) {
if(mCursor.getCount() > 0)
{
return true;
}
}
return false;
}
}
如您所见,我的布局中有用户名和密码字段的InitialValue。 我的问题是我想给用户一个选项来更改我设置的默认用户名和密码。简单地说,只需覆盖InitialValues,然后保存我的数据库。
任何人都可以帮助我,我只是开始进行android编程而且我迷失了这个。
答案 0 :(得分:0)
Java不支持默认参数值,因此您必须重载AddUser函数。
public long AddUser(){
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_USERNAME, "p");
initialValues.put(KEY_PASSWORD, "p");
return db.insert(DATABASE_TABLE, null, initialValues);
}
这将使用您的默认用户名和密码创建用户。
public long AddUser(String username, String password){
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_USERNAME, username);
initialValues.put(KEY_PASSWORD, password);
return db.insert(DATABASE_TABLE, null, initialValues);
}
此功能将使用用户提供的值创建用户。