So I have created a room database following tutorials on youtube. I have two columns day and likes, each holding int's. Currently I have populated the database manually with three rows of data.
Here is the code for populating database manually:
@Database(entities = Recovery.class, version = 1, exportSchema = false)
public abstract class RecoveryDatabase extends RoomDatabase {
private static RecoveryDatabase INSTANCE;
public abstract RecoveryDao recoveryDao();
// Singleton
public static RecoveryDatabase getInstance(final Context context) {
if (INSTANCE == null) {
synchronized (RecoveryDatabase.class) {
if (INSTANCE == null) {
INSTANCE = Room.databaseBuilder(context.getApplicationContext(), RecoveryDatabase.class, "recovery_database").fallbackToDestructiveMigration().addCallback(roomCallback).build();
}
}
}
return INSTANCE;
}
private static RecoveryDatabase.Callback roomCallback = new RoomDatabase.Callback() {
@Override
public void onCreate(@NonNull SupportSQLiteDatabase db) {
super.onCreate(db);
new PopulateDbAsyncTask(INSTANCE).execute();
}
};
private static class PopulateDbAsyncTask extends AsyncTask<Void, Void, Void> {
private RecoveryDao recoveryDao;
private PopulateDbAsyncTask(RecoveryDatabase db) {
recoveryDao = db.recoveryDao();
}
@Override
protected Void doInBackground(Void... voids) {
// First input is the day and the second is the num of likes for that day
recoveryDao.insert(new Recovery(6,1));
recoveryDao.insert(new Recovery(7,2));
recoveryDao.insert(new Recovery(8,3));
return null;
}
}
}
In my Dao class I currently have Insert, Update, deleteAll, and getAll... Methods. Here is the Dao:
@Dao
public interface RecoveryDao {
@Insert
void insert(Recovery recovery);
@Update
void update(Recovery recovery);
@Query("DELETE FROM recovery_table")
void deleteAllRecovery();
// Sends data from ascending day to the call. (1,2,3,4 ....)
@Query("SELECT * FROM RECOVERY_TABLE ORDER BY day ASC")
LiveData<List<Recovery>> getAllRecovery();
}
Now, I want to retrieve the data from the Room database based on the day. So I want the num of likes for day 6, which would be 1. I want to retrieve the data and store it into an int variable in mainActivity.
So my end goal is the have many rows of data in the database and retrieve that and store that into an ArrayList, but I must first figure out how to retrieve data first.
I have tried many solutions from stackover flow, but I have not yet figured it out. All tutorials on YT all use Recycler view and adapters, but I will not be using them. I am very new to sqlite and MVVM. Thank you for the help!!!
Try this query you need to pass the day in argument .
@Query("SELECT * FROM RECOVERY_TABLE WHERE day=:day ORDER BY day ASC ")
LiveData<List<Recovery>> getRecoveryWithDay(int day);
this will give you the list of Recovery with the matching day , you can change return type to List<Recovery>
from LiveData<List<Recovery>>
if you need
Let me know if you see any error .