Search code examples
androidandroid-sqliteindexoutofboundsexception

SQLite calls the same INSERT command twice


I was trying to insert multiple data based on two arrays. Both contains different value. And I want to insert them into one same table.

In my DBHandler I wrote INSERT statement as below

public void addData(Foto foto) {
    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues values = new ContentValues();
    values.put(KEY_TGL, foto.getDate());
    values.put(KEY_SITEID, foto.getSiteid());
    values.put(KEY_KATEGORI, foto.getKategori());
    values.put(KEY_FILENAME, foto.getFilename());
    values.put(KEY_PATH, foto.getPath());

    db.insert(TABLE_SHOPS, null, values);
    db.close();
}

And in my activity. I wrote like this

for(int i=0;i<=namefile.length;i++){
            Bitmap[] bitmap = new Bitmap[namefile.length];
            FileOutputStream outputStream = new FileOutputStream(String.valueOf(namefile[i]));
            bitmap[i] = BitmapFactory.decodeByteArray(decodedString[i],0,decodedString[i].length);
            bitmap[i].compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
            outputStream.close();

            MediaStore.Images.Media.insertImage(getActivity().getContentResolver(), namefile[i].getAbsolutePath(), namefile[i].getName(), namefile[i].getName());

            db.addData(new Foto(fDate,siteid,"genset_progres",namefile[i].getName(),namefile[i].getAbsolutePath()));
        }

        for(int a=0;a<=var.length;a++){
            db.addData(new Foto(fDate,siteid,"genset_progres","",var[a]));
        }

I intended to insert the data of namefile and the data of var into same table. So I wrote like above...But when I call them only namefile got inserted into database. I'm sorry I'm not quite understand about how looping and SQLITE works on android since this is my first time trying it. Maybe u guys can help me. I'd appreciate it a lot.

If there's anything I should provide...dont hesitate to ask.


Solution

  • replace

    for(int i=0;i<=namefile.length;i++)
    

    to

    for(int i=0;i<namefile.length;i++)
    

    and also

    for(int a=0;a<=var.length;a++)
    

    to

    for(int a=0;a<var.length;a++)
    

    so that you could run the code without ArrayOutOfBoundsException.