Ryan D Ryan D - 3 months ago 8
Android Question

Android pass increment value in intent between 2 activities

I am passing a value in intent between 2 activities to dynamically change data..

I am getting the value passed from the end activity in my home activity in the onCreate like so -

// Get Variable From Home Activity
Bundle extras = getIntent().getExtras();
String curhole;
curhole = extras.getString("hole");
TextView holeno = (TextView) findViewById(R.id.holeNumber);
holeno.setText(String.valueOf("Hole " + curhole));


I have this onClick function in my home activity-

@Override
public void onClick(View v) {
// Get Variable From Home Activity
Bundle extras = getIntent().getExtras();
String curhole;
curhole = extras.getString("hole");

Intent myIntent = new Intent(this, end.class);
myIntent.putExtra("hole",curhole);
startActivity(myIntent);

}


Then in my end activity I grab that value and pass it back to the home activity -

@Override
public void onClick(View v) {
Bundle extras = getIntent().getExtras();
String curhole;
curhole = extras.getString("hole");

int incHole = Integer.parseInt(curhole);
incHole++;
String.valueOf(incHole);

Intent myIntent = new Intent(this, hole.class);
myIntent.putExtra("hole",incHole);
startActivity(myIntent);

}


When I click the home activity button to go to the end activity and back to home it says the value is null.. Any idea why? I am new to android so im sure my approach is probably whack.

Thanks!

Answer

Probably because you need to be getting the value in onResume() since it doesn't look like you are killing the Home Activity so onCreate() won't be called again.

You might want to make use of startActivityForResult() in this type of case though, passing this way will work.

Also, Intent has a [getIntExtra()](https://developer.android.com/reference/android/content/Intent.html#getIntExtra(java.lang.String, int)) method so I'm not sure you need to do all of the converting you are doing.