Java – How to optimize the insertion of entries with multiple strings and images into a SQLite database

How to optimize the insertion of entries with multiple strings and images into a SQLite database… here is a solution to the problem.

How to optimize the insertion of entries with multiple strings and images into a SQLite database

I defined a method to add an entry in my database helper class and use it to insert data into the database, but it doesn’t work. This is the method I defined in the databasehelper class:

 public void createchannelEntry(ChannelPoster channel) {
        openDB();
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        channel.getPoster().compress(Bitmap.CompressFormat.PNG, 100, out);
        ContentValues cv = new ContentValues();
        cv.put(KEY_POSTER, out.toByteArray());            
        cv.put(KEY_CHANNEL, channel.getChannel());
        cv.put(KEY_PATH, channel.getPath());
        cv.put(KEY_DBLINK, channel.getDBlink());

mDb.insert(channelS_TABLE, null, cv);
        closeDB();
    }

This is how I insert the data

Bitmap sherlock = BitmapFactory.decodeResource(getResources(), R.drawable.sherlock);

mDB.createchannelEntry(new ChannelPoster(sherlock, "aa" ,"ll"  ,"ha" ));

I have a JavaBean to hold entries

public class ChannelPoster {
    private Bitmap poster;
    private String channel;
    private String path;
    private String dblink;

public ChannelPoster(Bitmap pi, String c, String p, String d) {
        poster = pi;
        channel = c;
        path = p;
        dblink = d;
    }

public Bitmap getPoster() { return poster; }
    public String getChannel() { return channel; }
    public String getPath() { return path; }
    public String getDBlink() { return dblink; }
}

And because I am adding entries one by one, the program runs slowly, so is there a faster way to insert many entries? Love getting all of this in one activity?

Solution

I recommend not saving images in a database, but saving them as files, and saving their paths in the database (using normal TEXT fields).

If you don’t want to do this, there are two things that can still greatly improve your processing speed:

  • Only the database is opened and closed around all inserts
  • Use Transactions

Something like that :

SQLiteDatabase db = openDB();
db.beginTransaction();

try {
     Add here the loop with all your inserts
    db.setTransactionSuccessful();
} finally {
    db.endTransaction();   will rollback and cancel the inserts if not marked as successful
    db.close();
}

(Finally is to ensure that you close transactions and connections, even if it fails in some way during inserts: in this case, ALL your inserts will be canceled).

Related Problems and Solutions