Android Studio|使用SqLite实现一个简单的登录注册功能
在Android Studio中,您可以使用SqLite数据库来实现一个简单的登录注册功能。以下是一个简单的例子:
- 创建数据库和表:
public class UserDbHelper extends SQLiteOpenHelper {
private static final String TABLE_NAME = "users";
private static final String COL_ID = "id";
private static final String COL_USERNAME = "username";
private static final String COL_PASSWORD = "password";
public UserDbHelper(Context context) {
super(context, "UserDb.db", null, 1);
}
@Override
public void onCreate(SQLiteDatabase db) {
String createTableStatement = "CREATE TABLE " + TABLE_NAME + " (" + COL_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + COL_USERNAME + " TEXT, " + COL_PASSWORD + " TEXT)";
db.execSQL(createTableStatement);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Implement schema migration logic if needed
}
// Method to add a new user
public boolean addUser(String username, String password) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(COL_USERNAME, username);
cv.put(COL_PASSWORD, password);
long result = db.insert(TABLE_NAME, null, cv);
return result != -1;
}
// Method to check if the user credentials are valid
public boolean checkLogin(String username, String password) {
SQLiteDatabase db = this.getReadableDatabase();
String query = "SELECT * FROM " + TABLE_NAME + " WHERE " + COL_USERNAME + " = '" + username + "' AND " + COL_PASSWORD + " = '" + password + "'";
Cursor cursor = db.rawQuery(query, null);
if (cursor.getCount() > 0) {
cursor.close();
return true;
}
cursor.close();
return false;
}
}
- 在Activity中实现注册和登录逻辑:
public class LoginActivity extends AppCompatActivity {
private EditText editTextUsername;
private EditText editTextPassword;
private Button buttonLogin;
private Button buttonRegister;
private UserDbHelper userDbHelper;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.a
评论已关闭