我是移动应用程序构建的初学者。我试图将插入数据功能放入我的android studio中,但似乎这些插入功能不起作用,并且无法插入输入数据。请帮忙。
我在MainActivity.java和DatabaseHelper.java中放入了一些代码。它没有任何错误报告,但是当我尝试运行模拟器并输入数据时,我的输入可以插入到sqlite数据库中。
// oncreateMainActivity
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myDb = new DatabaseHelper(this);
name2 = findViewById(R.id.name2);
birthdate2 = findViewById(R.id.birthdate2);
area2 = findViewById(R.id.area2);
receiver2 = findViewById(R.id.receiver2);
submit2 = findViewById(R.id.submit2);
submit2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
name = name2.getText().toString();
birth = birthdate2.getText().toString();
area = area2.getText().toString();
receiver = receiver2.getText().toString();
...
insertData2 (name, birth, area, receiver);
...
public void insertData2 (String name,String birth,String area, String receiver){
boolean add_data = myDb.insertData(name,birth,area,receiver);
if (!add_data){
Toast.makeText(MainActivity.this,"Something went wrong><", Toast.LENGTH_LONG).show();
}
else{
Toast.makeText(MainActivity.this,"Success to add data!", Toast.LENGTH_LONG).show();
}
}
//DatabaseHelper.java
public boolean insertData(String childname ,String bornday, String areaprogram, String receiverid){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL1, childname);
contentValues.put(COL2, bornday);
contentValues.put(COL3, areaprogram);
contentValues.put(COL4, receiverid);
long result = db.insert(TABLE_NAME, null, contentValues);
if(result == -1){
return false;
}
else{
return true;
}
}
最佳答案
put()
方法的第一个参数是列的名称,但是您传递了该值,将其更改为(当然请替换为您的列名,例如"Name"
,"Birthdate"
等):
public boolean insertData(String Name,String Birthdate,String Area, String ID){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(ColunNameForName, Name);
contentValues.put(ColunNameForBirthdate, Birthdate);
contentValues.put(ColunNameForArea, Area);
contentValues.put(ColunNameForID, ID);
long result = db.insert(TABLE_NAME, null, contentValues);
if(result == -1){
return false;
}
else{
return true;
}
}