我试图更好地了解 Android 版 SQLite,但遇到了问题。我的测试程序只有一个文本框和按钮。当您在文本框中输入文本并单击按钮时,我希望它创建一个新的“联系人”(数据库类)。
public class Home extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
DatabaseHandler db = new DatabaseHandler(this);
String name = "";
Button upButton = (Button) findViewById(R.id.button1);
upButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v, String name) {
EditText editText = (EditText)findViewById(R.id.editText1);
name = editText.getText().toString();
TextView textView = (TextView)findViewById(R.id.textView2);
textView.setText(name);
}
});
db.addContact(new Contact(1,name));
}
}
正如您所看到的,当他们单击时,它会将文本框中的任何内容保存为名称。我只是希望能够将其发送到 addContact 函数调用。我也对如何在 onClick 函数中使用我的 db 类感到有点困惑?理想情况下,我只想在 onClick 内更新它,或者我会吗?
最佳答案
为什么不在 onClickListener
中编写 db.addContact(new Contact(1,name));
代码行?
如果您不想这样做,请在 Activity
中编写一个方法,然后从 onClickListener
调用它。
private void addContact(String name) {
db.addContact(new Contact(1,name));
}
在onCreate()
方法中;
Button upButton = (Button) findViewById(R.id.button1);
upButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v, String name) {
EditText editText = (EditText)findViewById(R.id.editText1);
name = editText.getText().toString();
addContact(name);
}
});
关于java - 通过 onClick 传递字符串 var,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16551329/