0

I am new to Android Studio and also with Kotlin. I am currently making a program that allows users to input and change the name, address, and ratingStar of each location. But while doing so, I ran into a problem of not knowing how to pass the editText value from the detailActivity back to mainActivity.

I searched on multiple guides and tried various Intent passing + onAddTextChangeListener, but nothing works. It always resulted in my rating bar getting deleted in my mainActivity screen.

MainActivity.kt:

package com.example.core_2_kallenvp

import android.app.Activity
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.ImageView
import android.widget.RatingBar
import android.widget.TextView

class MainActivity : AppCompatActivity() {


    var location1 = Location(
        "Go mall Phu Thanh",
        "212 Thoai Ngoc Thau street, Phu Thanh ward, Tan Phu district, HCM city",
        "Day visited: 12/4/2021",
        5f,
        R.drawable.gomall
    )
    var location2 = Location(
        "Aeon mall Tan Phu",
        "30 Bo Bao Tan Thang street, Son Ky ward, Tan Phu district, HCM city",
        "Day visited: 12/4/2020",
        5f,
        R.drawable.aeon
    )
    var location3 = Location(
        "UMP University", "217 Hong Bang street, 11th ward, 5th district, HCM city",
        "Day visited: 12/4/2022",
        3f,
        R.drawable.daihocyduoc
    )
    var location4 = Location(
        "Tran Phu High School",
        "18 Le Thuc Hoach street, Phu Tho Hoa ward, Tan Phu district, HCM city",
        "Day visited: 12/4/2023",
        2.5f,
        R.drawable.tranphu
    )

    companion object{
        const val location1data = 1
        const val location2data = 2
        const val location3data = 3
        const val location4data = 4
    }
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // Find the TextView views in the layout
        val location1name = findViewById<TextView>(R.id.Go)
        val location2name = findViewById<TextView>(R.id.Aeon)
        val location3name = findViewById<TextView>(R.id.uni)
        val location4name = findViewById<TextView>(R.id.school)

        location1name.text = location1.name
        location2name.text = location2.name
        location3name.text = location3.name
        location4name.text = location4.name

        // Find the RatingBar views in the layout
        val goRatingBar = findViewById<RatingBar>(R.id.ratingBar1)
        val aeonRatingBar = findViewById<RatingBar>(R.id.ratingBar2)
        val uniRatingBar = findViewById<RatingBar>(R.id.ratingBar3)
        val schoolRatingBar = findViewById<RatingBar>(R.id.ratingBar4)

        // Set the ratings for each location
        goRatingBar.rating = location1.rating
        aeonRatingBar.rating = location2.rating
        uniRatingBar.rating = location3.rating
        schoolRatingBar.rating = location4.rating


        val vGo = findViewById<ImageView>(R.id.go)
        vGo.setOnClickListener {
            // Create a new intent to start the DetailActivity
            val intent = Intent(this, DetailActivity::class.java)
            // Add extra information to the intent
            // The DetailActivity will use this extra information to display details about the location
            intent.putExtra("location", location1)
            //start the intent activity.
            startActivityForResult(intent, location1data);
        }

        //Setting up a Listener for the ImageView
        val vAeon = findViewById<ImageView>(R.id.aeon)
        vAeon.setOnClickListener {
            // Create a new intent to start the DetailActivity
            val intent = Intent(this, DetailActivity::class.java)
            // Add extra information to the intent
            // The DetailActivity will use this extra information to display details about the location
            intent.putExtra("location", location2)
            // Start the DetailActivity and wait for a result (requestCode can be any number since we don't expect any results)
            startActivityForResult(intent, location2data)
        }

        val vUni = findViewById<ImageView>(R.id.Uni)
        vUni.setOnClickListener {
            // Create a new intent to start the DetailActivity
            val intent = Intent(this, DetailActivity::class.java)
            // Add extra information to the intent
            // The DetailActivity will use this extra information to display details about the location
            intent.putExtra("location", location3)
            //Start the intent activity.
            startActivityForResult(intent, location3data);
        }

