此代码不返回任何单词。似乎它跳过了“ word =”行。等确实连接到正确的编辑文本框。我们使用调试来运行它,然后直接进入“ try”行,而没有给word提供et editText框的值。
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_word);
mydb = new DBHelper(this);
et = (EditText) findViewById(R.id.nw);
word = et.getText().toString();
Toast.makeText(getApplicationContext(),word,Toast.LENGTH_LONG).show();
l = (Button) findViewById(R.id.ad);
l.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {mydb.insertWord(word);}
catch(Exception e){
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_SHORT).show();
}
et.setText("");
}
});
b = (Button) findViewById(R.id.back);
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {Intent i = new Intent(AddWord.this, MainActivity.class);
startActivity(i);
}
});
}
答案 0 :(得分:1)
转换:
l.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {mydb.insertWord(word);}
catch(Exception e){
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_SHORT).show();
}
et.setText("");
}
收件人:
l.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {mydb.insertWord(et.getText().toString());}
catch(Exception e){
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_SHORT).show();
}
et.setText("");
}
并删除此内容:
word = et.getText().toString();
答案 1 :(得分:1)
这是因为在活动开始时就将edit-text的值设置为word。请记住,在活动开始时,edit-text为空,因此单词将具有空字符串。因此,为了在try块中获取当前值,您应该再次从edit-text获取最新值。您可以这样更改try块,
try {
word = et.getText().toString();
mydb.insertWord(word);
}
catch(Exception e){
Toast.makeText(getApplicationContext(),e.toString(),Toast.LENGTH_SHORT).show();
}