0

I am trying to use ViewModel for making API calls, But when I cick the button to send the phone number for OTP the app breaks and their is not information in the logcat too.

Code of LoginActivity.kt `

class LoginActivity : AppCompatActivity() {
    private lateinit var binding: ActivityLoginBinding
    private lateinit var viewModel: LoginViewModel

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityLoginBinding.inflate(layoutInflater)
        setContentView(binding.root)

        viewModel = LoginViewModelFactory(LoginService.create()).create(LoginViewModel::class.java)
        binding.loginViewModel = viewModel
        binding.lifecycleOwner = this

        binding.continueButton.setOnClickListener {
            viewModel.onLogin()
        }

        viewModel.login.observe(this){
            gotoOTP()
        }
    }
    fun gotoOTP(){
        var intent = Intent(this@LoginActivity, OTPLoginVerification::class.java)
        intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_TASK_ON_HOME
        this.startActivity(intent)
        this.finish()
    }
}

`

code for LoginViewModel.kt `

class LoginViewModel(var loginService: LoginService) : ViewModel(), Observable {

    val phoneNumber: MutableLiveData<String> = MutableLiveData()
    val login = MutableLiveData<Unit>()

    fun onLogin(){
            loginService.getOTP(LoginRequestModel(phone_no = phoneNumber.value.toString()))
                .enqueue(object: Callback<LoginResponseModel>{
                    override fun onResponse(call: Call<LoginResponseModel>, response: Response<LoginResponseModel>) {

                        if(response.isSuccessful) {
                            if (response.body()!!.result) login.postValue(Unit)
                            else print("Error")
                        }
                        else{
                            print("Error")
                        }
                    }

                    override fun onFailure(call: Call<LoginResponseModel>, t: Throwable) {
                        print("Error")
                    }

                })
        }
    
    override fun addOnPropertyChangedCallback(callback: Observable.OnPropertyChangedCallback?) {

    }

    override fun removeOnPropertyChangedCallback(callback: Observable.OnPropertyChangedCallback?) {

    }
}

`

