How to refresh ScrollView/LinearLayout in Kotlin

Issue

i’m trying to solve my problem. When I made some basic weather app. When I open new activity I can add city to favourite list. The problem is when i push back button, I need to refresh scrollview, but i dont know how. I tried onBackPressed but it doesn’t work.

Here is a part of code

fun showWeather(searchedCity: String?) {
        var city: CityObject
        if (searchedCity.isNullOrEmpty()) {
            Toast.makeText(applicationContext, "NEED TO WRITE CITY!", Toast.LENGTH_LONG).show()
        }

        // Need have threat cause internet
        thread  Thread {
            // getting data
            var jsonData  jsonParser.getJsonData("$searchedCity")
            if (!jsonData.isNullOrEmpty()) {
                //parsing data
                city  jsonParser.parseJsonData(jsonData)!!
                // for start another activity
                startActivity(city)
            }
        }
        thread.start()
        textInputEditText.text?.clear()
    }

    //showing weather
    fun startActivity(city: CityObject) {
        runOnUiThread {
            val intent  Intent(this, WeatherActivity::class.java)
            intent.putExtra("CITY_OBJECT", city)
            startActivity(intent)
        }
    }

    // making favourite cities buttons
    fun getFavouriteCities() {
        linInScroll.removeAllViews()
        linInScroll.setOrientation(LinearLayout.VERTICAL);

        for (cityName in DB.getData()) {
            val button  Button(this)
            button.setText("$cityName")
            button.setTextSize(1, 20F)
            button.setOnClickListener {
                showWeather("$cityName")
            }
            linInScroll.addView(button)
        }
    }

List of favourite cities

enter image description here

Thanks for help

Solution

Each time your activity comes to foreground onResume method is called.

override fun onResume() {
    super.onResume()

    getFavouriteCities()
}

There are other lifecycle events that you might want to take a look.

Do check out android activity lifecycle for better understanding.

Android lifecycle

Answered By – shb

Leave a Comment