Menu
Who Do Is
  • Home
  • What
  • How
  • Is
  • Can
  • Are
  • Does
  • Do
  • Why
  • Who
  • Where
  • Which
  • Which
  • Should
  • Will
  • When
  • What’s
  • Did
Who Do Is

[ANSWERED] View Model State in android studio: Kotlin

Posted on November 14, 2022

Solution 1 :

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()
        }
    }
}

Problem :

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

READ  [ANSWERED] android - Reuse layouts and fragments
Powered by Inline Related Posts

Recent Posts

  • How can I play with my cat without toys?
  • What is a bag pipe band called?
  • Are Honda Civics actually fast?
  • Are Yankee candles toxic?
  • How do I pair my Michael Kors smartwatch with my Android?

Recent Comments

No comments to show.

Archives

  • January 2023
  • December 2022
  • November 2022
  • October 2022
  • September 2022

Categories

  • ¿Cómo
  • ¿Cuál
  • ¿Cuántas
  • ¿Cuánto
  • ¿Que
  • ¿Quién
  • 90” and 108” so you may have to round up to the nearest size.
  • and delete any Spotify folders from it. Once this is done
  • Android
  • Are
  • At
  • Bei
  • blink
  • C'est
  • Can
  • carbs
  • Comment
  • Did
  • Do
  • Does
  • During
  • For
  • Has
  • How
  • In
  • Is
  • Ist
  • Kann
  • Können
  • nouveau
  • On
  • or 108 inches.2020-08-03
  • Où
  • owning
  • Pourquoi
  • Puis-je
  • Quand
  • Quante
  • Quel
  • Quelle
  • Quelles
  • Quels
  • Qui
  • Should
  • Sind
  • Sollte
  • spiritual
  • tap the downward-facing arrow on the top left. A downward-facing arrow will appear underneath each song in the album; they'll turn green as the download completes.2020-07-28
  • Uncategorized
  • Wann
  • Warum
  • Was
  • Welche
  • Welcher
  • Welches
  • Welke
  • Wer
  • Were
  • What
  • What's
  • When
  • Where
  • Which
  • Who
  • Whose
  • Why
  • Wie
  • Will
  • Wo
  • Woher
  • you will receive two curtains each with the same measurements of width 66"" (168cm) x drop 54""(137cm).
  • you'll see a green downward-facing arrow next to each song.2021-02-26
©2023 Who Do Is | Powered by SuperbThemes & WordPress