我正遇到我的代码的问题,当我尝试使用insert(tablename,null,contenValues)函数在数据库中插入信息时,它返回-1。 这是我的代码
public void addItem(View view) {
String t1 = nameEt.getText().toString();
String t2 = priceEt.getText().toString();
if(t1.isEmpty() || t2.isEmpty()) {
Functions.message(this, "Enter both fields");
}
else {
long id = helper.insertData(t1, t2);
if (id<=0) {
Functions.message(this, "Unsuccessful");
}
else {
Functions.message(this, "Inserted!");
}
}
class myDataBaseAdapter {
private myDataBaseHelper myhelper;
myDataBaseAdapter(Context context) {
myhelper = new myDataBaseHelper(context);
}
long insertData(String name, String price) {
long id;
SQLiteDatabase db = myhelper.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(myDataBaseHelper.NAME, name);
contentValues.put(myDataBaseHelper.PRICE, price);
id = db.insert(myDataBaseHelper.TABLE_NAME, null, contentValues);
return id;
}
static class myDataBaseHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "myDataBase";
private static final String TABLE_NAME = "myTable";
private static final int DATABASE_VERSION = 1;
private static final String UID = "_id";
private static final String NAME = "Name";
private static final String PRICE = "Price";
private static final String CREATE_TABLE = "CREATE TABLE "+DATABASE_NAME+" ("+UID+" INTEGER PRIMARY KEY AUTOINCREMENT, "+NAME+" VARCHAR(255), "+PRICE+" VARCHAR(255));";
private static final String DROP_TABLE = "DROP TABLE IF EXISTS "+TABLE_NAME;
private Context context;
myDataBaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
this.context = context;
Functions.message(context, "constructor called");
}
@Override
public void onCreate(SQLiteDatabase db) {
try {
db.execSQL(CREATE_TABLE);
Functions.message(context, "onCreate called");
} catch (SQLException e) {
Functions.message(context, ""+e);
}
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
try {
db.execSQL(DROP_TABLE);
Functions.message(context, "onUpgrade called");
onCreate(db);
} catch (SQLException e) {
Functions.message(context, ""+e);
}
}
}
}
消息功能只是一个简单的祝酒消息,对我有帮助。 如果这有任何区别,我正在使用android studio。 我该如何纠正
答案 0 :(得分:0)
在尝试在onCreate()
上进行插入时,您的myDataBase
创建一个名为myTable
的表。更改
"CREATE TABLE "+DATABASE_NAME+"
到
"CREATE TABLE "+TABLE_NAME+"
您可以卸载应用程序以重新创建数据库。
在那里,请考虑删除所有这些catch (SQLException)
块-如果SQL存在问题,它们将被隐藏。您希望尽早发现编程错误。