我想從類Product中添加一個對象到我的SQLite數據庫,但是如果我調用dbhandler.addProduct(Product product)方法,模擬器會崩潰並且logcat不會顯示任何錯誤。SQLite不會創建行和崩潰
我ListviewActivity:
ArrayAdapter<Product> adapter;
ArrayList<Product> productnames=new ArrayList<>();
DBHandler dbhandler;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView productList=(ListView)findViewById(android.R.id.list);
dbhandler=new DBHandler(this,null,null,1);
adapter= new CustomAdapter(this,productnames);
productList.setAdapter(adapter);
}
public void addNewProduct(View view){
EditText userInput=(EditText)findViewById(R.id.userInput);
userInput.setVisibility(View.VISIBLE);
String productname=userInput.getText().toString();
if(productname.equals(""))return;
Product product=new Product();
product.set_productname(productname);
product.set_checked(false);
productnames.add(product);
dbhandler.addProduct(product);
adapter.notifyDataSetChanged();
userInput.setText("");
}
如果我註釋掉dbhandler.addProduct(產品)一切工作正常。
我DBHandler類:
public class DBHandler extends SQLiteOpenHelper{
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME="products.db";
public static final String TABLE_PRODUCTS= "products";
public static final String COLUMN_ID="_id";
public static final String COLUMN_PRODUCTNAME="productname";
public static final String COLUMN_ISCHECKED="ischecked";
public DBHandler(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context, DATABASE_NAME, factory, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
String query= "CREATE TABLE" + TABLE_PRODUCTS + "("+
COLUMN_ID + "INTEGER PRIMARY KEY AUTOINCREMENT" +
COLUMN_PRODUCTNAME + "TEXT" +
COLUMN_ISCHECKED + "BOOLEAN" +
");";
db.execSQL(query);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS" + TABLE_PRODUCTS);
onCreate(db);
}
public void addProduct(Product product){
ContentValues values= new ContentValues();
values.put(COLUMN_PRODUCTNAME,product.get_productname());
values.put(COLUMN_ISCHECKED,product.is_checked());
SQLiteDatabase db=getWritableDatabase();
db.insert(TABLE_PRODUCTS,null,values);
db.close();
}
什麼崩潰?你有沒有? –
Logcat請。 – Razgriz
首先檢入/data/data/packagename/databases/products.db是否存在? –