I need to have an button on the main acitivity which takes a few variables (double) and pass them to the second activity in which the given data is used in a function to measure your daily calorie-need. Is here a nice fella who has an example code or could help me with this topic? Im programming with java in android studio. My current code: https://www.codepile.net/pile/7gxK4VYZ
CodePudding user response:
This is actually quite simple to do, but as a new programmer, I can understand that it can be challenging at times. Here is what I would do.
Lets say your button function is called "passData()" and your getting these values from the user from the first screen and storing them in valOne and valTwo.
do this:
public void passData(View view) {
Intent intent = new Intent(MainActivity.this, MainActivity2.class);
intent.putExtra("valueOne", valOne);
intent.putExtra("valueTwo", valTwo);
startActivity(intent);
}
in your second activity, do this:
//Get the text view
TextView result = (TextView) findViewById(R.id.textView);
//Get the values from previous screen
getValOne = getIntent().getStringExtra("valueOne");
getValTwo = getIntent().getStringExtra("valueTwo");
//Convert to int to use in function
int intValOne = Integer.parseInt(getValOne);
int intValTwo = Integer.parseInt(getValOne);
//Insert in your function
int x = intValOne intValTwo;
result.setText(x);
*** getValOne and getValTwo have been declared globally. ***
CodePudding user response:
You can use Intent
to send the data from the first Activity
to another one like this:
In the first activity
Step 1 Add this code on button click:
Intent intent = new Intent();
intent.putExtra("value", oneValue);
startActivity(intent);
In the second activity
Step 2 Create a variable:
String anotherValue;
Step 3 Init this variable:
anotherValue = getIntent().getStringExtras("value");
Now the value from your first activity is stored in the variable `anotherValue and you can use it in any method of the second activity.
Thanks...
CodePudding user response:
Here is the easiest way to pass data from one activity (MainActivity) to another activity (SecondActivity):
MainActivity
String yourData = "My Data";
Intent intent = new Intent(this, SecondActivity.class);
intent.putExtra("EXTRA_DATA", yourData);
startActivity(intent);
then in SecondActivity you should set this to take the data
SecondActivity
String myData = getIntent().getStringExtra("EXTRA_DATA");
Another Example If you have 2 data you can try this
String name = "Sangkuni";
String gender = "Male";
Intent intent = new Intent(this, SecondActivity.class);
intent.putExtra("EXTRA_DATA_NAME", name);
intent.putExtra("EXTRA_DATA_GENDER", gender);
startActivity(intent);
then in SecondActivity
String name = getIntent().getStringExtra("EXTRA_DATA_NAME");
String gender = getIntent().getStringExtra("EXTRA_DATA_GENDER");
I hope my answer will help you