在我的应用程序中,我有2个EditText和Button。
单击按钮,我想从EditText获取值并将其插入SQLite数据库
但是我的代码不起作用,我的数据库也没有创建。
MainActivity.java:
public class MainActivity extends AppCompatActivity {
EditText editText1,editText2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText1 = (EditText) findViewById(R.id.editText);
editText2 = (EditText) findViewById(R.id.editText2);
findViewById(R.id.btn).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String name = editText1.getText().toString();
String family = editText2.getText().toString();
}
});
}
And Person.java:
public class Person {
private long id;
private String name;
private String family;
public Person() {
}
public Person(String name, String family) {
this.name = name;
this.family = family;
}
public Person(long id, String name, String family) {
this.id = id;
this.name = name;
this.family = family;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getFamily() {
return family;
}
public void setFamily(String family) {
this.family = family;
}
And PersonDatabaseAdapter:
public class PersonDatabaseAdapter {
private Context context;
private SQLiteOpenHelper sqLiteOpenHelper;
public PersonDatabaseAdapter(Context context) {
this.context = context;
sqLiteOpenHelper = new SQLiteOpenHelper(context, "database.db", null, 1) {
@Override
public void onCreate(SQLiteDatabase db) {
String sql = "create table tbl_persons (id integer primary key, name text, family text)";
db.execSQL(sql);
}
@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
}
};
}
public long savePerson(Person person) {
String name = person.getName();
String family = person.getFamily();
long id = -1;
SQLiteDatabase database = null;
try {
ContentValues values = new ContentValues();
values.put("name", name);
values.put("family", family);
database = sqLiteOpenHelper.getWritableDatabase();
id = database.insert("tbl_persons", null, values);
} catch (Exception ex) {
Log.d("Database", "Exception:" + ex.getMessage());
} finally {
if( database != null && database.isOpen()) {
database.close();
}
}
return id;
}
答案 0 :(得分:0)
您需要在savePerson
方法中调用onClick
函数。
findViewById(R.id.btn).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String name = editText1.getText().toString();
String family = editText2.getText().toString();
Person person = new Person(name, family);
savePerson(person);
}
});