Android - Multiple database one project - android

I would like to ask if is possible to have multiple database under one project, with Room Persistence Library? Changing dynamic the selection of the database.
Thanks

It is possible.
Let's assume you have two sets of entities and two sets of DAOs. You can obtain access to two databases by:
creating two classes that extends RoomDatabase:
AppDatabase 1:
#Database(entities = {/*... the first set of entities ...*/}, version = 1)
public abstract class AppDatabase1 extends RoomDatabase {
// the first set of DAOs
}
AppDatabase2:
#Database(entities = {/*... the second set of entities ...*/}, version = 1)
public abstract class AppDatabase2 extends RoomDatabase {
// the second set of DAOs
}
instantiating the two databases:
Note that you'll use two different file names.
AppDatabase db1 = Room.databaseBuilder(getApplicationContext(), AppDatabase1.class, "database1.db").build();
AppDatabase db2 = Room.databaseBuilder(getApplicationContext(), AppDatabase2.class, "database2.db").build();
In this case, you can use both databases, but you won't be able to create queries between them. If you need to attach the two databases, then you should take a look at the link #Anees provided

You can reuse the entities and DAO if databases have the same schema and dynamically switch between them (helpful if you want to have a different database file for each user).
Entity class
#Entity
public class User {
#PrimaryKey
#NonNull
public String uid;
#ColumnInfo(name = "first_name")
public String firstName;
#ColumnInfo(name = "last_name")
public String lastName;
}
DAO class
#Dao
public interface UserDao {
#Query("SELECT * FROM user")
List<User> getAll();
#Query("SELECT * FROM user WHERE uid IN (:userIds)")
List<User> loadAllByIds(int[] userIds);
#Query("SELECT * FROM user WHERE first_name LIKE :first AND " +
"last_name LIKE :last LIMIT 1")
User findByName(String first, String last);
#Insert
void insertAll(User... users);
#Delete
void delete(User user);
}
Database class
#Database(entities = {User.class}, version = 1)
public abstract class AppDatabase extends RoomDatabase {
public abstract UserDao userDao();
}
DatabaseClient class
public class DatabaseClient {
private Context mCtx;
private AppDatabase appDatabase;
private static String databaseName;
private static DatabaseClient mInstance;
private DatabaseClient(Context mCtx, String dbName) {
this.mCtx = mCtx;
if(databaseName == null || !databaseName.equalsIgnoreCase(dbName)) {
databaseName = dbName;
}
appDatabase = Room.databaseBuilder(mCtx, AppDatabase.class, databaseName).build();
}
public String getDatabaseName() {
return databaseName;
}
public static synchronized DatabaseClient getInstance(Context mCtx, String dbName) {
if (mInstance == null || databaseName == null || !databaseName.equalsIgnoreCase(dbName)) {
mInstance = new DatabaseClient(mCtx, dbName);
}
return mInstance;
}
public AppDatabase getAppDatabase() {
return appDatabase;
}
}
Now you can query based on a particular database by passing its name in the parameter in my case here let's say myDb
List<User> users = DatabaseClient.getInstance(getApplicationContext(), myDb).getAppDatabase().userDao().getAll()
Remember whenever you perform the first call with a database name, it creates the database file. If a new user arrives and calls to insert its info, it automatically creates a new database file and inserts the info data into it.

Just solved it with koin. I was creating an instant message app, and mutiple account login was required. After user1 logon my app, the databse name with im_id could be got, then by inject, I created the database with the id. Then user1 one logout , I just unload the datasource module and jump to the login activity. User2 then login, I reload the datasource module and created database for user2 with his im_id. Code as follows:
val dataSourceModule = module{
single {
Room.databaseBuilder(androidApplication(), AppDataBase::class.java, get<GsSelectedAndImTokenPersistence>().gsImToken?.gsImId ?: "im_database" )
.build()
}
single { get<AppDataBase>().gsInfoDao() }
single { get<AppDataBase>().gsGameInfoDao() }
single { get<AppDataBase>().gameClientDao() }
single { SharedPreferencesDataSourceImpl(androidContext()) } binds (
arrayOf(
ImDeviceIdPersistence::class,
GsSelectedAndImTokenPersistence::class
))
}
fun unLoadDataSourceModule() {
unloadKoinModules(dataSourceModule)
}
fun reLoadDataSourceModule() {
loadKoinModules(dataSourceModule)
}
The interesting is, even if
get().gsImToken?.gsImId
is null, it won't create the default database with name "im_database" by using koin inject.
And This is where I create the database by inject ,after I got the im_id from server
viewModel.gsImToken.observe(provideLifecycleOwner(), {
ELogger.d("database initial","init database===")
// Incase of the datasource module is not loaded by now
KoinInitializer.reLoadDataSourceModule()
val gs: AppDataBase by inject()
gs.gsGameInfoDao().run {
viewModel.initDao(this)
}
})
And the logout place:
class SettingViewModel(
...,
val db: AppDataBase
): ViewModel() {
...
fun onLogout(){
...
db.close()
KoinInitializer.unLoadDataSourceModule()
...
}
}

