Android LIvedata with ViewModel And Room

Hey folks, in this post we are going to implement livedata with SpinnerLiveData is an observable data holder class. Unlike a regular observable, LiveData is lifecycle-aware, meaning it respects the lifecycle of other app components, such as activities, fragments, or services. This awareness ensures LiveData only updates app component observers that are in an active lifecycle state. To know more about livedata and ViewModel ->LiveData,ViewModel

Before moving further, you should atleast have a basic idea of Room working and for that you can check our bloggetting-started-with-room or google-docs-for-room.

Create a new project and add dependencies for Room, ViewModel, Livedata:

// ViewModel and LiveData
implementation 'android.arch.lifecycle:extensions:1.0.0'
implementation 'android.arch.lifecycle:common-java8:1.0.0'
// Room
implementation ''
annotationProcessor ""

Create a Database, Entity, Dao(Data Access Object) for room:-

Database:- This class will be used to create Database, get Database instance and  Dao. “app_database” is our database name.

@Database(entities = {Item.class}, version = 1,exportSchema = false)
public abstract class AppDatabase extends RoomDatabase {
 private static AppDatabase INSTANCE;
 public static AppDatabase getDatabase(Context context)
 INSTANCE= Room.databaseBuilder(context,AppDatabase.class,"app_database").build();
 return INSTANCE;
 public abstract ItemDao itemDao();

Entity:- This class will have a mapping SQLite table in the database

public class Item {
    private String itemname;
    @PrimaryKey(autoGenerate = true)
    private int _id;

