All Projects → anitaa1990 → Roomdb Sample

anitaa1990 / Roomdb Sample

Licence: apache-2.0
A simple notes app to demo Room + LiveData implementation in Android

Programming Languages

java
68154 projects - #9 most used programming language

Projects that are alternatives of or similar to Roomdb Sample

Android Architecture Components Kotlin
Clean code App with Kotlin and Android Architecture Components
Stars: ✭ 23 (-77%)
Mutual labels:  android-architecture, livedata, room-persistence-library
Nytimes App
🗽 A Simple Demonstration of the New York Times App 📱 using Jsoup web crawler with MVVM Architecture 🔥
Stars: ✭ 246 (+146%)
Mutual labels:  android-architecture, livedata, room-persistence-library
KeepSafeNew
Sample app to demonstrate MVP (Model - View - Presenter), Android Architecture Components (Room Persistence, LiveData), RxJava2, ButterKnife in Android.
Stars: ✭ 58 (-42%)
Mutual labels:  livedata, room-persistence-library
Calculator-Plus
A Simple Calculator with rich features for daily use.
Stars: ✭ 14 (-86%)
Mutual labels:  android-architecture, room-persistence-library
Expenso
📊 A Minimal Expense Tracker App built to demonstrate the use of modern android architecture component with MVVM Architecture
Stars: ✭ 325 (+225%)
Mutual labels:  android-architecture, room-persistence-library
Dagger2 Sample
A sample app to demo how to implement dagger in Android using Dagger Android Support library
Stars: ✭ 72 (-28%)
Mutual labels:  android-architecture, livedata
GithubApp-android-architecture
Let's learn a deep look at the Android architecture
Stars: ✭ 16 (-84%)
Mutual labels:  android-architecture, livedata
Android Architecture Components
The template project that uses Android Architecture Components with Repository pattern. The simple app that uses awesome Fuel library instead of Retrofit for perfoming HTTP request. The app also persists data using the Room library and display data in RecyclerView.
Stars: ✭ 329 (+229%)
Mutual labels:  android-architecture, livedata
Room-Library-Login-Example
Simple Login Presentation Using Room Database
Stars: ✭ 43 (-57%)
Mutual labels:  android-architecture, room-persistence-library
Changedetection
Automatically track websites changes on Android in background.
Stars: ✭ 563 (+463%)
Mutual labels:  livedata, room-persistence-library
Instant Weather
An Android weather application implemented using the MVVM pattern, Retrofit2, Dagger2, LiveData, ViewModel, Coroutines, Room, Navigation Components, Data Binding and some other libraries from the Android Jetpack.
Stars: ✭ 473 (+373%)
Mutual labels:  livedata, room-persistence-library
Base Mvvm
App built to showcase basic Android View components like ViewPager, RecyclerView(homogeneous and heterogeneous items), NavigationDrawer, Animated Vector Drawables, Collapsing Toolbar Layout etc. housed in a MVVM architecture
Stars: ✭ 18 (-82%)
Mutual labels:  livedata, room-persistence-library
Simple-Note-App-with-Online-Storage
✍️ Simple Note Making App use Sqllite Room 🧰 for caching the notes and 📥 Firebase Database for online storage
Stars: ✭ 42 (-58%)
Mutual labels:  livedata, room-persistence-library
Android-MonetizeApp
A sample which uses Google's Play Billing Library and it makes In-app Purchases and Subscriptions.
Stars: ✭ 149 (+49%)
Mutual labels:  android-architecture, room-persistence-library
Android Mvvm Rx3 Dagger2 Navcomponent
Implemented using MVVM, LiveData, Room, RX3, Dagger2, Coil, View Binding, Navigation Component and AndroidX
Stars: ✭ 72 (-28%)
Mutual labels:  livedata, room-persistence-library
Einsen
🎯 Einsen is a prioritization app that uses Eisenhower matrix technique as workflow to prioritize a list of tasks & built to Demonstrate use of Jetpack Compose with Modern Android Architecture Components & MVVM Architecture.
Stars: ✭ 821 (+721%)
Mutual labels:  android-architecture, room-persistence-library
Daggerandroidmvvm
Demonstrates using Dagger 2.11+ in MVVM app with Android Architecture Components, Clean Architecture, RxJava
Stars: ✭ 255 (+155%)
Mutual labels:  android-architecture, livedata
Clean-MVVM-NewsApp
Android News app developed using Clean + MVVM architecture
Stars: ✭ 52 (-48%)
Mutual labels:  livedata, room-persistence-library
KTAndroidArchitecture
A Kotlin android architecture with Google Architecture Components
Stars: ✭ 33 (-67%)
Mutual labels:  android-architecture, livedata
Mvvmarms
Android MVVM Architecture Components based on MVPArms and Android Architecture Components.
Stars: ✭ 425 (+325%)
Mutual labels:  android-architecture, livedata

