我有两个按钮,当我们单击第一个按钮时,我们应该将M值分配给一个字符串,而对于第二个按钮,我想将F值分配给相同的字符串变量
在下面给出的代码中,性别是字符串变量,该变量为null,当我们单击regmalebtn时,我们应该将值M传递给字符串性别,将F传递给第二个按钮
在XML中,我没有将设置文本添加到两个按钮中。当我这样做时,传递了空值,并且我得到了空指针异常。
如何解决?任何帮助将不胜感激
提前感谢...!
String gender = null;
Button regmalebtn = (Button) findViewById(R.id.regmalebtn);
Button regfemalebtn = (Button) findViewById(R.id.regfemalebtn);
// Here in the above line I m getting the error//
public void onClick(View v) {
switch(v.getId()){
case R.id.regmalebtn:
// gender = regmalebtn.getText().toString();
gender.equals("M");
// request.addProperty("gender",gender );
break;
case R.id.regfemalebtn:
// gender = regfemalebtn.getText().toString();
gender.equals("F");
// request.addProperty("gender", gender);
break;
default:
break;
}
}
Button regmalebtn = (Button) findViewById(R.id.regmalebtn);
regmalebtn.setOnClickListener(this);
Button regfemalebtn = (Button) findViewById(R.id.regfemalebtn);
regfemalebtn .setOnClickListener(this);
public void onClick(View v)
{
switch(v.getId())
{
case R.id.regmalebtn:
gender = "M";
break;
case R.id.regfemalebtn:
gender = "F";
break;
default:
break;
}
}
// gender = regmalebtn.getText().toString();
或
gender.equals("F");
它们都为空。并且为变量赋值的正确方法是:
variable = value;
根据您的情况,而不是:
gender.equals("F")
您使用:
gender = "F"; // or gender = new String("F");
**String gender = "";**
Button regmalebtn = (Button) findViewById(R.id.regmalebtn);
regmalebtn.setOnClickListener(this);
Button regfemalebtn = (Button) findViewById(R.id.regfemalebtn);
regfemalebtn .setOnClickListener(this);
public void onClick(View v)
{
switch(v.getId())
{
case R.id.regmalebtn:
gender = "M";
break;
case R.id.regfemalebtn:
gender = "F";
break;
default:
break;
}
}
public class MainActivity extends AppCompatActivity
{
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView show= (TextView) findViewById(R.id.result);
//Buttons and their values
final Button male= (Button) findViewById(R.id.male);
final Button female= (Button) findViewById(R.id.female);
final View.OnClickListener gender =new View.OnClickListener(){
@Override
public void onClick(View v)
{
final int id=v.getId();
switch (id){
case R.id.male:{
show.setText("male"); //It will show gender in textView.
gen="male";
break;
}
case R.id.female:{
show.setText("female");
gen="female";
break;
}
default:
break;
}
}
};
male.setOnClickListener(gender);
female.setOnClickListener(gender);
}
}