我正在尝试创建一个创建对象并将其保存在TreeSet中的应用程序,但是当我按下该按钮时,应用程序崩溃了。我需要帮助
MainActivity如下:
public class MainActivity extends Activity {
private TreeSet<Variable> arbreDeVariables = new TreeSet<Variable>();
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
creeUneVariable();
}
private void creeUneVariable() {
Button boutonEnvoyer = (Button)findViewById(R.id.button1);
boutonEnvoyer.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
Variable variable = new Variable(getUsername(), getPassword());
arbreDeVariables.add(variable);
}
});
}
private String getUsername(){
final EditText username = (EditText)findViewById(R.id.editText1);
return username.getText().toString();
}
private String getPassword(){
final EditText password = (EditText)findViewById(R.id.editText2);
return password.getText().toString();
}
}
“变量”类如下:
public class Variable {
private String username;
private String password;
public Variable(String username,String password){
this.username = username;
this.password = password;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String toString(){
return "Username: "+username+" Password: "+password;
}
}
答案 0 :(得分:0)
我说你的一个editText或按钮没有被命名为你在代码中使用它。所以你会得到一个NullPointerException
答案 1 :(得分:0)
我很少修改代码尝试使用这种方式..
public class MainActivity extends Activity {
private TreeSet<Variable> arbreDeVariables = new TreeSet<Variable>();
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button boutonEnvoyer = (Button)findViewById(R.id.button1);
boutonEnvoyer.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
Variable variable = new Variable(getUsername(), getPassword());
arbreDeVariables.add(variable);
}
});
}
private String getUsername(){
final EditText username = (EditText)findViewById(R.id.editText1);
return username.getText().toString();
}
private String getPassword(){
final EditText password = (EditText)findViewById(R.id.editText2);
return password.getText().toString();
}
}