So I have two activities named “MainActivity” and activity named “Second”, so my MainActivity has it’s own Adapter class named “PractiseAdapter”. So my MainActivity contains a Textview with an id
” textCount ” and a recyclerview named “recyclerView” and a button “btnGo”. The button is used to go to another Activity “Second”. So When I click on the Cardview present in the recyclerview my count of “textCount” keeps increasing by 1. Below is the code of my MainActivity.kt
import android.annotation.SuppressLint
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
class MainActivity : AppCompatActivity() {
private lateinit var textCount:TextView
@SuppressLint("MissingInflatedId")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
setContentView(R.layout.activity_main)
val recyclerView = findViewById<RecyclerView>(R.id.recyclerview)
textCount = findViewById<TextView>(R.id.textCount)
val btnGo = findViewById<Button>(R.id.btnGo)
val cards = listOf("Item1")
// Load the saved text count
loadTextCount()
val adapter = PractiseAdapter(cards,textCount)
recyclerView.layoutManager = LinearLayoutManager(this)
recyclerView.adapter = adapter
btnGo.setOnClickListener {
val intent = Intent(this@MainActivity,Second::class.java)
startActivity(intent)
}
}
private fun saveTextCount(count: Int) {
val sharedPreferences: SharedPreferences = getSharedPreferences("MyPrefs", MODE_PRIVATE)
val editor = sharedPreferences.edit()
editor.putInt("textCount", count)
editor.apply() // or editor.commit()
}
private fun loadTextCount() {
val sharedPreferences: SharedPreferences = getSharedPreferences("MyPrefs", MODE_PRIVATE)
val savedCount = sharedPreferences.getInt("textCount", 0)
textCount.text = savedCount.toString()
}
private fun sendUpdateBroadcast(count: Int) {
val intent = Intent("com.example.UPDATE_TEXT_COUNT")
intent.putExtra("textCount", count)
sendBroadcast(intent)
}
fun updateTextCount(newValue: Int) {
// Update the TextView
textCount.text = newValue.toString()
// Save the new value
saveTextCount(newValue)
// Send broadcast
sendUpdateBroadcast(newValue)
}
}
Below is the code of my adapter class named PractiseAdapter.kt
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.cardview.widget.CardView
import androidx.recyclerview.widget.RecyclerView
class PractiseAdapter(
private val items:List<String>,
private val textCount:TextView
):RecyclerView.Adapter<PractiseAdapter.CardViewHolder>() {
private var count=0
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CardViewHolder {
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.cardview_item, parent, false)
return CardViewHolder(view)
}
override fun onBindViewHolder(holder: CardViewHolder, position: Int) {
val item = items[position]
holder.textView.text = item
// Optionally set up click listeners or other interactions
holder.cardView.setOnClickListener {
// Increment the count
val currentCount = textCount.text.toString().toIntOrNull() ?: 0
val newCount = currentCount + 1
(textCount.context as MainActivity).updateTextCount(newCount)
}
}
override fun getItemCount(): Int = items.size
class CardViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val cardView: CardView = itemView.findViewById(R.id.cardView1)
val textView: TextView = itemView.findViewById(R.id.textName)
}
}
In “Second” Activity, I have a TextView named “textSecondCount”, a recyclerview named ” recycler1″ and a button named “buttonSecond” . textSecond count displays the value of textCount from the MainActivity.kt . There is an Adapter class named SecondAdapter.kt. when I click on the cardview present in it a dialog box pops up like this UI Image as you can see in the dialog box when i click on YES button, subtraction takes place textSecondCount and default value of 10 Textview present in SecondAdapter. And then textSecondCount gets updated with the new value of newCount. Below is the code of my Second Activity
import android.annotation.SuppressLint
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.content.SharedPreferences
import android.os.Build
import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
class Second:AppCompatActivity() {
private lateinit var textSecondCount:TextView
private lateinit var buttonSecond:Button
private lateinit var recycler1:RecyclerView
@RequiresApi(Build.VERSION_CODES.O)
@SuppressLint("MissingInflatedId")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.second)
textSecondCount = findViewById(R.id.textSecondCount)
buttonSecond = findViewById(R.id.buttonBack)
recycler1 = findViewById(R.id.recycler1)
// Register receiver
registerReceiver(updateReceiver, IntentFilter("com.example.UPDATE_TEXT_COUNT"),
RECEIVER_NOT_EXPORTED
)
// Load the saved text count
loadTextCount()
buttonSecond.setOnClickListener {
onBackPressed()
}
val items = listOf("A1")
val adapter = SecondAdapter(this,items,textSecondCount)
recycler1.layoutManager = LinearLayoutManager(this)
recycler1.adapter = adapter
}
override fun onDestroy() {
super.onDestroy()
// Unregister receiver
unregisterReceiver(updateReceiver)
}
private fun loadTextCount() {
val sharedPreferences: SharedPreferences = getSharedPreferences("MyPrefs", MODE_PRIVATE)
val savedCount = sharedPreferences.getInt("textCount", 0)
findViewById<TextView>(R.id.textSecondCount).text = savedCount.toString()
}
fun sendUpdateBroadcast(newCount:Int){
val intent = Intent("com.example.UPDATE_TEXT_COUNT")
intent.putExtra("textCount", newCount)
sendBroadcast(intent)
}
private val updateReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
val newCount = intent?.getIntExtra("textCount", 0) ?: 0
findViewById<TextView>(R.id.textSecondCount).text = newCount.toString()
}
}
}
Code of it’s adapter class is
import android.annotation.SuppressLint
import android.content.Context
import android.os.Build
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.TextView
import android.widget.Toast
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AlertDialog
import androidx.cardview.widget.CardView
import androidx.recyclerview.widget.RecyclerView
class SecondAdapter(
private val context: Context,
private val items: List<String>,
private val textSecondCount: TextView
) : RecyclerView.Adapter<SecondAdapter.CardViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CardViewHolder {
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.second_adapter, parent, false)
return CardViewHolder(view)
}
@RequiresApi(Build.VERSION_CODES.O)
override fun onBindViewHolder(holder: CardViewHolder, position: Int) {
val item = items[position]
holder.textViewAdapter.text = holder.textViewAdapter.text
// Log item value and TextView text
Log.d("charm", "Item: $item")
Log.d("charm", "TextView value: ${holder.textViewAdapter.text}")
holder.cardViewSecond.setOnClickListener {
// Get the texAdapterCount value for the clicked card
val textAdapter = holder.textViewAdapter.text.toString()
val texAdapterCount = textAdapter.toIntOrNull() ?: 0
// Log the value to check conversion
Log.d("SecondAdapter", "texAdapterCount: $texAdapterCount")
showDialog(texAdapterCount)
}
}
@RequiresApi(Build.VERSION_CODES.O)
@SuppressLint("SetTextI18n")
private fun showDialog(texAdapterCount: Int) {
// Debugging: Log the value of texAdapterCount
Log.d("SecondAdapter", "texAdapterCount: $texAdapterCount")
val dialogView = LayoutInflater.from(context).inflate(R.layout.dialog_layout, null)
val messageTextView = dialogView.findViewById<TextView>(R.id.dialog_message)
// Log current textSecondCount value
val currentCount = textSecondCount.text.toString()
Log.d("SecondAdapter", "Current textSecondCount: $currentCount")
// Ensure there's a space between the message and the count
messageTextView.text = "Do you have apples $texAdapterCount?"
val dialogBuilder = AlertDialog.Builder(context)
.setView(dialogView)
.setCancelable(true)
val dialog = dialogBuilder.create()
dialogView.findViewById<Button>(R.id.dialog_button_positive).setOnClickListener {
try {
val currentCountInt = currentCount.toInt()
if (currentCountInt >= texAdapterCount) {
// Update textSecondCount and notify the change
val newCount = currentCountInt - texAdapterCount
textSecondCount.text = newCount.toString()
// Save updated count to SharedPreferences
val sharedPreferences = context.getSharedPreferences("MyPrefs", Context.MODE_PRIVATE)
val editor = sharedPreferences.edit()
editor.putInt("textCount", newCount)
editor.apply()
// Notify the user
showToast("Card unlocked successfully")
// Send update broadcast
if (context is Second) {
(context as Second).sendUpdateBroadcast(newCount)
}
} else {
// Notify the user
showToast("Not enough points to unlock")
}
} catch (e: NumberFormatException) {
Log.e("SecondAdapter", "Error parsing count: $e")
showToast("Error processing the count")
}
dialog.dismiss()
}
dialogView.findViewById<Button>(R.id.dialog_button_negative).setOnClickListener {
// Handle negative button click
dialog.dismiss()
}
dialog.show()
}
private fun showToast(messsage: String) {
Toast.makeText(context, messsage, Toast.LENGTH_SHORT).show()
}
override fun getItemCount(): Int = items.size
class CardViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val cardViewSecond: CardView = itemView.findViewById(R.id.cardViewSecond)
val textViewAdapter: TextView = itemView.findViewById(R.id.texAdapterCount)
}
}
So now when I click on YES button present in Alertdialog Subtraction takes place and I get a new value for textSecondCount and what I want is value of my textCount should also get updated by the same value
I tried to broadcast the value to the MainActivity so that changes might reflect there too but the value of textCount doesn’t change when value of textsecondCount changes.