Home > Back-end >  save text file in sqlite android
save text file in sqlite android

Time:11-23

I want to save text file in sqlite android but it is giving an error android.database.sqlite.SQLiteConstraintException: NOT NULL constraint failed: at 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;
}

The path gives this in log Download/Link_on.txt and the readFile(path) returns [49, 10, 48, 48, 58, 48...... but it is still failing to save the text file in db. Thanks for the help.

CodePudding user response:

In the CREATE statement of the table you have defined the column POSITION as NOT NULL, but in the method add_txt_file() you don't supply a value.

Add something like this line:

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