So for this I am trying to take 2 integer values the user inputs in the 2 EditTexts provided in the main activity and add them together. Then, I want the android application to switch to the 2nd Activity and in the EditText box there display the sum of the 2 values entered into the 2 EditText boxes from the previous(main) Activity.
I think I’m on the right track, but I’m not quite certain how to obtain the sum in the second activity. I’ve tried messing with bundles and such, but I still can’t quite figure it out.
**Re-edited to reflect some suggestions. The 2nd activity still does not show the total…I’m thinking it’s a conversion error of some sort.
***I’m almost positive it has something to do with the 2nd Activity..the first looks right to me
**PERFECT! It was a conversion error. Thanks all for the help 😀
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
public class MainActivity extends Activity
{
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
public void OnClick(View v) //android:onClick="OnClick" added to activity_main.xml for this button
{
Intent intent = new Intent(MainActivity.this, Summation.class);
EditText v1 = (EditText)findViewById(R.id.editText1);
EditText v2 = (EditText)findViewById(R.id.editText2);
int first = Integer.parseInt(v1.getText().toString());
int second = Integer.parseInt(v2.getText().toString());
String sum = String.valueOf(first + second);
intent.putExtra("sum", sum);
startActivity(intent);
}
}
Second Activity Class
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.EditText;
public class Summation extends Activity
{
//Second Activity
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_2);
String sum = (getIntent().getExtras().getString("sum"));
EditText addsum = (EditText)findViewById(R.id.editText1);
addsum.setText(sum);
}
}
You can’t assign your
intvalue straight from edittext. You need to assign the edit texts likeand the same with your second. Then get the values
int firstNum = Integer.parseInt(eText1.getValue.toString())and of course the same with the second. You can then add these two
intstogether and simply pass them withintent.putExtra("sume, sum). Then get them in your secondActivitywithgetIntent()If you are passing as an
intyou will need to do it this way and get theStringvalue of theint. But if you pass as aStringthen you are fine