RoomDb-Sample

This is a demo app on how to implement Room persistance library, making use of LiveData in Android app

How to implement Room: a SQLite object mapping library in your Android app?

Step 1: Add following library and annotation processor to your app gradle file.
compile "android.arch.persistence.room:runtime:1.0.0"
annotationProcessor "android.arch.persistence.room:compiler:1.0.0" 

Note: The reason why annotation processor is needed is because all operations like Insert, Delete, Update etc are annotated.

Step 2: Component 1 in room - Create an entity class: This is nothing but a model class annotated with @Entity where all the variable will becomes column name for the table and name of the model class becomes name of the table. The name of the class is the table name and the variables are the columns of the table Example: Note.java

@Entity
public class Note implements Serializable {

    @PrimaryKey(autoGenerate = true)
    private int id;

    private String title;
    private String description;


    @ColumnInfo(name = "created_at")
    @TypeConverters({TimestampConverter.class})
    private Date createdAt;

    @ColumnInfo(name = "modified_at")
    @TypeConverters({TimestampConverter.class})
    private Date modifiedAt;

    private boolean encrypt;
    private String password;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public Date getCreatedAt() {
        return createdAt;
    }

    public void setCreatedAt(Date createdAt) {
        this.createdAt = createdAt;
    }

    public Date getModifiedAt() {
        return modifiedAt;
    }

    public void setModifiedAt(Date modifiedAt) {
        this.modifiedAt = modifiedAt;
    }

    public boolean isEncrypt() {
        return encrypt;
    }

