Android Development Android Data Storage 2 — Questions and Answers
Question 1: Which Room annotation defines a foreign key relationship between two entities?
- @ForeignKey inside @Entity (Correct answer)
- @Relation
- @Join
- @Reference
Correct answer: @ForeignKey inside @Entity
The @ForeignKey annotation within @Entity defines referential integrity constraints between two Room database tables.
Question 2: How do you perform a database migration in Room when the schema changes?
- By providing a Migration object with SQL migration scripts (Correct answer)
- By deleting and recreating the database
- By using @SchemaVersion annotation
- Room handles migrations automatically
Correct answer: By providing a Migration object with SQL migration scripts
Room requires you to provide a Migration object containing the SQL statements needed to transform the old schema to the new one.
Question 3: What return type should a Room DAO method use to observe database changes reactively?
- Flow<T>
- LiveData<T>
- Observable<T>
- Both A and B (Correct answer)
Correct answer: Both A and B
Room supports both Flow<T> and LiveData<T> as return types for DAO queries, enabling reactive observation of database changes.
Question 4: Which method is used to get or create an instance of a Room database?
- Room.databaseBuilder() (Correct answer)
- RoomDatabase.create()
- Room.getInstance()
- RoomDatabase.build()
Correct answer: Room.databaseBuilder()
Room.databaseBuilder() creates or opens a Room database with the specified context, class, and database name.
Question 5: What is the purpose of the @TypeConverter annotation in Room?
- To convert non-primitive types that Room cannot store natively (Correct answer)
- To convert between database versions
- To transform query results
- To change column data types
Correct answer: To convert non-primitive types that Room cannot store natively
@TypeConverter marks methods that tell Room how to convert a custom type to and from a type it can store in SQLite.
Question 6: Which file access mode should be used to append data to a file in Android?
- MODE_APPEND (Correct answer)
- MODE_PRIVATE
- MODE_WORLD_READABLE
- MODE_WRITE_ONLY
Correct answer: MODE_APPEND
MODE_APPEND opens the file in append mode so new data is added to the end rather than overwriting existing content.
Which Room annotation defines a foreign key relationship between two entities?