Related

My data in Database are deleted everytime I am killing the app?

In my android app, I am storing data in database using Room Database library.I can store and get data in a single session.There is no problem in that. The problem is when I close the app and open again I am not getting the data stored in the local database.Those data are deleted.
I've searched in google and some of them said create room data database instance using databaseBuilder.But I am using that only.but I am getting this error.
This is my instance initialization.
This is my AppDtabase class ;
#Database(entities = {SelectedBuilding.class}, exportSchema =true, version=2)
public abstract class AppDatabase extends RoomDatabase {
private static AppDatabase INSTANCE;
public abstract SelectedBuildingDao myDao();
public static AppDatabase getAppDatabase(Context context){
if (INSTANCE==null){
INSTANCE= Room.databaseBuilder(context.getApplicationContext(),AppDatabase.class,"Selected_buildings")
.addMigrations(MIGRATION_1_2)
.build();
}
return INSTANCE;
}
public static void destroyInstance(){
INSTANCE=null;
}
static final Migration MIGRATION_1_2 = new Migration(1, 2) {
#Override
public void migrate(SupportSQLiteDatabase database) {
database.execSQL("ALTER TABLE selected_building ADD COLUMN Building_Id TEXT");
}
};
}
INSTANCE= Room.databaseBuilder(context.getApplicationContext(),AppDatabase.class,"Selected_area").build();
Can anyone help me to solve this issue?
Thanks in Advance.

Android room - id of insterted row - from ViewModel

