我想将main2Activity的变量indicatorpositionstart的内容发送到mainActivity。我使用了“额外”解决方案,但不起作用。
出什么问题了?
public class Main2Activity extends AppCompatActivity {
private Button imageValidate;
int indicatorPositionStart = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
imageValidate = findViewById(R.id.buttonValidate);
imageValidate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent2 = new Intent(Main2Activity.this, MainActivity.class);
intent2.putExtra("indicatorPositionStartt", indicatorPositionStart );
startActivity(intent2);
}
});
}
public class MainActivity extends AppCompatActivity{
int id = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView textView = findViewById(R.id.textView3);
if (id != 0) {
int id = getIntent().getExtras().getInt("indicatorPositionStartt", 0);
String indicatorPositionStart = String.valueOf(id);
textView.setText(indicatorPositionStart);
}
}
}
谢谢。
答案 0 :(得分:1)
问题是您在从附加功能中获取值之前正在检查该值,请参阅第二项活动中的以下行:
// you are using it here, before getting the value
if (id != 0) {
int id = getIntent().getExtras().getInt("indicatorPositionStartt", 0);
String indicatorPositionStart = String.valueOf(id);
textView.setText(indicatorPositionStart);
}
}
MainActivity
上的另一个问题是您没有填写id字段。
我已修复它,只需将其替换为您的第二个活动即可:
public class MainActivity extends AppCompatActivity{
int id = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView textView = findViewById(R.id.textView3);
// get the value first
id = getIntent().getExtras().getInt("indicatorPositionStartt", 0);
// then use it
if (id != 0) {
String indicatorPositionStart = String.valueOf(id);
textView.setText(indicatorPositionStart);
}
}
}
答案 1 :(得分:0)
在您的MainActivity中,删除此检查if (id !=0 )
,因为活动开始时您设置了id =0
的值,所以if (id !=0 )
永远不会成立。
用于发送数据:
Intent intent = new Intent(this, SecondActivity.class);
intent.putExtra("arg", YourData);
startActivity(intent);
用于接收数据:
String data = getIntent().getExtras().getString("arg");
更新
删除if( id != 0)
并使用if(getIntent().hasExtra("indicatorPositionStartt"))
像这样:
if (getIntent().hasExtra("indicatorPositionStartt")) {
int id = getIntent().getExtras().getInt("indicatorPositionStartt", 0);
String indicatorPositionStart = String.valueOf(id);
textView.setText(indicatorPositionStart);
}