code for LoginViewModelFactory.kt `

class LoginViewModelFactory(private val loginService: LoginService): ViewModelProvider.Factory{

    override fun <T : ViewModel> create(modelClass: Class<T>): T {
        if(modelClass.isAssignableFrom(LoginViewModel::class.java)){
            return LoginViewModel(loginService) as T
        }
        else throw IllegalArgumentException("Error Unknown ViewModel Type")
    }
}

And this is the service Interface

interface LoginService {

    @POST("getOTP")
    fun getOTP(@Body model: LoginRequestModel) : Call<LoginResponseModel>

    companion object{

        val BASE_URL = "*********"

        fun create(): LoginService{
            val client = OkHttpClient.Builder()
            client.connectTimeout(2, TimeUnit.MINUTES)
            client.readTimeout(2, TimeUnit.MINUTES)
            client.writeTimeout(2, TimeUnit.MINUTES)
            val gson = GsonBuilder()
                .serializeNulls()
                .setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ")
                .setLenient()
                .create()
            val retrofit = Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create(gson))
                .client(client.build())
                .build()
            return retrofit.create(LoginService::class.java)
        }
    }

}
<?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="LoginViewModel"
        type="com.example.sample.viewmodels.LoginViewModel" />
</data>

<ScrollView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".Auth.LoginActivity">

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <com.google.android.material.card.MaterialCardView
            android:layout_width="0dp"
            android:layout_height="0dp"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintBottom_toBottomOf="@id/g_h_1"
            app:cardBackgroundColor="@color/peach_dark"

            style="@style/CustomCardViewStyle">

            <androidx.constraintlayout.widget.ConstraintLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent">

                <ImageView
                    android:layout_width="0dp"
                    android:layout_height="0dp"
                    android:scaleType="fitXY"
                    app:layout_constraintEnd_toEndOf="parent"
                    app:layout_constraintBottom_toBottomOf="parent"
                    app:layout_constraintStart_toStartOf="parent"
                    app:layout_constraintTop_toTopOf="parent"
                    app:layout_constraintDimensionRatio="1.2:1"
                    android:src="@drawable/loginimage" />


            </androidx.constraintlayout.widget.ConstraintLayout>
        </com.google.android.material.card.MaterialCardView>

        <ImageView
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:scaleType="fitCenter"
            android:src="@drawable/logo"
            app:layout_constraintDimensionRatio="3:1"
            app:layout_constraintTop_toTopOf="@id/g_h_2"
            app:layout_constraintStart_toStartOf="@id/g_v_2"
            app:layout_constraintEnd_toEndOf="@id/g_v_3"
            app:layout_constraintBottom_toBottomOf="@id/g_h_3" />

        <TextView
            android:id="@+id/company_highlight"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:text="@string/company_highlight"
            android:layout_marginTop="10dp"
            app:layout_constraintStart_toStartOf="@id/g_v_1"
            app:layout_constraintEnd_toEndOf="@id/g_v_4"
            app:layout_constraintTop_toTopOf="@id/g_h_3"
            android:textAlignment="center"
            android:textSize="20dp"
            android:fontFamily="@font/metropolisbold"
            android:textColor="@color/t_dark" />

        <TextView
            android:id="@+id/login_textview"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:text="@string/login_text"
            android:layout_marginTop="20dp"
            app:layout_constraintStart_toStartOf="@id/g_v_1"
            app:layout_constraintEnd_toEndOf="@id/g_v_4"
            app:layout_constraintTop_toBottomOf="@id/company_highlight"
            android:textAlignment="center"
            android:textSize="17dp"
            android:fontFamily="@font/metropolissemibold" />

        <androidx.gridlayout.widget.GridLayout
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:id="@+id/gridview_mobilenumber"
            app:layout_constraintStart_toStartOf="@id/g_v_1"
            app:layout_constraintEnd_toEndOf="@id/g_v_4"
            app:layout_constraintTop_toBottomOf="@+id/login_textview"
            android:layout_marginTop="25dp"
            app:columnCount="2">

            <com.google.android.material.card.MaterialCardView
                android:id="@+id/country_flag_cardview"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                app:layout_column="0"
                android:padding="10dp"
                app:layout_columnWeight="0.4"
                app:cardCornerRadius="10dp"
                app:layout_rowWeight="1"
                android:layout_marginLeft="3dp"
                app:strokeWidth="1dp"
                app:strokeColor="@color/t_light">

                <RelativeLayout
                    android:layout_width="match_parent"
                    android:layout_height="match_parent">

                    <ImageView
                        android:id="@+id/country_flag"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_alignParentLeft="true"
                        android:padding="5dp"
                        android:src="@drawable/indianflag" />

                    <ImageView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_toRightOf="@id/country_flag"
                        android:layout_centerVertical="true"
                        android:src="@drawable/dropdown" />
                </RelativeLayout>
            </com.google.android.material.card.MaterialCardView>

            <com.google.android.material.card.MaterialCardView
                android:id="@+id/mobile_number_cardview"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                app:layout_column="1"
                android:padding="10dp"
                android:layout_marginLeft="10dp"
                app:layout_columnWeight="20"
                app:layout_rowWeight="1"
                app:cardCornerRadius="10dp"
                app:strokeWidth="1dp"
                app:strokeColor="@color/t_light">

                <RelativeLayout
                    android:layout_width="match_parent"
                    android:layout_height="match_parent">

                    <TextView
                        android:id="@+id/country_code_textview"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_centerVertical="true"
                        android:fontFamily="@font/metropolissemibold"
                        android:text="@string/country_code"
                        android:layout_alignParentLeft="true"
                        android:layout_marginLeft="5dp"
                        android:textColor="@color/t_dark"
                        android:textSize="22dp" />

                    <EditText
                        android:id="@+id/mobile_number_edittext"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_centerVertical="true"
                        android:layout_marginLeft="10dp"
                        android:layout_toRightOf="@+id/country_code_textview"
                        android:background="@null"
                        android:fontFamily="@font/metropolislight"
                        android:hint="@string/enter_mobile"
                        android:text="@{LoginViewModel.phoneNumber}"
                        android:inputType="phone"
                        android:maxLength="10"
                        android:textColor="@color/t_dark"
                        android:textColorHint="@color/t_light"
                        android:textSize="15dp" />


                </RelativeLayout>
            </com.google.android.material.card.MaterialCardView>
        </androidx.gridlayout.widget.GridLayout>

        <TextView
            android:id="@+id/new_user_textview"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="New User"
            android:textSize="15dp"
            android:fontFamily="@font/metropolisbold"
            app:layout_constraintEnd_toEndOf="@id/g_v_4"
            app:layout_constraintTop_toBottomOf="@id/gridview_mobilenumber"
            android:textColor="@color/peach_700"
            android:layout_marginTop="5dp" />

        <com.google.android.material.button.MaterialButton
            android:id="@+id/continue_button"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            app:layout_constraintStart_toStartOf="@id/g_v_1"
            app:layout_constraintEnd_toEndOf="@id/g_v_4"
            app:layout_constraintTop_toBottomOf="@id/new_user_textview"
            android:text="Continue"
            android:fontFamily="@font/metropolissemibold"
            android:textAllCaps="false"
            android:textSize="17dp"
            app:cornerRadius="10dp"
            android:layout_marginTop="20dp" />


        <androidx.constraintlayout.widget.Guideline
            android:id="@+id/g_h_1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            app:layout_constraintGuide_percent="0.45" />

        <androidx.constraintlayout.widget.Guideline
            android:id="@+id/g_h_2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            app:layout_constraintGuide_percent="0.47" />

        <androidx.constraintlayout.widget.Guideline
            android:id="@+id/g_h_3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            app:layout_constraintGuide_percent="0.54" />

        <androidx.constraintlayout.widget.Guideline
            android:id="@+id/g_v_1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            app:layout_constraintGuide_percent="0.10" />

        <androidx.constraintlayout.widget.Guideline
            android:id="@+id/g_v_2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            app:layout_constraintGuide_percent="0.30" />

        <androidx.constraintlayout.widget.Guideline
            android:id="@+id/g_v_3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            app:layout_constraintGuide_percent="0.70" />

        <androidx.constraintlayout.widget.Guideline
            android:id="@+id/g_v_4"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            app:layout_constraintGuide_percent="0.90" />

    </android.constraintlayout.widget.ConstraintLayout>
</ScrollView>

To the best of my knowledge I tried to make changes but nothing worked. Any help would be great, As I am unable to find the place where I am making mistake. Thanks in Advance.

0 Answers0