【问题标题】:save text file in sqlite android在sqlite android中保存文本文件
【发布时间】: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


【解决方案1】:

在表的CREATE 语句中,您将列POSITION 定义为NOT NULL,但在方法add_txt_file() 中您没有提供值。

添加类似这一行的内容:

cv.put(POSITION, "some value");

【讨论】:

  • 但是我已经以这种方式创建了许多方法并且它们工作正常。此外,我正在尝试将文本文件分配给某个 id,并且我不需要其中的位置。
  • 我在上面添加了一个我目前使用的方法,只有两个值。
  • @aawasi 您不能在没有 POSITION 值的情况下向表中添加新行。如果您不需要该位置,那么您不应该将其定义为 NOT NULL。
  • 谢谢你的回答,最终的问题是NOT NULL。我删除了它,它起作用了。
  • @aawasi 这个问题是专门针对 android 的,我帮不了你。
猜你喜欢
  • 2018-07-02
  • 2016-08-01
  • 2015-01-24
  • 1970-01-01
  • 1970-01-01
  • 2016-06-30
  • 2015-12-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多