我是Android应用程序开发的初学者。我只是想从一个Activity中获取Switch值并将其显示在另一个Activity中。但我得到'null'作为输出。请帮帮我。
Question1.java
public class Question1Activity extends AppCompatActivity {
Switch swi;
Button back1, next1;
String value = "NO";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_question1);
swi = (Switch) findViewById(R.id.Switch_Ques_1);
back1 = (Button) findViewById(R.id.Button_back1);
next1 = (Button) findViewById(R.id.Button_next1);
swi.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
if (isChecked) {
swi.setText("YES");
value="YES";
swi.setTextColor(Color.GREEN);
} else {
swi.setText("NO");
value="NO";
swi.setTextColor(Color.RED);
}
}
});
back1.setOnClickListener(new View.OnClickListener(){
public void onClick(View view){
Intent intent = new Intent(Question1Activity.this,LoginActivity.class);
startActivity(intent);
}
});
next1.setOnClickListener(new View.OnClickListener(){
public void onClick(View view){
Intent intent = new Intent(Question1Activity.this,Question2Activity.class);
intent.putExtra("Ans1",swi.isChecked());
startActivity(intent);
}
});
}
}
Question3.java
public class Question3Activity extends AppCompatActivity {
TextView t1;
private SQLiteDatabase database;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_question3);
t1 = (TextView) findViewById(R.id.result);
Intent intent = getIntent();
String s1 =(String) intent.getStringExtra("Ans1");
String s2 = intent.getStringExtra("Ans2");
t1.setText(s1+" "+s2);
}
}
答案 0 :(得分:1)
写为:
String r;
if(swi.isChecked())
r = "true";
else
r= "false";
intent.putExtra("Ans1",r);
而不是
intent.putExtra("Ans1",swi.isChecked());
答案 1 :(得分:0)
在Question3.java中,您获得了getStringExtra
的intent方法,尽管您要传递的值是切换值。
选项1:使用.toString
方法转换交换机小部件中的值以获取String中的值。
选项2(推荐):由于您已经设置了在Question3类中获取String值,因此只需传递value
字符串,然后在下一个Activity中获取它。
希望它有所帮助。