Storing Offline Data to Upload to Api When Online in Android

Salvage information in a local database using Room Part of Android Jetpack.

Apps that handle non-trivial amounts of structured data can do good profoundly from persisting that data locally. The almost common utilise case is to cache relevant pieces of information so that when the device cannot access the network, the user tin can still browse that content while they are offline.

The Room persistence library provides an brainchild layer over SQLite to permit fluent database access while harnessing the full ability of SQLite. In particular, Room provides the following benefits:

  • Compile-time verification of SQL queries.
  • Convenience annotations that minimize repetitive and error-prone boilerplate code.
  • Streamlined database migration paths.

Because of these considerations, nosotros highly recommend that y'all employ Room instead of using the SQLite APIs direct.

Setup

To apply Room in your app, add together the following dependencies to your app's build.gradle file:

Keen

dependencies {     def room_version = "2.4.2"      implementation "androidx.room:room-runtime:$room_version"     annotationProcessor "androidx.room:room-compiler:$room_version"      // optional - RxJava2 support for Room     implementation "androidx.room:room-rxjava2:$room_version"      // optional - RxJava3 support for Room     implementation "androidx.room:room-rxjava3:$room_version"      // optional - Guava back up for Room, including Optional and ListenableFuture     implementation "androidx.room:room-guava:$room_version"      // optional - Examination helpers     testImplementation "androidx.room:room-testing:$room_version"      // optional - Paging iii Integration     implementation "androidx.room:room-paging:2.5.0-alpha01" }            

Kotlin

dependencies {     val roomVersion = "two.4.2"      implementation("androidx.room:room-runtime:$roomVersion")     annotationProcessor("androidx.room:room-compiler:$roomVersion")      // To use Kotlin notation processing tool (kapt)     kapt("androidx.room:room-compiler:$roomVersion")     // To apply Kotlin Symbolic Processing (KSP)     ksp("androidx.room:room-compiler:$roomVersion")      // optional - Kotlin Extensions and Coroutines back up for Room     implementation("androidx.room:room-ktx:$roomVersion")      // optional - RxJava2 support for Room     implementation("androidx.room:room-rxjava2:$roomVersion")      // optional - RxJava3 back up for Room     implementation("androidx.room:room-rxjava3:$roomVersion")      // optional - Guava support for Room, including Optional and ListenableFuture     implementation("androidx.room:room-guava:$roomVersion")      // optional - Test helpers     testImplementation("androidx.room:room-testing:$roomVersion")      // optional - Paging 3 Integration     implementation("androidx.room:room-paging:2.5.0-alpha01") }            

Primary components

There are three major components in Room:

  • The database class that holds the database and serves as the main access signal for the underlying connectedness to your app's persisted data.
  • Information entities that represent tables in your app's database.
  • Data access objects (DAOs) that provide methods that your app can utilise to query, update, insert, and delete information in the database.

The database course provides your app with instances of the DAOs associated with that database. In plow, the app tin can use the DAOs to call up data from the database equally instances of the associated information entity objects. The app tin as well use the defined data entities to update rows from the corresponding tables, or to create new rows for insertion. Figure 1 illustrates the relationship between the different components of Room.

Effigy 1. Diagram of Room library architecture.

Sample implementation

This section presents an example implementation of a Room database with a single data entity and a single DAO.

Data entity

The following code defines a User data entity. Each instance of User represents a row in a user table in the app'southward database.

Kotlin

@Entity data class User(     @PrimaryKey val uid: Int,     @ColumnInfo(name = "first_name") val firstName: String?,     @ColumnInfo(name = "last_name") val lastName: Cord? )            

Java

@Entity public class User {     @PrimaryKey     public int uid;      @ColumnInfo(name = "first_name")     public String firstName;      @ColumnInfo(proper noun = "last_name")     public String lastName; }            

To learn more about data entities in Room, run into Defining data using Room entities.

Data admission object (DAO)

The following code defines a DAO called UserDao. UserDao provides the methods that the balance of the app uses to interact with data in the user tabular array.

Kotlin

@Dao interface UserDao {     @Query("SELECT * FROM user")     fun getAll(): List<User>      @Query("SELECT * FROM user WHERE uid IN (:userIds)")     fun loadAllByIds(userIds: IntArray): List<User>      @Query("SELECT * FROM user WHERE first_name Similar :kickoff AND " +            "last_name LIKE :terminal LIMIT i")     fun findByName(get-go: Cord, last: Cord): User      @Insert     fun insertAll(vararg users: User)      @Delete     fun delete(user: User) }            

Coffee

@Dao public interface UserDao {     @Query("SELECT * FROM user")     List<User> getAll();      @Query("SELECT * FROM user WHERE uid IN (:userIds)")     List<User> loadAllByIds(int[] userIds);      @Query("SELECT * FROM user WHERE first_name LIKE :first AND " +            "last_name Like :concluding LIMIT i")     User findByName(String first, String last);      @Insert     void insertAll(User... users);      @Delete     void delete(User user); }            

To learn more than near DAOs, encounter Accessing data using Room DAOs.

Database

The following lawmaking defines an AppDatabase grade to hold the database. AppDatabase defines the database configuration and serves every bit the app'southward main access point to the persisted data. The database course must satisfy the following conditions:

  • The class must exist annotated with a @Database annotation that includes an entities array that lists all of the data entities associated with the database.
  • The grade must be an abstract course that extends RoomDatabase.
  • For each DAO class that is associated with the database, the database form must define an abstract method that has aught arguments and returns an instance of the DAO class.

Kotlin

@Database(entities = [User::class], version = 1) abstruse course AppDatabase : RoomDatabase() {     abstract fun userDao(): UserDao }            

Coffee

@Database(entities = {User.class}, version = i) public abstract grade AppDatabase extends RoomDatabase {     public abstruse UserDao userDao(); }            

Annotation: If your app runs in a unmarried procedure, you should follow the singleton design design when instantiating an AppDatabase object. Each RoomDatabase instance is fairly expensive, and you rarely need admission to multiple instances within a single process.

If your app runs in multiple processes, include enableMultiInstanceInvalidation() in your database builder invocation. That way, when you have an instance of AppDatabase in each process, y'all can invalidate the shared database file in one procedure, and this invalidation automatically propagates to the instances of AppDatabase within other processes.

Usage

Afterward you lot have defined the information entity, the DAO, and the database object, you can utilise the post-obit code to create an instance of the database:

Kotlin

val db = Room.databaseBuilder(             applicationContext,             AppDatabase::class.java, "database-proper noun"         ).build()            

Java

AppDatabase db = Room.databaseBuilder(getApplicationContext(),         AppDatabase.course, "database-proper noun").build();            

You tin can then use the abstract methods from the AppDatabase to go an instance of the DAO. In turn, you lot can utilise the methods from the DAO instance to collaborate with the database:

Kotlin

val userDao = db.userDao() val users: List<User> = userDao.getAll()            

Coffee

UserDao userDao = db.userDao(); List<User> users = userDao.getAll();            

Boosted resources

To learn more about Room, see the following boosted resources:

Sample

  • Android Sunflower, a gardening app that illustrates Android development best practices with Android Jetpack.
  • Tivi, a TV testify tracking app that uses the latest libraries and tools.

Codelabs

  • Android Room with a View (Java) (Kotlin)

Blogs

  • 7 Pro-tips for Room
  • Incrementally drift from SQLite to Room

copelandtrince1983.blogspot.com

Source: https://developer.android.com/training/data-storage/room

0 Response to "Storing Offline Data to Upload to Api When Online in Android"

Postar um comentário

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel