Android学习:两个Activity如何操作同一个数据库SQLite
在Android中,两个Activity
可以通过ContentProvider
或者将数据库封装在一个Repository
类中来共享同一个数据库。以下是使用Room
库操作同一个数据库的简单示例:
- 定义数据实体和数据库接口:
// User.java
@Entity
public class User {
@PrimaryKey
private int id;
private String name;
// getters and setters
}
// UserDao.java
@Dao
public interface UserDao {
@Query("SELECT * FROM user")
List<User> getAll();
@Query("SELECT * FROM user WHERE id = :id")
User getUserById(int id);
@Insert
void insertUser(User user);
@Update
void updateUser(User user);
@Delete
void deleteUser(User user);
}
// AppDatabase.java
@Database(entities = {User.class}, version = 1)
public abstract class AppDatabase extends RoomDatabase {
public abstract UserDao userDao();
}
- 在
Application
类中初始化数据库:
// MyApplication.java
public class MyApplication extends Application {
private static AppDatabase db;
@Override
public void onCreate() {
super.onCreate();
db = Room.databaseBuilder(getApplicationContext(), AppDatabase.class, "my_database")
.build();
}
public static AppDatabase getDatabase() {
return db;
}
}
- 在
Activity
中使用数据库:
// Activity1.java
public class Activity1 extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// ...
UserDao userDao = MyApplication.getDatabase().userDao();
User user = new User();
user.setName("Alice");
userDao.insertUser(user);
}
}
// Activity2.java
public class Activity2 extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// ...
UserDao userDao = MyApplication.getDatabase().userDao();
List<User> users = userDao.getAll();
// 使用获取到的用户数据
}
}
确保在AndroidManifest.xml
中配置了MyApplication
类:
<application
android:name=".MyApplication"
...>
<!-- activities and other components -->
</application>
这样,两个Activity
都可以通过MyApplication.getDatabase().userDao()
来访问同一个数据库并操作用户数据。
评论已关闭