0

I was working on saving data that is in one to many relationship. Like Country has many states as the image below

Here is the model the db table is build up on Hint as to what the sqlite db table looks like

public class Country {

    private int countryId;

    private String countryName;

    private List<State> states;
}

and here is the country and state saving code.

public void saveToDb(List<Country> countries) {

    for(Country country: countries){
        saveCountry(country);

        List<State> states = country.getStates();

        for(State state :states)
            saveState(state);
    }
}

Knowing how expensive nested loops can be, I was wondering if there was an efficient way of saving that data without using nested loops. Any help would be very much appreciated

display name
  • 879
  • 11
  • 20

1 Answers1

1

you can do batch insertion :

db.beginTransaction();
for (Country country: countries) {
    saveCountry(country);
    List<State> states = country.getStates();

    for(State state :states)
        saveState(state);
}
db.setTransactionSuccessful();
db.endTransaction();

put your db.beginTransaction(); , db.setTransactionSuccessful(); and db.endTransaction(); outside the loop.

MinFu
  • 353
  • 1
  • 13
  • the idea was to just use one for loop, save both country and state with just one loop – display name Nov 05 '16 at 03:38
  • putting the begintransaction, settransaction and end transaction outside the loop does improve the performance. in my opinion loop can run fast in device the transaction that happen in each loop was the reason why the performance is slow. you may refer to this stackoverflow answer http://stackoverflow.com/questions/3501516/android-sqlite-database-slow-insertion – MinFu Nov 05 '16 at 05:25