Reputation: 303
I am a beginner in Android application development. I'm just trying to get Switch value from one Activity and display it in another activity. But I am getting 'null' as output. Please help me.
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);
}
}
Upvotes: 2
Views: 2168
Reputation: 60
In Question3.java, you are getting the intent method of getStringExtra
although the value you want to pass is a switch value.
Option 1: Use .toString
method to convert the value from the switch widget to get the value in String.
Option 2 (Recommended): Since you already have the setup to take String values in Question3 class, simply pass the value
string and just get it in the next Activity.
Hope it helps.
Upvotes: 0
Reputation: 521
write as :
String r;
if(swi.isChecked())
r = "true";
else
r= "false";
intent.putExtra("Ans1",r);
Instead of
intent.putExtra("Ans1",swi.isChecked());
Upvotes: 1