我想在 sqlite android 中保存文本檔案,但它android.database.sqlite.SQLiteConstraintException: NOT NULL constraint failed:在 line 處出錯long result = db.insert(TABLE_NAME,null,cv);。
@Override
public void onCreate(SQLiteDatabase db) {
String create_table = "CREATE TABLE " TABLE_NAME "( "
"ID INTEGER PRIMARY KEY ,"
POSITION " TEXT NOT NULL, "
TXT_FILE " BLOB NOT NULL, "
_ID " TEXT NOT NULL)";
db.execSQL(create_table);
}
public boolean add_txt_file(String id, byte[] txt_file) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(_ID,id);
cv.put(TXT_FILE,txt_file);
long result = db.insert(TABLE_NAME,null,cv);
if (result == -1){
return false;
} else {
return true;
}
}
if (data != null) {
Uri uri = data.getData();
String path = uri.getPath();
path = path.substring(path.indexOf(":") 1);
Log.e("TAG", "readFile(path) " Arrays.toString(readFile(path)));
boolean save_txt_file = db.add_txt_file(id,
readFile(path));
if (save_txt_file){
Toast.makeText(this, "saved successfully", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "failed", Toast.LENGTH_SHORT).show();
}
private byte[] readFile(String file) {
ByteArrayOutputStream bos = null;
try {
File f = new File(Environment.getExternalStorageDirectory(),file);
FileInputStream fis = new FileInputStream(f);
byte[] buffer = new byte[1024];
bos = new ByteArrayOutputStream();
for (int len; (len = fis.read(buffer)) != -1;) {
bos.write(buffer, 0, len);
}
} catch (FileNotFoundException e) {
Log.e("TAG","error " e.getMessage());
} catch (IOException e2) {
System.err.println(e2.getMessage());
}
return bos != null ? bos.toByteArray() : null;
}
該path日志給這個Download/Link_on.txt和readFile(path)回報[49,10,48,48,58,48 ......但它仍然無法保存在資料庫中的文本檔案。謝謝您的幫助。
uj5u.com熱心網友回復:
在CREATE表的陳述句中,您已將列定義POSITION為NOT NULL,但在方法中add_txt_file()您沒有提供值。
添加類似這一行的內容:
cv.put(POSITION, "some value");
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/363304.html
標籤:爪哇 安卓 sqlite android-sqlite sql 插入
