已经实现web服务器安卓程序作为web服务端的技术实现:AndServer 实现登录权限拦截-CSDN博客
现在需要和正常web项目类似,那么就需要操作数据库
一般web项目都是选择较为重型的数据库如MySQL,SQL server等
这里是安卓项目,我目前采用的是较为轻量级的sqllite,并且有现成的ORM框架
那么开始,首先增加依赖:
这里我使用版本是2.3 你可以酌情升级 因为我的安卓版本比较低 如果使用高版本会有依赖问题
在AndroidManifest.xml中增加:
MyApplication代码如下:
public class MyApplication extends Application {
private static MyApplication instance;
@Override
public void onCreate() {
super.onCreate();
instance = this;
Log.d("MyApplication", "执行");
ActivityUtils.init(this); // 初始化工具类
}
public static MyApplication getInstance() {
if (instance == null) {
throw new IllegalStateException("Application is not initialized yet.");
}
return instance;
}
public static Context getContext() {
return getInstance().getApplicationContext();
}
}
这里增加MyApplicaition的主要原因是Room初始化Database时需要使用到context:
DatabaseClient代码,新建数据库及名称:
public class DatabaseClient {
private static DatabaseClient instance;
private final AppDatabase appDatabase;
private DatabaseClient(Context context) {
appDatabase = Room.databaseBuilder(context.getApplicationContext(), AppDatabase.class, "MyDatabase").build();
}
public static synchronized DatabaseClient getInstance(Context context) {
if (instance == null) {
instance = new DatabaseClient(context);
}
return instance;
}
public AppDatabase getAppDatabase() {
return appDatabase;
}
}
ActivityUtils代码,工具类,方便可以在controller中访问context:
public class ActivityUtils {
private static Activity currentActivity;
private static List<Activity> activityList = new ArrayList<>();
public static void init(Application application) {
application.registerActivityLifecycleCallbacks(new Application.ActivityLifecycleCallbacks() {
@Override
public void onActivityCreated(@NonNull Activity activity, @Nullable Bundle bundle) {
}
@Override
public void onActivityStarted(Activity activity) {
currentActivity = activity;
}
@Override
public void onActivityResumed(Activity activity) {
currentActivity = activity;
}
@Override
public void onActivityPaused(Activity activity) {
currentActivity = null;
}
@Override
public void onActivityStopped(Activity activity) {
currentActivity = null;
}
@Override
public void onActivityDestroyed(Activity activity) {
activityList.remove(activity);
}
@Override
public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
// No implementation needed
}
});
}
public static Activity getCurrentActivity() {
return currentActivity;
}
public static Context getCurrentActivityContext() {
if (currentActivity != null) {
return currentActivity.getApplicationContext();
}
return null;
}
}
实体类和数据库操作代码:
@Entity(tableName = "users")
public class User {
// @PrimaryKey 标记主键
@PrimaryKey(autoGenerate = true) // autoGenerate 表示主键会自动递增
public int id;
// 数据库的普通列
public String name;
public int age;
// 构造函数(可选,用于创建对象)
public User(String name, int age) {
this.name = name;
this.age = age;
}
}
@Dao
public interface UserDao {
// 插入数据
@Insert
void insertUser(User user);
// 查询所有数据
@Query("SELECT * FROM users")
List<User> getAllUsers();
// 按条件查询数据
@Query("SELECT * FROM users WHERE age > :minAge")
List<User> getUsersOlderThan(int minAge);
// 删除数据
@Delete
void deleteUser(User user);
}
注册到数据库中:
// @Database 注解定义了数据库的表结构和版本
@Database(entities = {User.class}, version = 1)
public abstract class AppDatabase extends RoomDatabase {
// 定义抽象方法,返回 DAO
public abstract UserDao userDao();
}
项目结构如下:
在之前的Test Controller中使用:
@RestController
//@RequestMapping(path = "/api")
public class TestController {
@GetMapping("/user/get")
public String test(@RequestParam("id") String id) {
new Thread(() -> {
User user = new User("John Doe", 25);
Context context = ActivityUtils.getCurrentActivityContext(); // 使用工具类获取当前的 Context
if (context != null) {
DatabaseClient.getInstance(context).getAppDatabase().userDao().insertUser(user);
}
}).start();
return "id = " + id;
}
}
Room 默认不允许在主线程执行数据库操作,需要使用线程或协程来操作。
最终通过studio查看:
发现数据已经增加成功 说明链路已经打通了
告辞