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

  • Agentic AI Explained: Definition, Benefits, Challenges and Use Cases

    Artificial Intelligence (AI) has evolved significantly, transitioning from rule-based systems to more dynamic, learning-based models. Among the latest advancements is Agentic AI, an AI paradigm that enhances autonomy, decision-making, and self-improvement capabilities. Unlike traditional AI, which primarily follows predefined rules or models, Agentic AI exhibits goal-oriented behavior, adapts to complex environments, and makes decisions with […]

  • AI in payment: Key applications, advantages, and regulatory considerations

    The financial landscape is undergoing a profound transformation, driven by the rapid advancements in artificial intelligence (AI). From enhancing security to streamlining transactions, AI is revolutionizing how we make payments, making the process faster, safer, and more seamless. The global AI in payments market is projected to reach an impressive USD 12.7 billion by 2026, […]

  • Generative AI for IT: Integration approaches, use cases, challenges, ROI evaluation and future outlook

    Generative AI is a game-changer in the IT sector, driving significant cost reductions and operational efficiencies. According to a BCG analysis, Generative AI (GenAI) has the potential to deliver up to 10% savings on IT spending—a transformation that is reshaping multiple facets of technology. The impact is especially profound in application development, where nearly 75% […]

  • Generative AI in Manufacturing: Integration approaches, use cases and future outlook

    Generative AI is reshaping manufacturing by providing advanced solutions to longstanding challenges in the industry. With its ability to streamline production, optimize resource allocation, and enhance quality control, GenAI offers manufacturers new levels of operational efficiency and innovation. Unlike traditional automation, which primarily focuses on repetitive tasks, GenAI enables more dynamic and data-driven decision-making processes, […]

  • Generative AI in Healthcare: Integration, use cases, challenges, ROI, and future outlook

    Generative AI (GenAI) is revolutionizing the healthcare industry, enabling enhanced patient care, operational efficiency, and advanced decision-making. From automating administrative workflows to assisting in clinical diagnoses, GenAI is reshaping how healthcare providers, payers, and technology firms deliver services. A Q1 2024 survey of 100 US healthcare leaders revealed that over 70% have already implemented or […]

  • Generative AI in Hospitality: Integration, Use Cases, Challenges, and Future Outlook

    Generative AI is revolutionizing the hospitality industry, redefining guest experiences, and streamlining operations with intelligent automation. According to market research, the generative AI market in the hospitality sector was valued at USD 16.3 billion in 2023 and is projected to skyrocket to USD 439 billion by 2033, reflecting an impressive CAGR of 40.2% from 2024 […]

Click to Copy