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 'android.arch.persistence.room:runtime:1.0.0'
annotationProcessor "android.arch.persistence.room:compiler:1.0.0"

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)
 {
 if(INSTANCE==null)
 {
 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

@Entity
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.

@Dao
public interface ItemDao {
    @Insert
    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) {
        super(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) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        return itemlivedata;
    }

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

    class InsertItem extends AsyncTask<Void, Void, Void> {
        @Override
        protected void doInBackground(Void... voids) {
            appDatabase.ItemDao().insert(item);
        }
    }
}

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.support.v7.widget.AppCompatSpinner
    android:id="@+id/item_spinner"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="10dp" />

<android.support.v7.widget.AppCompatEditText
    android:id="@+id/item_et"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="10dp"
    android:ems="10"
    android:hint="item..." />

<android.support.v7.widget.AppCompatButton
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/saveitem_btn"
    android:layout_margin="10dp"
    android:gravity="center"
    android:padding="10dp"
    android:text="save"
    />

MainActivity.xml:-

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<>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        //initialize
        item_et = (AppCompatEditText) findViewById(R.id.item_et);
        item_spinner = (AppCompatSpinner) findViewById(R.id.item_spinner);
        mSaveitem_btn = (AppCompatButton) findViewById(R.id.saveitem_btn);
        mSaveitem_btn.setOnClickListener(this);
        
        //spinner-adapter
        aa = new ArrayAdapter(this, android.R.layout.simple_spinner_item,itemsname);
        aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        item_spinner.setAdapter(aa);
        
        //getviewmodel
        itemviewmodel = ViewModelProviders.of(this).get(ItemViewModel.class);
        
        //livedataobserver
        itemviewmodel.getAllItems().observe(this,
                                          new android.arch.lifecycle.Observer<List<Item>>() 
          {
            @Override
            public void onChanged(@Nullable List<Item> newitems) {
                if (newitems != null) {
                    items =newitems;
                   itemsname.clear();
                    for (int i = 0; i < items.size(); i++) {
                        itemsname.add(items.get(i).getItemName());
                    }
                    aa.notifyDataSetChanged();
                }
            }
        });
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.saveitem_btn:
                //add item to database
                String itemname = item_et.getText().toString();
                Item item = new Item();
                item.setItemname(itemname);
                itemviewmodel.insert(item);
                break;
        }
    }
}

Posted

in

by

Recent Post

  • AI Chatbots for Sales Team Automation: The Critical Role of AI Sales Assistants in Automating Your Sales Team

    Sales teams are the heart of any successful business, but managing them effectively can often feel like trying to juggle flaming swords. The constant pressure to generate leads, maintain relationships, and close deals leaves your team overwhelmed, spending more time on administrative tasks than actual selling. Here’s where AI-powered sales assistants step in to completely […]

  • Transforming HR with AI Assistants: The Comprehensive Guide

    The role of Human Resources (HR) is critical for the smooth functioning of any organization, from handling administrative tasks to shaping workplace culture and driving strategic decisions. However, traditional methods often fall short of meeting the demands of a modern, dynamic workforce. This is where our Human Resource AI assistants enter —a game-changing tool that […]

  • How Conversational AI Chatbots Improve Conversion Rates in E-Commerce?

    The digital shopping experience has evolved, with Conversational AI Chatbots revolutionizing customer interactions in e-commerce. These AI-powered systems offer personalized, real-time communication with customers, streamlining the buying process and increasing conversion rates. But how do Conversational AI Chatbots improve e-commerce conversion rates, and what are the real benefits for customers? In this blog, we’ll break […]

  • 12 Essential SaaS Metrics to Track Business Growth

    In the dynamic landscape of Software as a Service (SaaS), the ability to leverage data effectively is paramount for long-term success. As SaaS businesses grow, tracking the right SaaS metrics becomes essential for understanding performance, optimizing strategies, and fostering sustainable growth. This comprehensive guide explores 12 essential SaaS metrics that every SaaS business should track […]

  • Bagging vs Boosting: Understanding the Key Differences in Ensemble Learning

    In modern machine learning, achieving accurate predictions is critical for various applications. Two powerful ensemble learning techniques that help enhance model performance are Bagging and Boosting. These methods aim to combine multiple weak learners to build a stronger, more accurate model. However, they differ significantly in their approaches. In this comprehensive guide, we will dive […]

  • What Is Synthetic Data? Benefits, Techniques & Applications in AI & ML

    In today’s data-driven era, information is the cornerstone of technological advancement and business innovation. However, real-world data often presents challenges—such as scarcity, sensitivity, and high costs—especially when it comes to specific or restricted datasets. Synthetic data offers a transformative solution, providing businesses and researchers with a way to generate realistic and usable data without the […]

Click to Copy