    public void setEncrypt(boolean encrypt) {
        this.encrypt = encrypt;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

Step 3: Component 2 in room - Create a DAO class This is an interface which acts is an intermediary between the user and the database. All the operation to be performed on a table has to be defined here. We define the list of operation that we would like to perform on table Example: DaoAccess.java

@Dao
public interface DaoAccess {

    @Insert
    Long insertTask(Note note);


    @Query("SELECT * FROM Note ORDER BY created_at desc")
    LiveData<List<Note>> fetchAllTasks();


    @Query("SELECT * FROM Note WHERE id =:taskId")
    LiveData<Note> getTask(int taskId);


    @Update
    void updateTask(Note note);


    @Delete
    void deleteTask(Note note);
}

Step 4: Component 3 in room - Create Database class This is an abstract class where you define all the entities that means all the tables that you want to create for that database. We define the list of operation that we would like to perform on table Example: NoteDatabase.java

@Database(entities = {Note.class}, version = 1, exportSchema = false)
public abstract class NoteDatabase extends RoomDatabase {

    public abstract DaoAccess daoAccess();
}

Step 5: Create the Repository class A Repository mediates between the domain and data mapping layers, acting like an in-memory domain object collection. We access the database class and the DAO class from the repository and perform list of operations such as insert, update, delete, get Example: NoteRepository.java

public class NoteRepository {

    private String DB_NAME = "db_task";

    private NoteDatabase noteDatabase;
    public NoteRepository(Context context) {
        noteDatabase = Room.databaseBuilder(context, NoteDatabase.class, DB_NAME).build();
    }

    public void insertTask(String title,
                           String description) {

        insertTask(title, description, false, null);
    }

    public void insertTask(String title,
                           String description,
                           boolean encrypt,
                           String password) {

        Note note = new Note();
        note.setTitle(title);
        note.setDescription(description);
        note.setCreatedAt(AppUtils.getCurrentDateTime());
        note.setModifiedAt(AppUtils.getCurrentDateTime());
        note.setEncrypt(encrypt);


        if(encrypt) {
            note.setPassword(AppUtils.generateHash(password));
        } else note.setPassword(null);

        insertTask(note);
    }

    public void insertTask(final Note note) {
        new AsyncTask<Void, Void, Void>() {
            @Override
            protected Void doInBackground(Void... voids) {
                noteDatabase.daoAccess().insertTask(note);
                return null;
            }
        }.execute();
    }

    public void updateTask(final Note note) {
        note.setModifiedAt(AppUtils.getCurrentDateTime());

        new AsyncTask<Void, Void, Void>() {
            @Override
            protected Void doInBackground(Void... voids) {
                noteDatabase.daoAccess().updateTask(note);
                return null;
            }
        }.execute();
    }

    public void deleteTask(final int id) {
        final LiveData<Note> task = getTask(id);
        if(task != null) {
            new AsyncTask<Void, Void, Void>() {
                @Override
                protected Void doInBackground(Void... voids) {
                    noteDatabase.daoAccess().deleteTask(task.getValue());
                    return null;
                }
            }.execute();
        }
    }

    public void deleteTask(final Note note) {
        new AsyncTask<Void, Void, Void>() {
            @Override
            protected Void doInBackground(Void... voids) {
                noteDatabase.daoAccess().deleteTask(note);
                return null;
            }
        }.execute();
    }

    public LiveData<Note> getTask(int id) {
        return noteDatabase.daoAccess().getTask(id);
    }

    public LiveData<List<Note>> getTasks() {
        return noteDatabase.daoAccess().fetchAllTasks();
    }
}

Note: DO NOT PERFORM OPERATION ON MAIN THREAD AS APP WILL CRASH

Sample Implementation of basic CRUD operations using ROOM 1. Insert:

   NoteRepository noteRepository = new NoteRepository(getApplicationContext());
   String title = "This is the title of the third task";
   String description = "This is the description of the third task";
   noteRepository.insertTask(title, description);

2. Update:

   NoteRepository noteRepository = new NoteRepository(getApplicationContext());
   Note note = noteRepository.getTask(2);
   note.setEncrypt(true);
   note.setPassword(AppUtils.generateHash("[email protected]"));
   note.setTitle("This is an example of modify");
   note.setDescription("This is an example to modify the second task");

   noteRepository.updateTask(note);

3. Delete:

   NoteRepository noteRepository = new NoteRepository(getApplicationContext());
   noteRepository.deleteTask(3);

4. Get all notes:

   NoteRepository noteRepository = new NoteRepository(getApplicationContext());

   noteRepository.getTasks().observe(appContext, new Observer<List<Note>>() {
       @Override
       public void onChanged(@Nullable List<Note> notes) {
           for(Note note : notes) {
               System.out.println("-----------------------");
               System.out.println(note.getId());
               System.out.println(note.getTitle());
               System.out.println(note.getDescription());
               System.out.println(note.getCreatedAt());
               System.out.println(note.getModifiedAt());
               System.out.println(note.getPassword());
               System.out.println(note.isEncrypt());
            }
        }
    });

5. Get single note by id:

   NoteRepository noteRepository = new NoteRepository(getApplicationContext());
   Note note = noteRepository.getTask(2);

And that's it! It's super simple. You can check out the official documentation here

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].