Saving Data on Android



Download 19,28 Mb.
Pdf ko'rish
bet112/292
Sana24.01.2022
Hajmi19,28 Mb.
#407089
1   ...   108   109   110   111   112   113   114   115   ...   292
Bog'liq
Bailey J., Dominguez A., Djermanovic D. - Saving Data on Android (1st Edition) - 2019

Database
On a device, the data is stored on a local SQLite database. Room provides an 
additional layer on top of the usual SQLite APIs that avoids having to create a lot of 
boilerplate code using the 
SQLiteOpenHelper
 class.
Saving Data on Android
Chapter 5: Room Architecture
raywenderlich.com
95


For instance, suppose you want to create a simple database that stores a question 
table for a quiz app, like the one you are going to be building in the next chapter. A 
traditional implementation using the standard SQLite APIs would look something 
like this:
private
 const 
val
 SQL_CREATE_ENTRIES = 
        
"CREATE TABLE question ("
 + 
                
"question_id INTEGER PRIMARY KEY,"
 + 
                
"text TEXT"
 
 
private
 const 
val
 SQL_DELETE_ENTRIES = 
"DROP TABLE IF EXISTS 
question"
 
 
class
 
QuizDbHelper
(context: Context) : SQLiteOpenHelper(context, 
DB_NAME, 
null
, DATABASE_VERSION) { 
    
companion
 
object
 { 
        const 
val
 DATABASE_VERSION = 
1
 
        const 
val
 DB_NAME = 
"question_database.db"
 
    } 
    
override
 
fun
 
onCreate
(db: SQLiteDatabase)
 { 
        db.execSQL(SQL_CREATE_ENTRIES) 
    } 
    
override
 
fun
 
onUpgrade
(db: SQLiteDatabase, oldVersion: Int, 
newVersion: Int)
 { 
        db.execSQL(SQL_DELETE_ENTRIES) 
        onCreate(db) 
    } 
    
override
 
fun
 
onDowngrade
(db: SQLiteDatabase, oldVersion: 
Int, newVersion: Int)
 { 
        onUpgrade(db, oldVersion, newVersion) 
    } 
}
On the other hand, with Room the code becomes much more concise and easier to 
understand:
@Database(entities = [(Question::class)
], version = 
1

abstract
 
class
 
QuestionDatabase
 : 
RoomDatabase
() { 
  
abstract
 
fun
 
questionsDao
()
: QuestionDao 
}
As you can see, the amount of boilerplate code was drastically reduced since Room 
handles most of the database interaction for you under the hood.
Saving Data on Android
Chapter 5: Room Architecture
raywenderlich.com
96


En//es
Entities in Room represent tables in your database and are usually defined in Kotlin 
as data classes. Let's take a look at the following Entity that is used to define a 
question table:
@Entity(tableName = "question")
 
//1
 
data
 
class
 
Question

    
@PrimaryKey
 
//2
 
    
@ColumnInfo(name = "question_id")
 
//3
 
    
var
 questionId: 
Int

    
@ColumnInfo(name = "text")
 
    
val
 text: String)
Room gives you many annotations that allow you to define how your data class is 
going to be translated into an SQLite table.
Taking each commented section in turn:
1. The 
@Entity
 annotation tells Room that this data class is an 
Entity
. You can use 
many different parameters to tell Room how this 
Entity
 is going to be translated 
into an 
SQLite
 table. In this case, you are using the 
tableName
 parameter to 
define the name for the table.
2. The 
@PrimaryKey
 annotation is mandatory and each 
Entity
 must have at least 
one field annotated as the primary key. You could also use the 
primaryKeys
 
parameter inside your 
@Entity
 annotation to define your primary key.
3. The 
@ColumnInfo
 annotation is optional but very useful since it allows specific 
customization for your column. For example, you can define a custom name or 
change the data type.
DAOs
DAO stands for Data Access Object. DAOs are interfaces or abstract classes that 
Room uses to interact with your database using annotated functions. Your DAOs will 
typically implement one or more CRUD operations on a particular 
Entity
.
Saving Data on Android
Chapter 5: Room Architecture
raywenderlich.com
97


The code for a DAO that interacts with the question 
Entity
 defined above would 
look like this:
@Dao
 
//1
 
interface
 
QuestionDao
 { 
     
  
@Insert(onConflict = OnConflictStrategy.REPLACE)
 
//2
 
  
fun
 
insert
(question: Question)
 
 
  
@Query("DELETE FROM question")
 
//3
 
  
fun
 
clearQuestions
()
 
 
  
@Query("SELECT * FROM question ORDER BY question_id")
 
//4
 
  
fun
 
getAllQuestions
()
: LiveData
 
}
Step-by-Step:
1. The DAO annotation marks this interface as a Data Access Object. DAOs should 
always be abstract classes or interfaces since Room will internally create the 
necessary implementation at compile time for you according to the query 
methods that you provide.
2. The 
@Insert
 annotation declares that this method is going to perform a create 
operation by performing an 

Download 19,28 Mb.

Do'stlaringiz bilan baham:
1   ...   108   109   110   111   112   113   114   115   ...   292




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©hozir.org 2024
ma'muriyatiga murojaat qiling

kiriting | ro'yxatdan o'tish
    Bosh sahifa
юртда тантана
Боғда битган
Бугун юртда
Эшитганлар жилманглар
Эшитмадим деманглар
битган бодомлар
Yangiariq tumani
qitish marakazi
Raqamli texnologiyalar
ilishida muhokamadan
tasdiqqa tavsiya
tavsiya etilgan
iqtisodiyot kafedrasi
steiermarkischen landesregierung
asarlaringizni yuboring
o'zingizning asarlaringizni
Iltimos faqat
faqat o'zingizning
steierm rkischen
landesregierung fachabteilung
rkischen landesregierung
hamshira loyihasi
loyihasi mavsum
faolyatining oqibatlari
asosiy adabiyotlar
fakulteti ahborot
ahborot havfsizligi
havfsizligi kafedrasi
fanidan bo’yicha
fakulteti iqtisodiyot
boshqaruv fakulteti
chiqarishda boshqaruv
ishlab chiqarishda
iqtisodiyot fakultet
multiservis tarmoqlari
fanidan asosiy
Uzbek fanidan
mavzulari potok
asosidagi multiservis
'aliyyil a'ziym
billahil 'aliyyil
illaa billahil
quvvata illaa
falah' deganida
Kompyuter savodxonligi
bo’yicha mustaqil
'alal falah'
Hayya 'alal
'alas soloh
Hayya 'alas
mavsum boyicha


yuklab olish