【发布时间】:2021-12-31 19:34:01
【问题描述】:
我想在 sqlite android 中保存文本文件,但它在long result = db.insert(TABLE_NAME,null,cv); 行给出错误android.database.sqlite.SQLiteConstraintException: NOT NULL constraint failed:。
@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;
}
}
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...... 但它仍然无法将文本文件保存在 db 中.感谢您的帮助。
【问题讨论】:
-
want to save text file in sqlite您的代码中没有文本文件。我们唯一看到的是您尝试将字节数组保存为 blob。
标签: java android sqlite android-sqlite sql-insert