/** * Functions hooked into colormag_action_head action. * * @hooked colormag_head - 10 */ do_action( 'colormag_action_head' ); wp_head(); ?>

Android ViewModel tutorial with Example

In this tutorial,we will learn a very important Android Architecture Components known as ViewModel

ViewModel is the part of  jetpack library.It is designed to store and manage the UI(user interface) related data in a life-cycle conscious way.It keeps the data survive when configuration changes such as screen rotation,Keyboard change etc

Problem with onSaveInstanceState( )

When creating the Activity or Fragment then onSaveInstanceState( ) saves the instance of activity or fragment.

But the problem with that,when rotating the screen then the instance of activity or fragment is destroyed so there are chances of leakage of memory.

So removing this type of problem,Android launched a new  library named  “ViewModel”.

Advantage of ViewModel

1.Prevent from the memory leakage

2.It separate the  User Interface(UI) from the business logic.

3.Retains the data during the configuration change

4.ViewModel objects will often store LiveData objects

Now,How to use ViewModel in Android Studio project

To use ViewModel in our project,first of all we will have to add below dependencies inside the app/build.gradle file.

After that,Create ViewModel class ie UserViewModelClass

public class UserViewModelClass extends ViewModel
private List<User> users;

public List<User> getUserList( )
users=loadusers( );
return users;
private List<user> loadUsers( )
//perform any operations as you want

Here,ViewModel is a helper class for the UI controller that is responsible for preparing data for the UI(User interface).ViewModel objects retain data automatically on the configuration change.

Now,We can access the userlist from an activity as follow

public class UserListActivity extends AppCompatActivity

protected void onCreate(Bundle onSaveInstancestate)

UserViewModelClass obj=ViewModelProvides.of(this).get(UserViewModelClass.class);

userData(obj.getUserList( ));

To get our ViewModel inside an Activity we use “ViewModelProviders.of( )”.

Now,Let’s look

onSaveInstanceState( ) vs ViewModel

onSaveInstanceState( ) 

1.In onSaveInstanceState( ),we can store only small amount of data

2.It store the activity record until the application killed


1.In ViewModel,We can store large amount of data

2.ViewModel cleaned the data once the user finish the activity

I hope,It will help you to make robust  & fast applications with the new jetpack library “ViewModel” for the persistence of data during screen rotation etc

Best of Luck!!!


Hello Friends,I have written and developed this website because you can learn technology easily ,prepare for the placement and also for the any type of examination . By :Suman Kumar

Leave a Reply

Your email address will not be published. Required fields are marked *