0

我正在尝试制作一个创建对象并将其保存在 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;
}

}

4

2 回答 2

0

我会说你的一个 editText 或按钮的名称不像你在代码中使用它那样命名。所以你会得到一个 NullPointerException

于 2013-06-15T11:44:29.033 回答
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();
    }
}
于 2013-06-15T11:47:19.333 回答