        val vSchool = findViewById<ImageView>(R.id.tranphu)
        vSchool.setOnClickListener {
            // Create a new intent to start the DetailActivity
            val intent = Intent(this, DetailActivity::class.java)
            // Add extra information to the intent
            // The DetailActivity will use this extra information to display details about the location
            intent.putExtra("location", location4)
            //Start the intent activity.
            startActivityForResult(intent, location4data);
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == location1data && resultCode == Activity.RESULT_OK) {
            var receivedValue = data?.getFloatExtra("rating", 0F)
            val Ratingbar1 = findViewById<RatingBar>(R.id.ratingBar1)
            if (receivedValue != null) {
                Ratingbar1.rating = receivedValue
                location1.rating = Ratingbar1.rating
            }
        }
        if (requestCode == location2data && resultCode == Activity.RESULT_OK) {
            val receivedValue = data?.getFloatExtra("rating", 0F)
            val Ratingbar2 = findViewById<RatingBar>(R.id.ratingBar2)
            if (receivedValue != null) {
                Ratingbar2.rating = receivedValue
                location2.rating = Ratingbar2.rating
            }
        }
        if (requestCode == location3data && resultCode == Activity.RESULT_OK) {
            val receivedValue = data?.getFloatExtra("rating", 0F)
            val Ratingbar3 = findViewById<RatingBar>(R.id.ratingBar3)
            if (receivedValue != null) {
                Ratingbar3.rating = receivedValue
                location3.rating = Ratingbar3.rating
            }
        }
        if (requestCode == location4data && resultCode == Activity.RESULT_OK) {
            val receivedValue = data?.getFloatExtra("rating", 0F)
            val Ratingbar4 = findViewById<RatingBar>(R.id.ratingBar4)
            if (receivedValue != null) {
                Ratingbar4.rating = receivedValue
                location4.rating = Ratingbar4.rating
            }
        }

    }
}

DetailActivity.kt:

package com.example.core_2_kallenvp

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.widget.EditText
import android.widget.ImageView
import android.widget.RatingBar
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.widget.addTextChangedListener


class DetailActivity : AppCompatActivity() {

    private var rate = 0f

    companion object {
        const val RATING_KEY = "rating"
    }

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


        // Define a list of location keys
        val locationKey = intent.getParcelableExtra<Location>("location")

        // If locationData is not null, set the data to the corresponding views
        locationKey?.let {
            // Set the image of the location
            val imageView = findViewById<ImageView>(R.id.location_image)
            imageView.setImageResource(it.imageResource)


            /*focus on this later*/
            // Set the name of the location
            var nameEditText = findViewById<EditText>(R.id.location_name)
            nameEditText.setText(it.name)
            nameEditText.addTextChangedListener(){

            }

            // Set the address of the location
            val addressEditText = findViewById<EditText>(R.id.location_address)
            addressEditText.setText(it.address)

            // Set the date the location was visited
            val dateEditText = findViewById<EditText>(R.id.location_date)
            dateEditText.setText(it.visited)

            // Set the rating of the location
            val ratingBar = findViewById<RatingBar>(R.id.rating_bar)
            rate = savedInstanceState?.getFloat(RATING_KEY) ?: it.rating
            ratingBar.rating = rate

            rate = it.rating

            // Update rating when rating is changed
            ratingBar.setOnRatingBarChangeListener { ratingBar, rating, fromUser ->
                rate = rating // Save the rating value
                // Create a new intent to return the rating back to MainActivity
                if (fromUser) {
                    Toast.makeText(this@DetailActivity, "You rated: $rating", Toast.LENGTH_SHORT)
                        .show()
                    val returnIntent = Intent()
                    returnIntent.putExtra("rating", rating)
                    setResult(Activity.RESULT_OK, returnIntent)
                }
            }
        }
    }
}

Location.kt:

package com.example.core_2_kallenvp

import android.os.Parcelable
import kotlinx.parcelize.Parcelize

@Parcelize
data class Location(
    var name: String,
    var address: String,
    var visited: String,
    var rating: Float,
    val imageResource: Int // the new property to store the image resource id
    ) : Parcelable

These are the 3 classes that I created for my program, Location is a class for creating objects.
It would mean a lot of help for me in learning Kotlin, thank you!

Sujith Kumar
  • 872
  • 6
  • 19

1 Answers1

0

you need registerForActivityResult. So basically the use case is you go from Activity A to activity B.. and when you're back you need a result back in Activity A. The other useCases include .. Selecting a Image, clicking a photo etc

val startForResult = registerForActivityResult(
    ActivityResultContracts.StartActivityForResult()
) { result: ActivityResult ->
    if (result.resultCode == Activity.RESULT_OK) {
        //  you will get result here in result.data 
    }
}

startForResult.launch(Intent(activity, SecondActivity::class.java))

in the second activity use setResult(intent) with the data in the intent.

The easy but wrong way is creating a companion object in 1st Activity and then access it from both the Activities

Narendra_Nath
  • 4,578
  • 3
  • 13
  • 31
  • Thank you very much for answering my question. So I need to remove the companion object in my first activity and then replace it with registerForActivityResult? And if that is the case, how should I update my onActivityResult? – Kallen Houston Mar 21 '23 at 12:29
  • registerForActivityResult does not not need onActivityResult or the Code .. Look into it once. it'll make handing your responses much easier – Narendra_Nath Mar 22 '23 at 06:27