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

  • Generative AI in HR Operations: Overview, Use Cases, Challenges, and Future Trends

    Overview Imagine a workplace where HR tasks aren’t bogged down by endless paperwork or repetitive chores, but instead powered by intelligent systems that think, create, and adapt—welcome to the world of GenAI. Generative AI in HR operations offers a perfect blend of efficiency, personalization, and strategic insight that transforms how organizations interact with their talent. […]

  • Generative AI in Sales: Implementation Approaches, Use Cases, Challenges, Best Practices, and Future Trends

    The world of sales is evolving at lightning speed. Today’s sales teams are not just tasked with meeting ambitious quotas but must also navigate a maze of complex buyer journeys and ever-rising customer expectations. Despite relying on advanced CRM systems and various sales tools, many teams remain bogged down by repetitive administrative tasks, a lack […]

  • Generative AI in Due Diligence: Integration Approaches, Use Cases, Challenges, and Future Outlook

    Generative AI is revolutionizing the due diligence landscape, setting unprecedented benchmarks in data analysis, risk management, and operational efficiency. By combining advanced data processing capabilities with human-like contextual understanding, this cutting-edge technology is reshaping traditional due diligence processes, making them more efficient, accurate, and insightful. This comprehensive guide explores the integration strategies, practical applications, challenges, […]

  • Exploring the Role of AI in Sustainable Development Goals (SDGs)

    Artificial Intelligence (AI) is revolutionizing how we address some of the world’s most pressing challenges. As we strive to meet the United Nations’ Sustainable Development Goals (SDGs) by 2030, AI emerges as a powerful tool to accelerate progress across various domains. AI’s potential to contribute to sustainable development is vast from eradicating poverty to combating […]

  • Future Trends in AI Chatbots: What to Expect in the Next Decade

    Artificial Intelligence (AI) chatbots have become indispensable across industries. The absolute conversational capabilities of AI chatbots are enhancing customer engagement, streamlining operations, and transforming how businesses interact with users. As technology evolves, the future of AI chatbots holds revolutionary advancements that will redefine their capabilities. So, let’s start with exploring the AI chatbot trends: Future […]

  • Linguistics and NLP: Enhancing AI Chatbots for Multilingual Support

    In today’s interconnected world, businesses and individuals often communicate across linguistic boundaries. The growing need for seamless communication has driven significant advancements in artificial intelligence (AI), particularly in natural language processing (NLP) and linguistics. AI chatbots with multilingual support, are revolutionizing global customer engagement and service delivery. This blog explores how linguistics and NLP are […]

Click to Copy