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

  • LLMOps Essentials: A Practical Guide To Operationalizing Large Language Models

    When you engage with ChatGPT or any other Generative AI tool, you just type and enter your query and Tada!! You get your answer in seconds. Ever wondered how it happens and how it is so quick? Let’s peel back the curtain of the LLMs a bit. What actually happens behind the screen is a […]

  • Building Intelligent AI Models For Enterprise Success: Insider Strategies 

    Just picture a world where machines think and learn like us. It might sound like a scene straight out of a sci-fi movie, right? Well, guess what? We are already living in that world now. Today, data, clever algorithms, and AI models are changing the way businesses operate. AI models are serving as a brilliant […]

  • Introducing Google Vids in Workspace: Your Ultimate AI-Powered Video Creation Tool

    Hey there, fellow content creators and marketing gurus! Are you tired of drowning in a sea of emails, images, and marketing copy, struggling to turn them into eye-catching video presentations? Fear not, because Google has just unveiled its latest innovation at the Cloud Next conference in Las Vegas: Google Vids- Google’s AI Video Creation tool! […]

  • Achieve High ROI With Expert Enterprise Application Development

    Nowadays modern-day enterprises encounter no. of challenges such as communication breakdown, inefficient business processes, data fragmentation, data security risks, legacy system integration with modern applications, supply chain management issues, lack of data analytics and business intelligence, inefficient customer relationship management, and many more. Ignoring such problems within an organization can adversely impact various aspects of […]

  • State Management with Currying in React.js

    Dive into React.js state management made easy with currying. Say goodbye to repetitive code and hello to streamlined development. Explore the simplicity and efficiency of currying for your React components today!

  • How Much Does It Cost to Develop an App in 2024?

    The price of bringing your app to life typically ranges from $20,000 to $200,000. This cost varies based on factors like which platform you choose, the complexity of features you want, and the size of your intended audience. However, costs can climb even higher for more complex projects, reaching up to $350,000.