I am using Android Room, and I would like to get ID of new inserted row. I have declared column in my model class:
#PrimaryKey (autoGenerate = true)
#ColumnInfo (name = "productID")
int id;
And then I know I can retrive it by dao returning long:
#Insert
long insert(Product p);
At first I was using "thread" calls directly in View. And as you know, it is not recommended method. So I am trying to change it for ModelView and repository. But I don't know how can I get this ID.
My repository class:
public class ProductRepository {
private ProductDao mProductDao;
ProductRepository(Application application) {
AppDatabase db = AppDatabase.getDatabase(application);
mProductDao = db.pDao();
}
public void insertProduct(Product p) {
new insertAsyncTask(mProductDao).execute(p);
}
private static class insertAsyncTask extends AsyncTask<Product, Void, Void> {
private ProductDao mAsyncTaskDao;
insertAsyncTask(ProductDao dao) {
mAsyncTaskDao = dao;
}
#Override
protected Void doInBackground(final Product... params) {
mAsyncTaskDao.insert(params[0]);
return null;
}
}
}
And my model class:
public class ProductModelView extends AndroidViewModel {
private ProductRepository mRepository;
public ProductModelView(Application application) {
super(application);
mRepository = new ProductRepository(application);
}
public void insert(Product p) {
mRepository.insertProduct(p);
}
}
And in my Activity I am inserting new object like this:
mProductModelView.insert(pc);
So how I can retrive this long value from "insert" and get it in my activity? I guess LiveData could be a good way to go, but to be honest I dont havy any ideas how to achieve it :(
The best way to do this is by using LiveData. If you want to use MVVM might as well learn how to use LiveData. It's easy.
In your DAO interface, declare a method like this:
#Query("SELECT * FROM Product ORDER BY id DESC LIMIT 1")
LiveData<Product> getLastProductLive();
This method returns the last Product inserted as LiveData
Then inside your Repository:
public LiveData<Product> getLastProductLive(){
return mProductDao.getLastProductLive();
}
And then inside your ViewModel:
public LiveData<Product> getLastProductLive(){
return mRepository.getLastProductLive();
}
And finally inside your Activity:
mProductViewModel.getLastProductLive().observe(this, product -> {
long lastInsertedRowId = product.getId();
}
By using LiveData, any time that a product is added to table, it triggers this method and you can get the id of the last inserted row.

Android ROOM - LiveData not triggered when using custom insert query

I'm trying to store values of some variable that my application regulary obtains from API. I whant to add new row to the database table only when variable changes its value to be able to show user some kind of "history of changes". I'm using ROOM for storing data.
I've created an entity:
#Entity(tableName = "balance_history",
indices = {#Index("received_at")})
public class BalanceResponse {
//region getters & setters
...
//endregion
#PrimaryKey(autoGenerate = true)
#ColumnInfo(name = "id")
private long mId;
#ColumnInfo(name = "money")
private double mMoney;
#ColumnInfo(name = "received_at")
private DateTime mReceivedAt;
}
Dao:
#Dao
public abstract class DatabaseDao {
#Query("SELECT * FROM balance_history ORDER BY received_at DESC LIMIT 1")
public abstract LiveData<BalanceResponse> selectLatestBalanceResponse();
public void insertNewBalanceResponse(BalanceResponse balanceResponse) {
String sqlRequest = "INSERT INTO balance_history(money, received_at) " +
"SELECT ?, ? " +
"WHERE NOT EXISTS(SELECT 1 FROM (SELECT * FROM balance_history ORDER BY received_at DESC LIMIT 1) WHERE money = ?);";
SupportSQLiteDatabase database = DatabaseStorage.getInstance().getAppDatabase().getOpenHelper().getWritableDatabase();
database.execSQL(sqlRequest,
new Object[]{balanceResponse.getMoney(), balanceResponse.getReceivedAt().getMillis(), balanceResponse.getMoney()});
}
}
Database object:
#Database(entities = {BalanceResponse.class}, version = 1)
#TypeConverters(DateTimeConverter.class)
public abstract class AppDatabase
extends RoomDatabase {
public abstract DatabaseDao getDatabseDao();
}
Singleton for storing single database object:
public class DatabaseStorage {
//region singleton
private static final DatabaseStorage ourInstance = new DatabaseStorage();
public static DatabaseStorage getInstance() {
return ourInstance;
}
//endregion
#NonNull
public AppDatabase getAppDatabase() {
return mAppDatabase;
}
#NonNull
private AppDatabase mAppDatabase;
private DatabaseStorage() {
mAppDatabase =
Room.databaseBuilder(MyApp.getAppContext(), AppDatabase.class, "app-database")
.build();
}
}
And viewmodel that I instantiate in my Activity's onCreate():
public class BalanceView implements Observer<BalanceResponse> {
private LiveData<BalanceResponse> mLatestBalanceResponse;
public BalanceView(LifecycleOwner lifecycleOwner){
mLatestBalanceResponse = DatabaseStorage.getInstance().getAppDatabase().getDatabseDao()
.selectLatestBalanceResponse();
mLatestBalanceResponse.observe(lifecycleOwner, this);
//finding views here
}
#Override
public void onChanged(#Nullable BalanceResponse balanceResponse) {
//displaying changes here
}
}
I've expected triggering of BalanceView.onChanges() method each time when method DatabaseDao.insertNewBalanceResponse() inserts a row.
Actually BalanceView.onChanges() method never gets fired. Why is that so? How can I accomplish this?
p.s. However, If I replace method DatabaseDao.insertNewBalanceResponse() with original:
#Insert
public abstract Long insertBalanceResponse(BalanceResponse balanceResponse);
Everithing works fine and method onChange() gets invoked. But this kind of insert statement doesn't fit my needs.
I have the same issue and here I got a hint to solve this issue.
#Dao
interface RawDao {
#RawQuery
User getUserViaQuery(SupportSQLiteQuery query);
}
SimpleSQLiteQuery query = new SimpleSQLiteQuery("SELECT * FROM User WHERE id = ? LIMIT 1",
new Object[]{userId});
User user2 = rawDao.getUserViaQuery(query);
For More details, check https://developer.android.com/reference/android/arch/persistence/room/RawQuery.

How write Create and Update Query in Room Library?

I go through SQL query other solution. i am not able to find suitable solutions for my problem.
In My project, i have the insert data into the table. I have to follow some steps
Step1:- I have to check data through a primary key that the data is available or not.
Step 2: if data is available then I have to update that data and return response code. if not I have to go step 3
Step 3: if data is not in the table then insert data into it and return code.
I am using Room Library. i am confused how to write in #Dao to perform that task.
Thanks in advance
Android Architecture Components introduced Android Room Persistence Library which is best for sqlite android database handling. Entity in Room Persistence represents a database table and Dao is where we define database interactions. Example
#Entity
public class Trail {
public #PrimaryKey String id;
public String name;
public double kilometers;
public int difficulty;
}
possible Dao for this table will be
#Dao
public interface TrailDao {
#Insert(onConflict = IGNORE)
void insertTrail(Trail trail);
#Query("SELECT * FROM Trail")
List<Trail> findAllTrails();
#Update(onConflict = REPLACE)
void updateTrail(Trail trail);
#Query("DELETE FROM Trail")
void deleteAll();
}
Further you need to provide RoomDatabase implementation, Example
#Database(entities = {Trail.class}, version = 1)
public abstract class AppDatabase extends RoomDatabase {
private static AppDatabase INSTANCE;
public abstract TrailDao trailDao();
public static AppDatabase getInMemoryDatabase(Context context) {
if (INSTANCE == null) {
INSTANCE =
Room.inMemoryDatabaseBuilder(context.getApplicationContext(), AppDatabase.class)
.allowMainThreadQueries()
.build();
}
return INSTANCE;
}
public static void destroyInstance() {
INSTANCE = null;
}
}
Use It like
AppDatabase. getInMemoryDatabase(context).trailDao().findAllTrails();

Android Room: Insert relation entities using Room

I've added one to many relationship in Room using Relation.
I referred to this post to write the following code for relation in Room.
The post tells how to read the values from the database but storing the entities into the database resulted in userId to be empty which means there is no relation between the 2 tables.
I'm not sure what is the ideal way to insert a User and List of Pet into the database while having userId value.
1) User Entity:
#Entity
public class User {
#PrimaryKey
public int id; // User id
}
2) Pet Entity:
#Entity
public class Pet {
#PrimaryKey
public int id; // Pet id
public int userId; // User id
public String name;
}
3) UserWithPets POJO:
// Note: No annotation required at this class definition.
public class UserWithPets {
#Embedded
public User user;
#Relation(parentColumn = "id", entityColumn = "userId", entity = Pet.class)
public List<Pet> pets;
}
Now to fetch the records from DB we use the following DAO:
#Dao
public interface UserDao {
#Insert
fun insertUser(user: User)
#Query("SELECT * FROM User")
public List<UserWithPets> loadUsersWithPets();
}
EDIT
I have created this issue https://issuetracker.google.com/issues/62848977 on the issue tracker. Hopefully they will do something regarding it.
You can do this by changing your Dao from an interface to an abstract class.
#Dao
public abstract class UserDao {
public void insertPetsForUser(User user, List<Pet> pets){
for(Pet pet : pets){
pet.setUserId(user.getId());
}
_insertAll(pets);
}
#Insert
abstract void _insertAll(List<Pet> pets); //this could go in a PetDao instead...
#Insert
public abstract void insertUser(User user);
#Query("SELECT * FROM User")
abstract List<UserWithPets> loadUsersWithPets();
}
You can also go further by having a User object have an #Ignored List<Pet> pets
#Entity
public class User {
#PrimaryKey
public int id; // User id
#Ignored
public List<Pet> pets
}
and then the Dao can map UserWithPets to User:
public List<User> getUsers() {
List<UserWithPets> usersWithPets = loadUserWithPets();
List<User> users = new ArrayList<User>(usersWithPets.size())
for(UserWithPets userWithPets: usersWithPets) {
userWithPets.user.pets = userWithPets.pets;
users.add(userWithPets.user);
}
return users;
}
This leaves you with the full Dao:
#Dao
public abstract class UserDao {
public void insertAll(List<User> users) {
for(User user:users) {
if(user.pets != null) {
insertPetsForUser(user, user.pets);
}
}
_insertAll(users);
}
private void insertPetsForUser(User user, List<Pet> pets){
for(Pet pet : pets){
pet.setUserId(user.getId());
}
_insertAll(pets);
}
public List<User> getUsersWithPetsEagerlyLoaded() {
List<UserWithPets> usersWithPets = _loadUsersWithPets();
List<User> users = new ArrayList<User>(usersWithPets.size())
for(UserWithPets userWithPets: usersWithPets) {
userWithPets.user.pets = userWithPets.pets;
users.add(userWithPets.user);
}
return users;
}
//package private methods so that wrapper methods are used, Room allows for this, but not private methods, hence the underscores to put people off using them :)
#Insert
abstract void _insertAll(List<Pet> pets);
#Insert
abstract void _insertAll(List<User> users);
#Query("SELECT * FROM User")
abstract List<UserWithPets> _loadUsersWithPets();
}
You may want to have the insertAll(List<Pet>) and insertPetsForUser(User, List<Pet>) methods in a PetDAO instead... how you partition your DAOs is up to you! :)
Anyway, it's just another option. Wrapping your DAOs in DataSource objects also works.
There is no native solution till any update in Room Library but you can do this by a trick. Find below mentioned.
Just Create a User with Pets (Ignore pets). Add getter and setter. Notice that we have to set our Id's manually later and can't use autogenerate.
#Entity
public class User {
#PrimaryKey
public int id;
#Ignore
private List<Pet> petList;
}
Create a Pet.
#Entity
public class Pet
{
#PrimaryKey
public int id;
public int userId;
public String name;
}
The UserDao should be an abstract class instead of an Interface. Then finally in your UserDao.
#Insert
public abstract void insertUser(User user);
#Insert
public abstract void insertPetList(List<Pet> pets);
#Query("SELECT * FROM User WHERE id =:id")
public abstract User getUser(int id);
#Query("SELECT * FROM Pet WHERE userId =:userId")
public abstract List<Pet> getPetList(int userId);
public void insertUserWithPet(User user) {
List<Pet> pets = user.getPetList();
for (int i = 0; i < pets.size(); i++) {
pets.get(i).setUserId(user.getId());
}
insertPetList(pets);
insertUser(user);
}
public User getUserWithPets(int id) {
User user = getUser(id);
List<Pet> pets = getPetList(id);
user.setPetList(pets);
return user;
}
Your problem can be solved by this without creating UserWithPets POJO.
As Room does not manage the Relations of the entities, you have to set the userId on each pet yourself and save them. As long as there are not too many pets at once, I'd use an insertAll method to keep it short.
#Dao
public interface PetDao {
#Insert
void insertAll(List<Pet> pets);
}
I don't think there's any better way at the moment.
To make the handling easier, I'd use an abstraction in the layer above the DAOs:
public void insertPetsForUser(User user, List<Pet> pets){
for(Pet pet : pets){
pet.setUserId(user.getId());
}
petDao.insertAll(pets);
}
Currently there is no native solution to this problem. I have created this https://issuetracker.google.com/issues/62848977 on Google's issue tracker and the Architecture Components Team said they will adding a native solution in or after v1.0 of Room library.
Temporary Workaround:
Meanwhile you can use the solution mentioned by tknell.
public void insertPetsForUser(User user, List<Pet> pets){
for(Pet pet : pets){
pet.setUserId(user.getId());
}
petDao.insertAll(pets);
}
I managed to insert it properly with a relatively simple workaround. Here are my entities:
#Entity
public class Recipe {
#PrimaryKey(autoGenerate = true)
public long id;
public String name;
public String description;
public String imageUrl;
public int addedOn;
}
#Entity
public class Ingredient {
#PrimaryKey(autoGenerate = true)
public long id;
public long recipeId;
public String name;
public String quantity;
}
public class RecipeWithIngredients {
#Embedded
public Recipe recipe;
#Relation(parentColumn = "id",entityColumn = "recipeId",entity = Ingredient.class)
public List<Ingredient> ingredients;
I am using autoGenerate for auto-increment value(long is used with a purpoes).
Here is my solution:
#Dao
public abstract class RecipeDao {
public void insert(RecipeWithIngredients recipeWithIngredients){
long id=insertRecipe(recipeWithIngredients.getRecipe());
recipeWithIngredients.getIngredients().forEach(i->i.setRecipeId(id));
insertAll(recipeWithIngredients.getIngredients());
}
public void delete(RecipeWithIngredients recipeWithIngredients){
delete(recipeWithIngredients.getRecipe(),recipeWithIngredients.getIngredients());
}
#Insert
abstract void insertAll(List<Ingredient> ingredients);
#Insert
abstract long insertRecipe(Recipe recipe); //return type is the key here.
#Transaction
#Delete
abstract void delete(Recipe recipe,List<Ingredient> ingredients);
#Transaction
#Query("SELECT * FROM Recipe")
public abstract List<RecipeWithIngredients> loadAll();
}
I had problem linking the entities, auto generate produced "recipeId=0" all the time. Inserting the recipe entity firstly fixed it for me.
Now at v2.1.0 Room seems to be not suitable for models with nested relations. It needed lots of boilerplate code to maintain them. E.g. manual insert of lists, creating and mapping local IDs.
This relations-mapping operations are done out of box by Requery https://github.com/requery/requery Additionaly it does not have issues with inserting Enums and have some converters for other complex types like URI.

Categories

Resources