View Model State in android studio: Kotlin

1.1k Views Asked by At

As I was working on this code yesterday after I tried using SaveInstanceState for saving my textview output while changing my orientation from portrait to landscape mode but it didn't work. so i thought and realized that i could work it out using View Model state but. unlike SaveInstance State, I tried doing View Model but i find it little tough to do and fix the errors, here is the code for main activity and ViewModel

Main Activity kotlin

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

        var count = 10
        val textCount = findViewById<View>(R.id.textView) as TextView
         val buttonred = findViewById<View>(R.id.injury) as Button
         
         val buttoning = findViewById<View>(R.id.revive) as Button


            var viewModel = ViewModelProvider(this).get(MainActivityViewModel::class.java)

            buttonred.setOnClickListener {
                if (count >= 0) {

                   count--
                    textCount.text = count.toString()
                }

            }
           
            buttoning.setOnClickListener {
                if (count <= 10) {
                    count += 2
                    textCount.text = count.toString()
                }
            }
    }
}

Viewmodel kotlin code (note: i just started working on it, but i have no idea how to work it out)

class MainActivityViewModel: ViewModel() {
    var count = 10
    fun medivial()
    {
        count--
    }
}

here is the xml file

<LinearLayout 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"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/textView"
        android:layout_width="60dp"
        android:layout_height="78dp"
        android:layout_marginStart="145dp"
        android:layout_marginTop="68dp"
        android:layout_marginEnd="145dp"
        android:textSize="50dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
<Button
        android:id="@+id/injury"
        android:layout_width="106dp"
        android:layout_height="wrap_content"
        android:layout_marginHorizontal="150dp"
        android:text="injury"
         />
<Button
        android:id="@+id/revive"
        android:layout_width="197dp"
        android:layout_height="wrap_content"
        android:layout_marginHorizontal="109dp"
        android:text="revive" />
</LinearLayout>

need help on this

1

There are 1 best solutions below

0
On

You have to add LiveData to the ViewModel class and observe it. Your activity class cannot have any data like count. ViewModel has to carry all actions and just give data to View (MainActivity)

To Your Gradle (module.app) file add:

dependencies {
    def lifecycle_version = "2.2.0"

    // ViewModel
    implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:$lifecycle_version"
    // LiveData
    implementation "androidx.lifecycle:lifecycle-livedata-ktx:$lifecycle_version"
}

MainActivityViewModel class:

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel


internal class MainActivityViewModel : ViewModel() {

    private val _count: MutableLiveData<Int> = MutableLiveData()
    val count: LiveData<Int>
        get() = _count

    init {
        _count.value = START_VALUE
    }

    fun increment() {
        _count.value = _count.value!! + 1
    }

    fun decrement() {
        _count.value = _count.value!! - 1

    }

    companion object {
        private const val START_VALUE = 10
    }
}

MainActivity class:

import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.ViewModelProvider

class MainActivity : AppCompatActivity()
{
    private lateinit var viewModel: MainActivityViewModel

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

        val textCount = findViewById<View>(R.id.textView) as TextView
        val butIncrement = findViewById<View>(R.id.injury) as Button
        val butDecrement = findViewById<View>(R.id.vial) as Button

        viewModel = ViewModelProvider(this).get(MainActivityViewModel::class.java)

        viewModel.count.observe(this, {
            textCount.text = it.toString()
        })

        butIncrement.setOnClickListener {
            viewModel.increment()
        }

        butDecrement.setOnClickListener {
            viewModel.decrement()
        }
    }
}