    public String getItemname() {
        return itemname;

    public void set_id(int _id) {
        this._id = _id;

    public void setItemname(String itemname) {
        this.itemname =itemname;

    public int get_id() {
        return _id;

Dao:-This class will be used for accessing the table. In our project we just need to insert Item and fetch all list.

public interface ItemDao {
    public void insert(Item item);

    @Query("select * from Item")
    public LiveData<List<Item>> getAllItems();

ViewModel:-The ViewModel class is designed to store and manage UI-related data in a lifecycle conscious way. The ViewModel class allows data to survive configuration changes such as screen rotations.

If the system destroys or re-creates a UI controller, any transient UI-related data you store in them is lost. For example, your app may include a list of users in one of its activities. When the activity is re-created for a configuration change, the new activity has to re-fetch the list of users. For simple data, the activity can use the onSaveInstanceState() method and restore its data from the bundle in onCreate(), but this approach is only suitable for small amounts of data that can be serialized then deserialized, not for potentially large amounts of data like a list of users or bitmaps.

Another problem is that UI controllers frequently need to make asynchronous calls that may take some time to return. The UI controller needs to manage these calls and ensure the system cleans them up after it’s destroyed to avoid potential memory leaks. This management requires a lot of maintenance, and in the case where the object is re-created for a configuration change, it’s a waste of resources since the object may have to reissue calls it has already made.

UI controllers such as activities and fragments are primarily intended to display UI data, react to user actions, or handle operating system communication, such as permission requests. Requiring UI controllers to also be responsible for loading data from a database or network adds bloat to the class. Assigning excessive responsibility to UI controllers can result in a single class that tries to handle all of an app’s work by itself, instead of delegating work to other classes. Assigning excessive responsibility to the UI controllers in this way also makes testing a lot harder.It’s easier and more efficient to separate out view data ownership from UI controller logic.

Our ViewModel:- for creating a viewmodel class you can either extend the AndroidViewModel class(if context is required as it contains application context)  or ViewModel class.

public class ItemViewModel extends AndroidViewModel {
    private final Application application;
    private final AppDatabase appDatabase;

    public ItemViewModel(@NonNull Application application) {
        this.application = application;
        appDatabase = AppDatabase.getDatabase(this.getApplication());

    public void insert(final Item item) {
        new InsertItem().execute();

    public LiveData<List<Item>> getAllItems() {
        LiveData<List<Item>> itemlivedata = null;
        try {
            itemlivedata = new LoadAllItems().execute().get();
        } catch (InterruptedException e) {
        } catch (ExecutionException e) {
        return itemlivedata;

    class LoadAllItems extends AsyncTask<Void, Void, LiveData<List<Item>>> {
        protected LiveData<List<Item>> doInBackground(Void... voids) {
            return appDatabase.ItemDao().getAllItems();

    class InsertItem extends AsyncTask<Void, Void, Void> {
        protected void doInBackground(Void... voids) {

activity_main.xml :- In Our activity_main.xml we are going to add a edittext, button and spinner, edittext to add items in database and spinner to show all the items available in room.

    android:layout_marginTop="10dp" />

    android:hint="item..." />



Whenever the livedata data changes, onChanged method of the observer is called. Generally, LiveData delivers updates only when data changes, and only to active observers. An exception to this behavior is that observers also receive an update when they change from an inactive to an active state. Furthermore, if the observer changes from inactive to active a second time, it only receives an update if the value has changed since the last time it became active.

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private AppCompatEditText item_et;
    private AppCompatSpinner item_spinner;
    private AppCompatButton mSaveitem_btn;
    private List<Item> items = new ArrayList<>();
    private ArrayAdapter aa;
    private ItemViewModel itemviewmodel;
    private ArrayList<String> itemsname = new ArrayList<>();
    protected void onCreate(Bundle savedInstanceState) {
        item_et = (AppCompatEditText) findViewById(;
        item_spinner = (AppCompatSpinner) findViewById(;
        mSaveitem_btn = (AppCompatButton) findViewById(;
        aa = new ArrayAdapter(this, android.R.layout.simple_spinner_item,itemsname);
        itemviewmodel = ViewModelProviders.of(this).get(ItemViewModel.class);
                                          new android.arch.lifecycle.Observer<List<Item>>() 
            public void onChanged(@Nullable List<Item> newitems) {
                if (newitems != null) {
                    items =newitems;
                    for (int i = 0; i < items.size(); i++) {

    public void onClick(View view) {
        switch (view.getId()) {
                //add item to database
                String itemname = item_et.getText().toString();
                Item item = new Item();




Recent Post

  • How to Connect A Biometric Attendance Device to a System through JS and Node.js?

    In the world of highly advanced workspaces, the utilization of biometric attendance structures has come to be important for accurate and steady tracking of worker or student attendance. This blog publishes objectives to provide a complete guide on integrating a biometric attendance device with a gadget with the use of JavaScript and Node.Js. By making […]

  • How to Implement File Uploads in Node.js with Multer?

    For many web applications that let users share papers, photos, and other types of material, file uploads are a necessary functionality. Multer is a well-liked middleware used for Handling file uploads in Node.js using Multer the Node.js environment to effectively handle file uploads. We’ll look at how to use Multer to create file uploads […]

  • How to Use Local Storage to Persist Data in a JavaScript Application?

    Data persistence is a key aspect of web applications. In JavaScript, one of the primary tools for achieving this is Local Storage, a part of the Web Storage API. This JavaScript data persistence tool provides a simple key-value storage mechanism within the user’s browser. Unlike session storage, which persists data only during a session, Local […]

  • How to Use WordPress API?

    WordPress stands out as a leading content management system, celebrated for its dynamic capabilities in website and blog development. Renowned for its rich feature set and extensive customization options, WordPress empowers creators to fashion captivating online experiences. In recent times, WordPress has expanded its horizons into the realm of APIs, granting developers a potent tool […]

  • How to Use Post and Pre Hooks in Mongoose?

    In Mongoose, a widely-used library for working with MongoDB, there are valuable tools called “Pre and Post Hooks.” These hooks, also known as “Mongoose Middleware” or “Mongoose Model Hooks,” allow developers to run their own code just before or after specific actions on the database. With “Pre Hooks,” you can customize actions before they happen, […]

  • How To Create Reusable Components in React: Best Practices

    Rеact is a popular library for building usеr intеrfacеs with JavaScript. One of the main benefits of Rеact is its ability to create reusable componеnts that can be used in different parts of your application. Reusable componеnts can help you savе timе, rеducе codе duplication, and еnsurе consistеncy in your UI. However, creating rеusablе componеnts […]