我的表没有在Sqlite中创建(Toast for dataNotInserted).Code片段在下面......
android.database.sqlite.SQLiteException: no such table: PETROL.DB (code 1): , while compiling: INSERT INTO PETROL.DB(AMOUNT) VALUES (?)
public class Activity2 extends AppCompatActivity {
EditText ET1;
Button B1;
Button Bview;
DatabaseHelper myDb;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_2);
myDb = new DatabaseHelper(this);
ET1 = findViewById(R.id.editText_amount);
B1 = findViewById(R.id.button_add);
Bview = findViewById(R.id.button_view);
AddData();
}
public void AddData() {
B1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
boolean isInserted = myDb.insertData(Integer.parseInt(ET1.getText().toString()));
if (isInserted == true) {
Toast.makeText(Activity2.this, "DataInserted", Toast.LENGTH_LONG).show();
} else
Toast.makeText(Activity2.this, "DataNotInserted", Toast.LENGTH_LONG).show();
}
}
);
}
}
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME="PETROL.DB";
public static final String TABLE_NAME="PETROL_TABLE";
public static final String COL_1="ID";
public static final String COL_2="AMOUNT";
public DatabaseHelper(Context context)
{
super(context,DATABASE_NAME,null,1);
}
@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
sqLiteDatabase.execSQL( "CREATE TABLE " + TABLE_NAME + "(" + COL_1 + " INTEGER PRIMARY KEY AUTOINCREMENT," + COL_2 + " INTEGER );");
Log.d("data","ghgc");
}
public boolean insertData(int data)
{
SQLiteDatabase sqLiteDatabase=this.getWritableDatabase();
ContentValues contextValues=new ContentValues();
contextValues.put("AMOUNT",data);
Log.d("insertData",Integer.toString(data));
long result= sqLiteDatabase.insert(DATABASE_NAME,null,contextValues);
if(result==-1)
return false;//to check if data is inserted
else
return true;
//sqLiteDatabase.close();
}
}
onUpgrade未提及,因为我还在使用版本1
答案 0 :(得分:1)
您的问题是根据消息导致的,因为您将数据库名称 PETROL.DB 传递给insert
方法而不是传递表名。根据方法的签名: -
long insert(String table, String nullColumnHack, ContentValues values)
将行插入数据库的便捷方法。 SQLiteDatabase - insert
正如此改变: -
long result= sqLiteDatabase.insert(DATABASE_NAME,null,contextValues);
来: -
long result= sqLiteDatabase.insert(TABLE_NAME,null,contextValues);