Skip to content Skip to sidebar Skip to footer

Need SQLite To Replace Only Rows With New Information

I am making an SQLite database that is going to store information from a webserver(for an android app) that had data that may change at any time. It seems inefficient to me to dele

Solution 1:

I suggest you to solve that with these steps:

  • Create a convenience-method isTechnicalEqual(Vehicle pVehicle) in Vehicle which compares all attributes except the ID attribute:

            //Dont forgett Nullcheck!
            if (!this.gettrackID().equals(pVehicle.gettrackID()))
            return false;
            //etc... after all attribute are checked:
            return true;
    

    If one attribute is not equal return false. At the end of the function return true.

  • Now select all existing Vehicle's from your local database and store it in a Map<Integer,Vehicle> lLocalDb //The Integer is your Vehicle-ID

  • Create two Lists: List<Vehicle> for Vehicle's which must be inserted and another one for the updates.
  • Iterate over all passed Vehicle's and call:

        Vehicle lVehicleDB = lLocalDb.get(lVehicle.getId());
        if (null == lVehicleDB){
          lInsertList.add(lVehicleDB);
        }else{
          if (!lVehicleDB.isTechnicalEqual(lVehicle))
            lUpdateList.add(lVehicle);
        }
    
  • After the loop is finished do the following stuff:

        if (!lInsertList.isEmpty){
          //Call SQLite insert for the list lInsertList
        }
        if (!lUpdateList.isEmpty){
          // Call SQLite update for the list lUpdateList
        }
    

Solution 2:

It sounds to me like you want to make use of functionality built into the framework named "Loaders" (introduced in API 3.0). This will automatically update the dataset backing your list, and provide updates to the UI (which you can act upon when you want).

http://developer.android.com/guide/components/loaders.html

If you are using a ViewHolder in your adapter, if data updates in your list (but isn't appearing on the screen), the dataset will be updated, but the user won't be effected (until they scroll to the new data, which will be there).

I think you should make use of this built-in functionality, instead of using a custom approach (as this should be more extensible).


Post a Comment for "Need SQLite To Replace Only Rows With New Information"