I have a button. When I click the button, I want to change the value of the variable to 3. In another activity, I want to be able to get the value of the variable and do some computation based on that value.
I have tried using getters and setters methods and just traditionally changing the values and nothing seems to work.
//MainActivity.java
mButtonChoice2 = (Button)findViewById(R.id.choice2);
mButtonChoice2.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view){
//My logic for Button goes in here
if (mButtonChoice2.getText() == "Three"){
setDays(3);
openActivity();
}
}
public int getDays() {
return days;
}
public void setDays(int value){
days = value;
}
public void openActivity() {
Intent intent = new Intent(this, SecondActivity.class);
startActivity(intent);
}
//SecondActivity.java
public class SecondActivity extends AppCompatActivity {
private TextView textview;
private MainActivity obj = new MainActivity();
Integer days = obj.getDays();
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
textview = findViewById(R.id.program);
if (days == 3) {
textview.setText("Days is 3");
}
else {
textview.setText(days);
}
I want the textview in the SecondActivity to update the textview text with "days is 3"
However, it just errors out because it is not being able to correctly receive the value of the integer days.
try the following updated code:
//MainActivity.java
mButtonChoice2 = (Button)findViewById(R.id.choice2);
mButtonChoice2.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view){
//My logic for Button goes in here
if (mButtonChoice2.getText() == "Three"){
setDays(3);
openActivity();
}
}
public int getDays() {
return days;
}
public void setDays(int value){
days = value;
}
public void openActivity() {
Intent intent = new Intent(this, SecondActivity.class);
intent.putExtra ("days",days);
startActivity(intent);
}
//SecondActivity.java
public class SecondActivity extends AppCompatActivity {
private TextView textview;
private MainActivity obj = new MainActivity();
// Integer days = obj.getDays();
int days=0;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
Intent intent=getIntent();days=intent.getIntExtra ("days",0);
textview = findViewById(R.id.program);
if (days == 3) {
textview.setText("Days is 3");
}
else {
textview.setText(days);
}
Reference : https://developer.android.com/reference/android/content/Intent https://www.dev2qa.com/passing-data-between-activities-android-tutorial/
只需在一个活动中声明一个静态变量,然后在第二个活动中使用它即可。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.