Deepak
Deepak

Reputation: 157

How to achieve Synchronization in Room (Android persistence library)

In normal sqlite we can achieve Synchronization easily but How to implement it in Room

Upvotes: 6

Views: 8689

Answers (3)

Vinay Kumar
Vinay Kumar

Reputation: 111

@Database(entities = [Student::class,Teacher::class], version = 1, exportSchema = false)
@TypeConverters(DataTypeConverter::class)
abstract class ClassDatabase : RoomDatabase() {

 // initiate database

 abstract fun studentDao()
 abstract fun teacherDao()
}

val database = ClassDatabase(context)
database.beginTransaction()
try{
   //write your operations
    database.setTransactionSuccessful()
   }
finally{
    database.endTransaction()
     }

Upvotes: 0

Ishwor Khanal
Ishwor Khanal

Reputation: 1370

Here is the sample which shows how to use Room with Content Provider which then you can link (ContentProvider ) with your SynchronizationAdapter.

Having said that you can modify your Room model as like

@Entity(tableName = Student.TABLE_NAME) 
public class Student { 
    /** The name of the Student table. */ 
    public static final String TABLE_NAME = "student"; 


    /** The name of the ID column. */ 
    public static final String COLUMN_ID = BaseColumns._ID; 


    /** The name of the name column. */ 
    public static final String COLUMN_NAME = "name"; 


    /** The unique ID of the Student*/ 
    @PrimaryKey(autoGenerate = true) 
    @ColumnInfo(index = true, name = COLUMN_ID) 
    public long id; 


    /** The name of the Student*/ 
    @ColumnInfo(name = COLUMN_NAME) 
    public String name; 


    /** 
     * Create a new {@link Studentfrom the specified {@link ContentValues}. 
     * 
     * @param values A {@link ContentValues} that at least contain {@link #COLUMN_NAME}. 
     * @return A newly created {@link Student} instance. 
     */ 
    public static Student fromContentValues(ContentValues values) { 
        final Student student= new Student(); 
        if (values.containsKey(COLUMN_ID)) {
            student.id = values.getAsLong(COLUMN_ID); 
        } 
        if (values.containsKey(COLUMN_NAME)) { 
            student.name = values.getAsString(COLUMN_NAME); 
        }
        return student; 
    }
}

Upvotes: 5

Pascal Ganaye
Pascal Ganaye

Reputation: 1364

As you stated "this is easy to achieve synchronization with SQLITE"

Room uses internally a SQLite Database. I believe the methods of SQLite are accessible in Room. Consequently, it should be easy with room too.

This said the Sqlite classes are wrapped into Room classes you might have to write a bit of plumbing. What do you use for your easy synchronization?

Upvotes: 0

Related Questions