Reputation: 1697
Inside onCreateView method
MainActivity.localDatabase.categoriesDao().getCategories().subscribe(new SingleObserver<List<CategoriesModel>>() {
@Override
public void onSubscribe(@io.reactivex.rxjava3.annotations.NonNull Disposable d) {
}
@Override
public void onSuccess(@io.reactivex.rxjava3.annotations.NonNull List<CategoriesModel> categoriesModels) {
}
@Override
public void onError(@io.reactivex.rxjava3.annotations.NonNull Throwable e) {
}
});
MainActivity.localDatabase.subcategoriesDao().getSubcategories(1).subscribe(new SingleObserver<List<SubcategoriesModel>>() {
@Override
public void onSubscribe(@io.reactivex.rxjava3.annotations.NonNull Disposable d) {
}
@Override
public void onSuccess(@io.reactivex.rxjava3.annotations.NonNull List<SubcategoriesModel> subcategoriesModels) {
}
@Override
public void onError(@io.reactivex.rxjava3.annotations.NonNull Throwable e) {
}
});
CategoriesDao
@Dao
public interface CategoriesDao {
@Query("SELECT * FROM CATEGORIES")
Single<List<CategoriesModel>> getCategories();
@Query("DELETE FROM CATEGORIES")
void deleteCategories();
@Insert
void insertCategories(List<CategoriesModel> categoriesModelList);
}
SubcategoriesDao
@Dao
public interface SubcategoriesDao {
@Query("SELECT * FROM SUBCATEGORIES WHERE category_id = :categoryId")
Single<List<SubcategoriesModel>> getSubcategories(int categoryId);
@Insert
void insertSubcategories(List<SubcategoriesModel> subcategoriesModelList);
@Query("DELETE FROM SUBCATEGORIES")
void deleteSubcategories();
}
LocalDatabase
@Database(entities = {CategoriesModel.class, SubcategoriesModel.class}, version = 1)
public abstract class LocalDatabase extends RoomDatabase {
public abstract CategoriesDao categoriesDao();
public abstract SubcategoriesDao subcategoriesDao();
}
I want to get the categories and subcategories that are stored in the room database, I did it such as the code above, But how can I avoid creating multiple connections?
Is it possible to get the categories and subcategories in one connection only instead of two?
What about Transactions or is there another way?
Please leave an example with your answer.
Upvotes: 0
Views: 224
Reputation: 7087
You need to apply JOIN between your CATEGORIES table and SUBCATEGORIES.
Below is an exam of doing the JOIN with android ROOM.
Make sure you have CategoryID as ForeignKey in SUBCATEGORIES table.
You can try the following.
class CatSubCate{
@Embedded
var mCat: CategoriesModel? = null
//Declare Column you need from the SUBCATEGORIES table
var mSubCatId: String? = null
var mCatId: String? = null
}
In Side
@Dao
public interface CategoriesDao {
@Transaction
@Query("SELECT * FROM CATEGORIES LEFT JOIN (SELECT S.SubCatId AS mSubCatId, S.ID as mCatId FROM SUBCATEGORIES S GROUP BY S.ID) AS SUBCATEGORIES ON CATEGORIES.ID=SUBCATEGORIES.ID WHERE CATEGORIES.ID != :catId ")
abstract fun getAllCategory(catId: String): Flowable<List<CatSubCate>>
}
For more info see this android dev link
Upvotes: 1