//Add this Dependency in gradle
def room_version = "2.4.2"
def lifecycle_version = "2.5.0-rc02"
def arch_version = "2.1.0"
implementation "androidx.room:room-runtime:$room_version"
annotationProcessor "androidx.room:room-compiler:$room_version"
// ViewModel
implementation "androidx.lifecycle:lifecycle-viewmodel:$lifecycle_version"
// LiveData
implementation "androidx.lifecycle:lifecycle-livedata:$lifecycle_version"
//Firstly create Dao Object where we can define all operation related to Database
@Dao
public interface DaoObject {
@Insert(onConflict = OnConflictStrategy.REPLACE)
void insertData(List<DataModel> modelList);
@Insert(onConflict = OnConflictStrategy.REPLACE)
void insertDataOne(DataModel modelList);
@Delete
void delete(DataModel model);
@Query("SELECT * FROM simple_data_info WHERE id= :id")
DataModel getNoteByQuery(int id);
@Query("SELECT * FROM simple_data_info ORDER BY DataInfo DESC")
LiveData<List<DataModel>> getAllnotesData();
@Query("DELETE FROM SIMPLE_DATA_INFO")
int deletenote();
@Query("SELECT COUNT(*) FROM SIMPLE_DATA_INFO")
int getCount();
}
//Then create Room Database Object using single pattern to communicate with Dao .
@Database(entities = {DataModel.class}, version = 3)
@TypeConverters(DateConverter.class)
public abstract class AppDatabase extends RoomDatabase {
private static final String DATABASE_NAME = "all_data_table.db";
public abstract DaoObject mDaoObject();
private static volatile AppDatabase mAppDatabaseInstance;
private final static Object mObject = new Object();
public static AppDatabase getInstance(Context application) {
if (mAppDatabaseInstance == null) {
synchronized (mObject) {
mAppDatabaseInstance = Room.databaseBuilder(application.getApplicationContext(),
AppDatabase.class, DATABASE_NAME)
.fallbackToDestructiveMigration()
.build();
}
}
return mAppDatabaseInstance;
}//Create Repository to communicate with AppDatabase calss (Room Database).
Note :- repository is responsible to decide from in which source data will get
either local db (Room Database) or NetWork (like Retrofit) .and operation will been done
on background thread in repository but onl if Your method return live data object then
you don't need to call background thread beacuase it will already managed by live Data.
public class AppRepository {
public LiveData<List<DataModel>> mList;
private final Executor mExecutors= Executors.newSingleThreadExecutor();
private static AppRepository mRepositoryIntance;
private AppDatabase mAppDatabase;
//create the repository instance
public static AppRepository getRepoitoryInstance(Context context)
{
Log.d("mytag",""+"apprepository called");
return mRepositoryIntance=new AppRepository(context.getApplicationContext());
}private AppRepository(Context context)
{
mAppDatabase=AppDatabase.getInstance(context.getApplicationContext());
Log.d("mytag","mytag"+getAllData());
// getCount();
mList=getAllData();
}
//to get the all data from db
private LiveData<List<DataModel>> getAllData() {
return mAppDatabase.mDaoObject().getAllnotesData();
}
//do on background thread
public void insertThedateIntoTable() {
mExecutors.execute(() -> {
mAppDatabase.mDaoObject().insertData(SimpleData.getSimpleData());
});
}
public void deleteAll() {
mExecutors.execute(()->{
int notes= mAppDatabase.mDaoObject().deletenote();
Log.d("mytag","mytag"+notes);
});
}
public void deleteOneNoteBySwipe(DataModel dataModel) {
mExecutors.execute(new Runnable() {
@Override
public void run() {
mAppDatabase.mDaoObject().delete(dataModel);
}
});
}
public void getCount() {
mExecutors.execute(new Runnable() {
@Override
public void run() {
int a= mAppDatabase.mDaoObject().getCount();
Log.d("mytag","row inside it "+a);
}
});
}
public DataModel loadnoteById(int id) {
DataModel model= mAppDatabase.mDaoObject().getNoteByQuery(id);
return model;
}
public void deleteSingleNote(DataModel value) {
mExecutors.execute(new Runnable() {
@Override
public void run() {
mAppDatabase.mDaoObject().delete(value);
}
});
}
public void updateNotes(DataModel model) {
mExecutors.execute(new Runnable() {
@Override
public void run() {
mAppDatabase.mDaoObject().insertDataOne(model);
}
});
}}//Create AndroidViewModel to communicate with Repository
//Note- every calss will have own ViewModel if in your app You need multiple ViewModel
then you can use
public class ListViewModel extends AndroidViewModel {
private AppRepository mRepository;
public LiveData<List<DataModel>> mList;
public ListViewModel(@NonNull Application application) {
super(application);
Log.d("mytag","view model called ");
mRepository=AppRepository.getRepoitoryInstance(application.getApplicationContext());
mList=mRepository.mList;
}
public void isertData(List<DataModel> modelList)
{
//lsit IS PASS IN repository class
mRepository.insertThedateIntoTable();
}
public void deleteAll()
{
mRepository.deleteAll();
}
public void deleteOneNotesBySwipe(DataModel dataModel)
{
mRepository.deleteOneNoteBySwipe(dataModel);
}
public void getCount()
{
mRepository.getCount();
}
}//Create the Reference of ViewModel in MainActivity//in MainActivity calss create the Top level variable
private ActivityMainBinding mMainBinding;
private ListViewModel mListViewModel;
private List<DataModel> mDataModelList;
private Myadpter mMyadpter;//in MainActivity calss create the Top level variable
private void initilalizeViewmodel() {
Observer<List<DataModel>> observer=new Observer<List<DataModel>>() {
@Override
public void onChanged(List<DataModel> modelList) {
mDataModelList.clear();
mDataModelList.addAll(modelList);
i++;
Log.d("mytag","observer called "+i);
mMyadpter.notifyDataSetChanged();
}
};
mListViewModel=new ViewModelProvider(MainActivity.this).get(ListViewModel.class);
mListViewModel.mList.observe(this,observer);
}//Create the Model calss which is hold your data or set your data field .may be in
your case will different model class and more than one
@Entity(tableName = "simple_data_info")
public class DataModel {
@PrimaryKey(autoGenerate = true)
private int id;
@ColumnInfo(name = "DataInfo")
private Date mDate;
private String simpledata;
@Ignore
public DataModel()
{
}
@Ignore
public DataModel(int id, Date date, String simpledata) {
this.id = id;
mDate = date;
this.simpledata = simpledata;
}
public DataModel(Date date, String simpledata) {
mDate = date;
this.simpledata = simpledata;
}
public int getId() {
return id;
}
public Date getDate() {
return mDate;
}
public String getSimpledata() {
return simpledata;
}
public void setId(int id) {
this.id = id;
}
public void setSimpledata(String trim) {
}
public void setDate(Date date) {
}
}//Create SimpleData Class to insert value into Room Database
note- in Real app your data will come from any newtwork .then save the value
into insert the value into Room database but in this example we are taking simpleData class
to check
public class SimpleData {
public static final String data1=" 1. this is first node .i love coding ";
public static final String data2=" 2. this is second node where i m testing . ";
public static final String data3=" 3. this is third node \n what is best language to leran android developer";
private static Date getData(int diffAmount)
{
GregorianCalendar gregorianCalendar=new GregorianCalendar();
gregorianCalendar.add(Calendar.MILLISECOND,diffAmount);
return gregorianCalendar.getTime();
}
public static List<DataModel> getSimpleData()
{
List<DataModel> simleList=new ArrayList<>();
simleList.add(new DataModel(getData(0),data1));
simleList.add(new DataModel(getData(-1),data2));
simleList.add(new DataModel(getData(-2),data3));
return simleList;
}//in Above code one thing is creating a problem Room Database will be not put the value as
Date type to get rid of this we can use TypeConverter
public class DateConverter {
@TypeConverter
public static Long togetTimeStamp(Date date)
{
return date==null?null:date.getTime();
}
@TypeConverter
public static Date toDate(Long timnestamp)
{
return timnestamp==null?null:new Date(timnestamp);
}
}
No comments:
Post a Comment