So I have a child activity that I press two buttons, one to increment and one to decrement. I want to save this number when I go back to the previous activity. However, I am stuck here. I tried using shared preference, however that seems to work for main to secondary activity. I tried using Activity Result and that seems way above me right now. I want my value in the textView to stay until I press a button to reset the whole thing.
This is the parent activity.
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.widget.Button
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
class TallBoys : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_tall_boys)
val btn1: Button = findViewById(R.id.button1)
val btn2: Button = findViewById(R.id.button2)
val btn3: Button = findViewById(R.id.button3)
val btn4: Button = findViewById(R.id.button4)
val btn5: Button = findViewById(R.id.button5)
val btn6: Button = findViewById(R.id.button6)
val btn7: Button = findViewById(R.id.button7)
btn1.setOnClickListener {
val intent = Intent(this, TallBoysNumbers::class.java)
}
btn2.setOnClickListener {
val intent = Intent(this, TallBoysNumbers::class.java)
startActivity(intent)
}
btn3.setOnClickListener {
val intent = Intent(this, TallBoysNumbers::class.java)
startActivity(intent)
}
btn4.setOnClickListener {
val intent = Intent(this, TallBoysNumbers::class.java)
startActivity(intent)
}
btn5.setOnClickListener {
val intent = Intent(this, TallBoysNumbers::class.java)
startActivity(intent)
}
btn6.setOnClickListener {
val intent = Intent(this, TallBoysNumbers::class.java)
startActivity(intent)
}
btn7.setOnClickListener {
val intent = Intent(this, TallBoysNumbers::class.java)
startActivity(intent)
}
}
}
This is the child activity
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
class TallBoysNumbers : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_tall_boys_numbers)
val confirmBtn: Button = findViewById(R.id.confirm_button)
val plusBtn: Button = findViewById(R.id.plus)
val textView = findViewById<TextView>(R.id.numbers)
val negBtn: Button = findViewById(R.id.negative)
var count = 0
plusBtn.setOnClickListener {
count++
textView.text = count.toString()
if (count >= 8) {
plusBtn.isEnabled = false
negBtn.isEnabled = true
}
}
negBtn.setOnClickListener {
count--
textView.text = count.toString()
if (count <= 0) {
negBtn.isEnabled = false
plusBtn.isEnabled = true
}
}
confirmBtn.setOnClickListener {
finish()
}
}
}
There are a lot of ways to do this, so I'm just going to show how to do it using SharedPreferences. The steps you need are:
In the parent activity, load the saved numbers from SharedPreferences in onResume and set the views accordingly. This needs to be in onResume so that it is also called when returning from the child activity after the numbers are modified.
Pass the key that is being edited to the child activity, so that it can save it in the correct spot in the SharedPreferences. The child activity can also use this key to load the current value so it is initialized correctly.
For example, in the parent activity
class ShowNumbersActivity : AppCompatActivity() {
private lateinit var prefs: SharedPreferences
private lateinit var txt1: TextView
private lateinit var txt2: TextView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_show_numbers)
prefs = getSharedPreferences("MY_PREFS", Context.MODE_PRIVATE)
val btn1 = findViewById<Button>(R.id.btn1)
val btn2 = findViewById<Button>(R.id.btn2)
txt1 = findViewById(R.id.txt1)
txt2 = findViewById(R.id.txt2)
// When you click on "Button 1" you have to signal
// to the second activity which key you are editing
btn1.setOnClickListener {
val i = Intent(this, PickNumber::class.java)
i.putExtra("KEY","VAL1")
startActivity(i)
}
btn2.setOnClickListener {
val i = Intent(this, PickNumber::class.java)
i.putExtra("KEY","VAL2")
startActivity(i)
}
}
// Update the displayed state in onResume
// so that it is updated after returning from the
// child activity editing the number
override fun onResume() {
super.onResume()
val num1 = prefs.getInt("VAL1", 0)
val num2 = prefs.getInt("VAL2", 0)
txt1.text = num1.toString()
txt2.text = num2.toString()
}
}
Then in the child activity, get the "KEY" and the same SharedPreferences instance and edit it when you click "Submit"
class PickNumber : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_pick_number)
val key = intent.getStringExtra("KEY")
if( key == null ) {
finish()
}
val prefs = getSharedPreferences("MY_PREFS", Context.MODE_PRIVATE)
val txt = findViewById<EditText>(R.id.num)
val submit = findViewById<Button>(R.id.submit)
// load the current value and display it
val current = prefs.getInt(key, 0)
txt.setText(current.toString())
submit.setOnClickListener {
// Get the updated number, save it to shared preferences
// (remember to call "apply") and finish this activity.
// When onResume is called in the parent activity it will
// load this updated number.
val num = txt.text.toString()
val numI = num.toIntOrNull() ?: 0
prefs.edit().putInt(key, numI).apply()
finish()
}
}
}
If you want to clear the numbers, you could make a button that calls prefs.edit().clear().apply() to erase all the saved values, or prefs.edit().remove(someKey).apply() to erase just one specific value.
There are definitely better ways to do this - if you switch to using a Fragment like you indicated these could be stored in a shared ViewModel that handles persistence and would be a cleaner design overall.
You are calling "finish" method. This will finish TallBoysNumbers activity without saving any data. Do not use SharedPreferences for that. What you'll need is "startActivityForResult".
This will allow you to save the data before calling "finish" AND getting it from the caller activity. Take a look here:
https://developer.android.com/training/basics/intents/result
with using shared pref I hope it will come to you
class dataShared() for saving count
class DataShared(
context: Context,
userSharedPrefName:String="USER_SHARED_PREF_NAME"
) {
private val sharedPreferences: SharedPreferences =
context.getSharedPreferences(
userSharedPrefName, Context.MODE_PRIVATE
)
fun getCount(): Int {
return (sharedPreferences.getInt("count", 0))
}
fun setCount(value: Int) {
val editor = sharedPreferences.edit()
editor.putInt("count", value)
editor.apply()
}
}
plusBtn and negBtn
val data=DataShared(this)
plusBtn.setOnClickListener {
if (data.getCount()<7) {
data.setCount(data.getCount() + 1)
textView.text = data.getCount().toString()
}
}
negBtn.setOnClickListener {
if (data.getCount()>=1){
data.setCount(data.getCount()-1)
textView.text=data.getCount().toString()
}
}
Related
I'm new at Kotlin, and I'm doing a simple app where the user writes something on EditText, presses a button then the app proceeds to show that text on SecondActivity, on that SecondActivity the user can do exactly the same thing, but on the FirstActivity (the one who shows up on the user starts the app) there are on EditText with "Welcome" text for default that shows empty when the application starts, this started to happen when I implement the text to be substituted by what the user writes on the SecondActivity
Here's the code for the FirtActivity
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val result = findViewById<TextView>(R.id.nomeUser)
val nameEntered = findViewById<EditText>(R.id.nameEntered)
val button = findViewById<Button>(R.id.button)
button.setOnClickListener{
val name = nameEntered.text.toString()
val intent = Intent(this#MainActivity, NomeEscrito::class.java)
intent.putExtra("Name", name)
startActivity(intent)
}
val intent = intent
val name = intent.getStringExtra("Name")
result.text = name
}
}
And here's the code for the SecondActivity
class NomeEscrito : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_nome_escrito)
val intent = intent
val name = intent.getStringExtra("Name")
val result = findViewById<TextView>(R.id.result)
result.text = name
val wordEntered = findViewById<EditText>(R.id.textPhrase)
val button2 = findViewById<Button>(R.id.button2)
button2.setOnClickListener{
val name2 = wordEntered.text.toString()
val intent2 = Intent(this#NomeEscrito, MainActivity::class.java)
intent2.putExtra("Name", name2)
startActivity(intent2)
}
}
}
The problem is in the following line of your FirstActivity:
val name = intent.getStringExtra("Name")
When you open up the app for the first time, there is no data in the intent. As a result, it returns an empty string.
You can do the a check for empty string before setting your EditText text to avoid this situation:
if (!name.isNullOrBlank()) {
result.text = name
}
Choose different keys in getStringExtra in both intent data passing
There are two classes MainActivity and PickTimeForNotif in my project. In MainActivity getSharedPreferences works just fine, i can save my data and get it back. In PickTimeForNotif, however, the same method seems to do nothing.
Here's my simplified MainActivity class:
class MainActivity : AppCompatActivity(), ChangeCupDialogFragment.StringListener {
#SuppressLint("SetTextI18n")
//this is variable i'm saving
private var drankToday = 0
//function in which i save my value to SharedPreferences
private fun saveWaterCountToInternalStorage(clickCounter: Int) {
val sharedPref = this.getSharedPreferences("something", Context.MODE_PRIVATE)
with (sharedPref.edit()){
putInt(getString(R.string.clickCount), clickCounter)
apply()
}
}
//and here i get it from there
private fun loadWaterCountToInternalStorage(): Int {
val sharedPref = this.getSharedPreferences("something", Context.MODE_PRIVATE)
return sharedPref.getInt(getString(R.string.clickCount), drankToday)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.main_activity)
val setupNotifButton = findViewById<Button>(R.id.setupNotifButton)
setupNotifButton.setOnClickListener{
val notifIntent = Intent(applicationContext, PickTimeForNotif::class.java)
startActivity(notifIntent)
}
}
}
In setOnClickListener i intend my second activity PickTimeForNotif, here it is.
class PickTimeForNotif: AppCompatActivity(), TimePickerFragment.OnCompleteListener {
val APP_PREFERENCES = "settings"
private val SAVED_FROM_HOUR = "SetFromHour"
private var FROM_HOUR = 99
private fun saveTimeToInternalStorage(prefName1: String, Hour:Int) {
val sharedPref = this.getSharedPreferences(APP_PREFERENCES, MODE_PRIVATE)
with (sharedPref.edit()){
putInt(prefName1, Hour)
apply()
}
}
private fun loadTimeFromInternalStorage() {
val sharedPref = this.getSharedPreferences(APP_PREFERENCES, MODE_PRIVATE)
if (sharedPref.contains(APP_PREFERENCES)) {
sharedPref.getInt(SAVED_FROM_HOUR, FROM_HOUR)
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.pick_time_activity)
saveTimeToInternalStorage(SAVED_FROM_HOUR, 1)
loadTimeFromInternalStorage()
Toast.makeText(applicationContext,"$FROM_HOUR", Toast.LENGTH_SHORT).show()
}
}
In the code above i'm trying to set value (1 for example ) to a SAVED_FROM_HOUR key and then get it back and assign to FROM_HOUR variable. However, the Toast shows 99, which means that new data wasn't loaded properly. I tried putting all code from loadTimeFromInternalStorage and saveTimeToInternalStorage to onCreate, but the result is same.
I also tried checking if the Preferences file exists after i call getSharedPreferences with
if (sharedPref.contains(APP_PREFERENCES))
but it does not.
So i'm asking to explain what am i doing wrong and why i can save the data in my MainActivity, but not in the second one. Thanks alot to anyone in advance!!
In loadTimeFromInternalStorage(), you are fetching the value but not assigning to variable like this:
private fun loadTimeFromInternalStorage() {
val sharedPref = this.getSharedPreferences(APP_PREFERENCES, MODE_PRIVATE)
if (sharedPref.contains(APP_PREFERENCES)) {
FROM_HOUR = sharedPref.getInt(SAVED_FROM_HOUR, FROM_HOUR)
}
}
Also, in this line FROM_HOUR = sharedPref.getInt(SAVED_FROM_HOUR, FROM_HOUR), the last parameter in getInt() method is the default value so you should make another constant for it or supply it 0.
I have two activities. One is the homepage with a button to add a dynamic button and the second page is two edit texts. So you click the button on the homepage and go to the second page where you input two edit texts and youre sent back to the homepage where a dynamic button set to one of the edit text is created. I made an inflator that allows you to go back into the second activity through the button but it starts a new second activity so the previous inputted edit texts are gone. How do I get them to stay?
Main page:
package com.example.quest
import android.app.Activity
import android.app.AlertDialog
import android.content.Intent
import android.graphics.Color
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.Gravity
import android.widget.Button
import android.widget.LinearLayout
import androidx.preference.PreferenceManager
import com.google.android.material.floatingactionbutton.FloatingActionButton
class MainActivity : AppCompatActivity() {
private val questionActivityCode = 2
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
findViewById<FloatingActionButton>(R.id.btn2).setOnClickListener{
startActivityForResult(Intent(this#MainActivity, SecondActivity::class.java), questionActivityCode)
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == questionActivityCode && resultCode == Activity.RESULT_OK) {
createNewButtonWithText(data?.getStringExtra("test") ?: "")
}
}
private fun createNewButtonWithText(text: String)
{
val newbutton = Button(this#MainActivity)
val layout = findViewById<LinearLayout>(R.id.mainlayout)
newbutton.text = text
newbutton.layoutParams = LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT)
newbutton.width=1010
newbutton.height=300
newbutton.gravity = Gravity.CENTER
newbutton.translationX= 65F
newbutton.setTextColor(Color.parseColor("#FFFFFFFF"))
newbutton.setBackgroundColor(Color.parseColor("#250A43"))
layout.addView(newbutton)
val inflator = layoutInflater
val builder = AlertDialog.Builder(this)
val intent = Intent(this#MainActivity, SecondActivity::class.java)
newbutton.setOnClickListener{
val dialogLayout = inflator.inflate(R.layout.text, null)
with(builder) {
setTitle(newbutton.text)
setPositiveButton("Edit"){dialog, which ->
startActivity(intent)
}
setNegativeButton("Cancel"){dialog, which ->
Log.d("Main", "Negative button clicked")
}
setView(dialogLayout)
show()
}
}
}}
Second Activity:
package com.example.quest
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.widget.EditText
import androidx.appcompat.app.AppCompatActivity
import androidx.preference.PreferenceManager
import com.google.android.material.floatingactionbutton.FloatingActionButton
class SecondActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_second)
val question = findViewById<EditText>(R.id.question)
val answer = findViewById<EditText>(R.id.answer)
findViewById<FloatingActionButton>(R.id.btn3).setOnClickListener {
val questiontext = question.text.toString()
val answertext = answer.text.toString()
val sharedPre = PreferenceManager.getDefaultSharedPreferences(this#SecondActivity).edit()
sharedPre.putString("question", questiontext)
sharedPre.putString("answer", answertext)
sharedPre.apply()
val returnIntent = Intent()
returnIntent.putExtra("test", questiontext)
setResult(Activity.RESULT_OK, returnIntent)
finish()
}
}
}
If you look at the activity lifecycle after creating an activity and when moving from one activity to the next activity the activity is destroyed, and a new activity is created. An easy way to save this data could be to use shared preferences whereby you can store the data when the user inputs it in the second activity and before you inflate the second activity check if the sharedprefs data is not null and use the data to update the activity else just create a new activity.
Are you using MVVM architecture? You should probably store all your value in ViewModel and call these values between activities in ViewModel, as View (Actiity/Fragment) is only responsible for UI-related task.
Here is a simple example
SharedViewModel
class SharedViewModel : ViewModel() {
// ViewModel that holds data-related values
var question: String ?= null
var answer: Stirng ?= null
}
SecondActivity
class SecondActivity : AppCompatActivity() {
private val sharedViewModel: SharedViewModel by viewModels() <-- add your viewmodel here
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_second)
val question = findViewById<EditText>(R.id.question)
val answer = findViewById<EditText>(R.id.answer)
// Step 1 - Check viewmodel's value and assign it back to edittext
if(sharedViewModel.question != null) {
question.text = sharedViewModel.question
}
if(sharedViewModel.answer != null) {
answer.text = sharedViewModel.answer
}
// Step 2 - Assign your value into viewmodel
findViewById<FloatingActionButton>(R.id.btn3).setOnClickListener {
sharedViewModel.question = question.text.toString()
sharedViewModel.answer = answer.text.toString()
returnIntent.putExtra("test", questiontext)
setResult(Activity.RESULT_OK, returnIntent)
finish()
}
}
}
Additional
onActivityResult will be deprecated soon in API 30, it it better you can learn ActivityResultContract
Try to use databinding as it helps to reduce many of the boilerplate since you're using kotlin.
Try to adapt to MVVM architecture as it helps you a lot in developing Android app.
Basically, I want to have a screen/view that will open when the user opens up the app for the first time. This will be a login screen type of thing.
there are classes SplashActivity
class SplashActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
//hiding title bar of this activity
window.requestFeature(Window.FEATURE_NO_TITLE)
//making this activity full screen
window.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN)
setContentView(R.layout.activity_splash)
//4second splash time
Handler().postDelayed({
//start main activity
startActivity(Intent(this#SplashActivity, MyCustomAppIntro::class.java))
//finish this activity
finish()
},2000)
}
}
class MyCustomAppIntro
class MyCustomAppIntro : AppIntro() {
companion object {
fun startActivity(context: Context) {
val intent = Intent(context, MyCustomAppIntro::class.java)
context.startActivity(intent)
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setTransformer(AppIntroPageTransformerType.Depth)
// You can customize your parallax parameters in the constructors.
setTransformer(AppIntroPageTransformerType.Parallax(
titleParallaxFactor = 1.0,
imageParallaxFactor = -1.0,
descriptionParallaxFactor = 2.0
))
// Make sure you don't call setContentView!
// Call addSlide passing your Fragments.
// You can use AppIntroFragment to use a pre-built fragment
addSlide(
AppIntroFragment.newInstance(
imageDrawable = R.drawable.ayana,
backgroundDrawable = R.color.black,
description = "Привет мой друг"
))
addSlide(
AppIntroFragment.newInstance(
imageDrawable = R.drawable.ayana,
backgroundDrawable = R.color.black,
description = "Меня зовут AYANA"
))
addSlide(
AppIntroFragment.newInstance(
backgroundDrawable = R.drawable.screen_3
))
}
override fun onSkipPressed(currentFragment: Fragment?) {
super.onSkipPressed(currentFragment)
// Decide what to do when the user clicks on "Skip"
val intent = Intent(this,MainActivity::class.java)
startActivity(intent);
finish()
}
override fun onDonePressed(currentFragment: Fragment?) {
super.onDonePressed(currentFragment)
val intent = Intent(this,MainActivity::class.java)
startActivity(intent);
finish()
}
class MainActivity
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.layout_activity_main)
window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
about.setOnClickListener{
val intent = Intent(this,ScondActivity::class.java)
startActivity(intent);
}
val assistantFragment = AimyboxAssistantFragment()
supportFragmentManager.beginTransaction().apply {
replace(R.id.assistant_container, assistantFragment)
commit()
}
}
override fun onBackPressed() {
val assistantFragment = (supportFragmentManager.findFragmentById(R.id.assistant_container)
as? AimyboxAssistantFragment)
if (assistantFragment?.onBackPressed() != true) super.onBackPressed()
}
}
We suggest to don't declare MyCustomAppIntro as your first Activity unless you want the intro to launch every time your app starts. Ideally you should show the AppIntro activity only once to the user, and you should hide it once completed (you can use a flag in the SharedPreferences) ????
Use SharedPreference for that Issue, its quite easy and simple approach:
Splash Activity:
SharedPreference sharedpref = getApplicationContext.getSharedPreferences(SETTINGS_PREFERENCES,MODE_PRIVATE);
String token = sharedPreferences.getString("token", null);
if (token.equals("False") || token == null){
//will call the view for the first and last time until cache is cleared
//after trigger this login programmatically set the token value true thus you can solve the problem
SharedPreferences.Editor editor = sharedpref.edit();
editor.putString("token", "True");
editor.apply();
}else{
//do something or redirect to login or main activity
}
as #EmonHossainMunna suggested, SharedPreferences are the go, kotlin code will be as follows
val sharedpref: SharedPreferences =
getApplicationContext().getSharedPreferences(
"com.example.android.your_application",
MODE_PRIVATE
)
val token: String? = sharedpref.getString("token", null)
if (token == "False" || token == null) {
// rest of the FirstTime Logic here
sharedpref.edit().putString("token", "true").apply()
} else {
// rest of the Not-FirstTime Logic here
}
You also may want to check if onCreate() runs the first time:
if (savedInstanceState == null) {
...
}
I am having a ton of trouble passing the product of two EditTexts to a TextView in another activity. Here is my code for MainActivity.
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val button1: Button = findViewById(R.id.button1)
val editText1: EditText = findViewById(R.id.editText1)
val editText2: EditText = findViewById(R.id.editText2)
val firstNumber = editText1.toString().toInt()
val secondNumber = editText2.toString().toInt()
val product = firstNumber * secondNumber
button1.setOnClickListener{
val intent = Intent(this, Activity2::class.java)
intent.putExtra("RESULT_PRODUCT", product)
startActivity(intent)
}
}
}
Here is my code for Activity2:
class Activity2 : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_2)
val product = intent.getIntExtra("RESULT_SUM", 0)
textView1.text = product.toString()
}
}
I am relatively new to Kotlin and Android Studio but this has caused crashes left and right.
First of all, You have to calculate the product inside OnClickListener to get correct result.
button1.setOnClickListener{
val firstNumber = editText1.text.toString().trim()
val secondNumber = editText2.text.toString().trim()
if(!(firstNumber.isEmpty() or secondNumber.isEmpty())) {
val product = firstNumber.toInt() * secondNumber.toInt()
val intent = Intent(this, Activity2::class.java)
intent.putExtra("RESULT_PRODUCT", product)
startActivity(intent)
} else {
//Show messages
}
}
And then you have to use the exact key RESULT_PRODUCT that you use in your activity to pass data through intent
val product = intent.getIntExtra("RESULT_PRODUCT", 0)
You are passing "RESULT_PRODUCT" from MainActivity but getting "RESULT_SUM" in your Activity2. You should use intent.getIntExtra("RESULT_PRODUCT", 0) in you second activity.