Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show/Hide ProgessBar from ViewModel using Databinding - MVVM

While getting a response from web service, I would like to Show/Hide a progressBar using ViewModel and dataBinding. Currently, I am having a function loginOnClicked in the ViewModel bound from my layout XML directly.

I want to create a progress bar and implemented it in function loginOnClicked and update the visibility based on that. Can somebody help me with that?

loginActivity

class loginActivity : AppCompatActivity(),SignupResultCallBack {

            override fun onSucces(message: String) {
                Toast.makeText(this,message, Toast.LENGTH_SHORT)
                        .show()
            }

            override fun onError(message: String) {
                Toast.makeText(this,message, Toast.LENGTH_SHORT)
                        .show()
            }


            override fun onCreate(savedInstanceState: Bundle?) {
                super.onCreate(savedInstanceState)
               // setContentView(R.layout.activity_login)



     val activityLoginBinding=DataBindingUtil.setContentView<ActivityLoginBinding(this,R.layout.activity_login)
       activityLoginBinding.viewModel=of(this,LoginViewModelFactory(this)).get(LoginViewModel::class.java)



   link_signup.setOnClickListener() {
        var intent=Intent(this@loginActivity,signupActivity::class.java)
                    startActivity(intent)
                    finish()
                }

                var test=activityLoginBinding.viewModel!!.progBar()
                if(test)
                    progressBar?.visibility=View.VISIBLE

                else
                    progressBar?.visibility=View.GONE

            }
        }

ViewModel

    class LoginViewModel(private var listener: SignupResultCallBack): ViewModel() {
        private val loginUser:UserRequest



        init {
            this.loginUser= UserRequest("","")
        }

         fun loginOnCLicked(v:View){
             var editLogin: Int = loginUser.isDataValid()
                         if (editLogin == 0)
                         listener.onError("entrer votre email")
                        else
                         if (editLogin == 1)
                         listener.onError("email invalide")
                        else
                         if (editLogin == 2)
                         listener.onError("mot de passe invalide")
                        else
                         if (editLogin == 3)
                             listener.onError("entrer votre mot de passe")
                         else
                             if (editLogin == 4)
                                 listener.onError("champs vides")
                             else


                             {
                                 RetrofitClient.instance.loginUser(UserRequest(loginUser.getEmail(), loginUser.getPassword())).enqueue(object : Callback<DefaultResponse> {
                                     override fun onFailure(call: Call<DefaultResponse>, t: Throwable) {
                                         listener.onError("t.message")

                                     }

                                     override fun onResponse(call: Call<DefaultResponse>, response: Response<DefaultResponse>) {

                                         if (response.code() == 400)
                                             listener.onSucces("login or password invalid")
                                         else if (response.code() == 200)
                                             listener.onSucces("success login")


                                     }

                                 })

               }

         }



}

login.xml

<?xml version="1.0" encoding="utf-8"?>
    <layout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools">
        <data>
            <variable
                name="viewModel"
                type="com.example.rahma.alerteaccidentapp.vm.login.LoginViewModel"/>

        </data>



        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="@color/colorBackground"
             tools:context=".ui.login.loginActivity">


            <Button
                android:id="@+id/btn_connexion"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="30dp"
                android:background="@drawable/btn_round"
                android:text="Connexion"
                android:onClick="@{viewModel::loginOnCLicked}"

                android:layout_marginLeft="20dp"
                android:layout_marginRight="20dp"
                android:layout_below="@id/password_Edit"
                android:textAppearance="@style/MySerifBoldbtn"
                android:textColor="@android:color/background_light"
                />



        </RelativeLayout>


    </layout>  
like image 721
Rahma El Ouni Avatar asked Apr 02 '19 22:04

Rahma El Ouni


1 Answers

First Answering your exact question, adding progress bar to the web service loading.

Create a MutableLiveData object in your LoginViewModel

public MutableLiveData<Integer> progress = new MutableLiveData<>();

inside your loginOnCLicked Method

fun loginOnCLicked(v:View){

    progress.setValue(0); //View.VISIBLE

   .

   .

   .

   progress.setValue(8); //View.GONE

}

Add progress bar to your layout with data binding

<ProgressBar
                android:id="@+id/progressBar"
                style="?android:attr/progressBarStyleLarge"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center_horizontal"
                android:layout_marginTop="8dp"
                android:visibility="@{viewModel.progress}" />

Hope this helps.

On the side note, I would request you to change your listener implementation for webservice success/Error case into LiveData. That's the MVVM way of doing things without holding reference of Activity in the ViewModel.

like image 198
rafa Avatar answered Oct 02 '22 14:10

rafa