Learn to work with databases on Android using the Room persistence library.

Overview

Bus Scheduler App

This folder contains the source code for the Bus Scheduler app codelab.

Introduction

The Bus Scheduler app displays a list of bus stops and arrival times. Tapping a bus stop on the first screen will display a list of all arrival times for that particular stop.

The bus stops are stored in a Room database. Schedule items are represented by the Schedule class and queries on the data table are made by the ScheduleDao class. The app includes a view model to access the ScheduleDao and format data to be display in a list, using Flow to send data to a recycler view adapter.

Pre-requisites

  • Experience with Kotlin syntax.
  • Familiarity with activities, fragments, and recycler views.
  • Basic knowledge of SQL databases and performing basic queries.

Getting Started

  1. Install Android Studio, if you don't already have it.
  2. Download the sample.
  3. Import the sample into Android Studio.
  4. Build and run the sample.
Comments
  • Step 8: Accessing database on main thread leads to app crash

    Step 8: Accessing database on main thread leads to app crash


    name: 'Android Basics: Introduction to Room and Flow issue template' about: 'Cannot access database on the main thread.' title: 'Android Basics: Introduction to Room and Flow' labels: '' assignees: ''


    URL of codelab https://developer.android.com/codelabs/basic-android-kotlin-training-intro-room-flow?continue=https%3A%2F%2Fdeveloper.android.com%2Fcourses%2Fpathways%2Fandroid-basics-kotlin-unit-5-pathway-1%23codelab-https%3A%2F%2Fdeveloper.android.com%2Fcodelabs%2Fbasic-android-kotlin-training-intro-room-flow#7

    In which task and step of the codelab can this issue be found? 8 - 4. (really 9, also bad numbers on indexes)Finally, to update a list view, call submitList(), passing in the list of bus stops from the view model 8- 11 Then configure the recycler view in onCreate(). This time you just need to pass in an empty block (function) with {}. You don't actually want anything to happen when rows on this screen are tapped.

    Describe the problem these lines code busStopAdapter.submitList(viewModel.scheduleForStopName()) busStopAdapter.submitList(viewModel.fullSchedule()) java.lang.IllegalStateException: Cannot access database on the main thread since it may potentially lock the UI for a long period of time. no sure but need to run it on corouitines? (only that way i make it work) also the onCreate() of 8 - 11 (onViewCreated)

    Steps to reproduce? complete the codelabs to the poit 8 inclusive 6/12 inclusive

    Versions _Android Studio version:_4.2.1 API version of the emulator: 28

    Additional information

    opened by raulhaag 9
  • Data changes using Flow: Android Basics: Introduction to Room and Flow

    Data changes using Flow: Android Basics: Introduction to Room and Flow

    In the instructions for changing the FullScheduleFragment it says:

    Replace the line.

    busStopAdapter.submitList(viewModel.fullSchedule())

    With this code that uses the flow returned from fullSchedule().

    lifecycle.coroutineScope.launch {
       viewModel.fullSchedule().collect() {
           busStopAdapter.submitList(it)
       }
    }
    

    When it should say to replace the entire GlobalScope function. The same goes for the StopScheduleFragment section

    opened by mcchots 7
  • Android Basics: Introduction to Room and Flow

    Android Basics: Introduction to Room and Flow

    Inside onCreate() in the StopScheduleFragment, busStopAdapter.submitList(viewModel.scheduleByStopName()) should be called instead as : busStopAdapter.submitList(viewModel.scheduleByStopName(stopName)) I am not sure but most probably this is correct!

    image

    opened by tnahata 5
  • Android Basics: Introduction to Room and Flow

    Android Basics: Introduction to Room and Flow

    Create list adapter at the end "Now that you've set up the adapter, you're done integrating Room into the Bus Schedule app. Take a moment to run the app and you should see a list of arrival times. Tapping on a row should navigate to the detail screen." Got error

    FATAL EXCEPTION: main
        Process: com.example.busschedule, PID: 22917
        java.lang.IllegalStateException: Cannot access database on the main thread since it may potentially lock the UI for a long period of time.
    

    in main branch

            lifecycle.coroutineScope.launch {
                viewModel.fullSchedule().collect() {
                    busStopAdapter.submitList(it)
                }
            }
    

    But in course there is none

            recyclerView.adapter = busStopAdapter
            busStopAdapter.submitList(viewModel.fullSchedule())
    

    soz you have to use something like this:

            lifecycleScope.launch {
                busStopAdapter.submitList(viewModel.fullSchedule())
            }
    

    and in viewModel sort of:

        suspend fun fullSchedule(): List<Schedule> = withContext(Dispatchers.IO) {
            scheduleDao.getAll()
        }
    
    opened by pentiux 4
  • Issue downloading `starter` branch

    Issue downloading `starter` branch

    Whenever you try to download the starter app in GitHub, the main branch is downloaded instead. All the changes are already done for the codelab. The only way I could get around it was to copy and change the URL to say "starter" rather than "main."

    opened by aredshaw 3
  • Android Basics: Introduction to Room and Flow

    Android Basics: Introduction to Room and Flow

    This example would be improved with more explanation for each new section of code, especially on Step 8, to say why each step is needed. Currently it's just saying effectively "write this code, then write this code, then this, etc.." and the application may work at the end but without enough clarity to really explain what is happening. This is based on having worked through the previous tutorials on view models etc.

    opened by pgilhead 2
  • Android Basics: Introduction to Room and Flow - grammar

    Android Basics: Introduction to Room and Flow - grammar

    In the "Define the ViewModel" step, there is a sentence that reads "As the ViewModel class BusScheduleViewModel needs from is meant to be lifecycle aware, it should be instantiated by an object that can respond to lifecycle events."

    Should this instead be? "As the ViewModel class BusScheduleViewModel is meant to be lifecycle aware, it should be instantiated by an object that can respond to lifecycle events."

    opened by nichojo89 2
  • Android Basics: Introduction to Room and Flow

    Android Basics: Introduction to Room and Flow

    It seems as if there's a typo in step 6 of the "Introduction to Room and Flow" Codelab.

    "As the ViewModel class BusScheduleViewModel needs from is meant to be lifecycle aware, it should be instantiated by an object that can respond to lifecycle events." image

    opened by BankSinatra 2
  • Step 8: Accessing database on main thread leads to app crash

    Step 8: Accessing database on main thread leads to app crash

    Followed instructions as provided. App crashes while testing the result of Step 8.

    I compared my code to the main code and apart from the Flow introductions in Step 9 is the same.

    Error given by the debugger is:

    E/AndroidRuntime: FATAL EXCEPTION: main Process: com.example.busschedule, PID: 26884 java.lang.IllegalStateException: Cannot access database on the main thread since it may potentially lock the UI for a long period of time. at androidx.room.RoomDatabase.assertNotMainThread(RoomDatabase.java:385) at androidx.room.RoomDatabase.query(RoomDatabase.java:441) at androidx.room.util.DBUtil.query(DBUtil.java:83) at com.example.busschedule.database.schedule.ScheduleDao_Impl.getAll(ScheduleDao_Impl.java:29) at com.example.busschedule.viewmodel.BusScheduleViewModel.fullSchedule(BusScheduleViewModel.kt:10) at com.example.busschedule.FullScheduleFragment$onViewCreated$1.invokeSuspend(FullScheduleFragment.kt:77) at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33) at kotlinx.coroutines.internal.DispatchedContinuationKt.resumeCancellableWith(DispatchedContinuation.kt:342) at kotlinx.coroutines.intrinsics.CancellableKt.startCoroutineCancellable(Cancellable.kt:30) at kotlinx.coroutines.intrinsics.CancellableKt.startCoroutineCancellable$default(Cancellable.kt:27) at kotlinx.coroutines.CoroutineStart.invoke(CoroutineStart.kt:109) at kotlinx.coroutines.AbstractCoroutine.start(AbstractCoroutine.kt:158) at kotlinx.coroutines.BuildersKt__Builders_commonKt.launch(Builders.common.kt:56) at kotlinx.coroutines.BuildersKt.launch(Unknown Source:1) at kotlinx.coroutines.BuildersKt__Builders_commonKt.launch$default(Builders.common.kt:49) at kotlinx.coroutines.BuildersKt.launch$default(Unknown Source:1) at com.example.busschedule.FullScheduleFragment.onViewCreated(FullScheduleFragment.kt:76) at androidx.fragment.app.Fragment.performViewCreated(Fragment.java:2987) at androidx.fragment.app.FragmentStateManager.createView(FragmentStateManager.java:546) at androidx.fragment.app.FragmentStateManager.moveToExpectedState(FragmentStateManager.java:282) at androidx.fragment.app.FragmentStore.moveToExpectedState(FragmentStore.java:112) at androidx.fragment.app.FragmentManager.moveToState(FragmentManager.java:1647) at androidx.fragment.app.FragmentManager.dispatchStateChange(FragmentManager.java:3128) at androidx.fragment.app.FragmentManager.dispatchViewCreated(FragmentManager.java:3065) at androidx.fragment.app.Fragment.performViewCreated(Fragment.java:2988) at androidx.fragment.app.FragmentStateManager.createView(FragmentStateManager.java:546) at androidx.fragment.app.FragmentStateManager.moveToExpectedState(FragmentStateManager.java:282) at androidx.fragment.app.FragmentStore.moveToExpectedState(FragmentStore.java:112) at androidx.fragment.app.FragmentManager.moveToState(FragmentManager.java:1647) at androidx.fragment.app.FragmentManager.dispatchStateChange(FragmentManager.java:3128) at androidx.fragment.app.FragmentManager.dispatchActivityCreated(FragmentManager.java:3072) at androidx.fragment.app.FragmentController.dispatchActivityCreated(FragmentController.java:251) at androidx.fragment.app.FragmentActivity.onStart(FragmentActivity.java:501) at androidx.appcompat.app.AppCompatActivity.onStart(AppCompatActivity.java:246) at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1425) at android.app.Activity.performStart(Activity.java:7825) at android.app.ActivityThread.handleStartActivity(ActivityThread.java:3294) at android.app.servertransaction.TransactionExecutor.performLifecycleSequence(TransactionExecutor.java:221) at android.app.servertransaction.TransactionExecutor.cycleToPath(TransactionExecutor.java:201) at android.app.servertransaction.TransactionExecutor.executeLifecycleState(TransactionExecutor.java:173) at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:97) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2016) at android.os.Handler.dispatchMessage(Handler.java:107) at android.os.Looper.loop(Looper.java:214) at android.app.ActivityThread.main(ActivityThread.java:7356) at java.lang.reflect.Method.invoke(Native Method) E/AndroidRuntime: at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)

    opened by DrirEmilius 2
  • Android Basics: Introduction to Room and Flow

    Android Basics: Introduction to Room and Flow

    Just letting you know that the package database.schedule doesn't exist in this project. There is only a database package located in the assets directory and no subdirectory or package named schedule within it. Should we just create a directory within database called schedule or create a new package altogether within java called database.schdule?

    These are the instructions I'm referring to:

    "Note that the SQL types used in the database are actually INTEGER for Int and TEXT for String. When working with Room, however, you should only be concerned with the Kotlin types when defining your model classes. Mapping the data types in your model class to the ones used in the database is handled automatically.

    To create an entity for the "schedule" table, in the database.schedule package, create a new file called Schedule.ktand define a data class called Schedule."

    opened by shawn-fetanat 2
  • Android Basics: Introduction to Room and Flow

    Android Basics: Introduction to Room and Flow

    In section 4: Create an Entitiy, it is stated, "To create an entity for the "schedule" table, in the database.schedule package, create a new file called Schedule.kt and define a data class called Schedule."

    There is not a "database.schedule" package within the Project Manager. My assumption is that it is referencing "assets/database", but this needs to be clarified.

    opened by crave503 2
  • Android Basics: Introduction to Room and Flow

    Android Basics: Introduction to Room and Flow

    I downloaded the project from the "main" branch, I open it and try to compile it without changing anything - it says that there is an error in ActivityMain, R.id.nav_host_fragment is highlighted.

    Internal Error occurred while analyzing this expression:
    java.lang.NullPointerException
    at com.android.tools.idea.res.AarResourceRepositoryCache.createCachingData(AarResourceRepositoryCache.kt:108)
    at com.android.tools.idea.res.AarResourceRepositoryCache.access$createCachingData(AarResourceRepositoryCache.kt:42)
    at com.android.tools.idea.res.AarResourceRepositoryCache$getSourceRepository$1.invoke(AarResourceRepositoryCache.kt:62)
    at com.android.tools.idea.res.AarResourceRepositoryCache$getSourceRepository$1.invoke(AarResourceRepositoryCache.kt:61)
    at com.android.tools.idea.res.AarResourceRepositoryCache$Companion$getRepository$1.invoke(AarResourceRepositoryCache.kt:136)
    at com.android.tools.idea.res.AarResourceRepositoryCache$Companion$getRepository$1.invoke(AarResourceRepositoryCache.kt:136)
    at com.android.utils.concurrency.CacheUtils$sam$java_util_concurrent_Callable$0.call(CacheUtils.kt)
    at com.google.common.cache.LocalCache$LocalManualCache$1.load(LocalCache.java:4868)
    at com.google.common.cache.LocalCache$LoadingValueReference.loadFuture(LocalCache.java:3533)
    at com.google.common.cache.LocalCache$Segment.loadSync(LocalCache.java:2282)
    at com.google.common.cache.LocalCache$Segment.lockedGetOrLoad(LocalCache.java:2159)
    at com.google.common.cache.LocalCache$Segment.get(LocalCache.java:2049)
    at com.google.common.cache.LocalCache.get(LocalCache.java:3966)
    at com.google.common.cache.LocalCache$LocalManualCache.get(LocalCache.java:4863)
    at com.android.utils.concurrency.CacheUtils.getAndUnwrap(CacheUtils.kt:33)
    at com.android.tools.idea.res.AarResourceRepositoryCache$Companion.getRepository(AarResourceRepositoryCache.kt:136)
    at com.android.tools.idea.res.AarResourceRepositoryCache$Companion.access$getRepository(AarResourceRepositoryCache.kt:127)
    at com.android.tools.idea.res.AarResourceRepositoryCache.getSourceRepository(AarResourceRepositoryCache.kt:61)
    at com.android.tools.idea.res.ResourceRepositoryManager.lambda$computeLibraryResourceMap$5(ResourceRepositoryManager.java:765)
    at java.base/java.util.concurrent.FutureTask.run(Futur...
    opened by eclipsn 0
  • Android Basics: Introduction to Room and Flow

    Android Basics: Introduction to Room and Flow

    This whole Kotlin thing went from 0 to a 100 real quick. Every lesson until now was understandable, even if I didn't understand something that I wrote, a quick Googleing job would help, but things happening in here are high above my knowledge, knowledge that I gained from previous classes. Description of steps is very poor, the only thing I can do is a lot of retyping and almost no understanding of what I'm doing.

    opened by Eagle528 0
  • Android Basics: Introduction to Room and Flow

    Android Basics: Introduction to Room and Flow

    "FullScheduleFragmentDirections" showing error as Unresolved reference

    and " .navigate(action)" as Overload resolution ambiguity

    But the project builds successfully.

    opened by grvknight 1
  • Android Basics: Introduction to Room and Flow

    Android Basics: Introduction to Room and Flow

    private val viewModel: BusScheduleViewModel by activityViewModels { BusScheduleViewModelFactory( (activity?.application as BusScheduleApplication).database.scheduleDao() ) }

    Missing from starter code. No mention in the tutorial. Would be nice to get an explanation, that would complete this tutorial for me. 
    
    
    nevermind, found it here https://developer.android.com/codelabs/basic-android-kotlin-training-intro-room-flow?continue=https%3A%2F%2Fdeveloper.android.com%2Fcourses%2Fpathways%2Fandroid-basics-kotlin-unit-5-pathway-1%23codelab-https%3A%2F%2Fdeveloper.android.com%2Fcodelabs%2Fbasic-android-kotlin-training-intro-room-flow#7
    
    opened by PMLyf 0
Owner
Google Developer Training
Google Developer Training
Small project on using Room + MVVM + data binding

healthinfo This is a demo project that utilizes Room Database, MVVM, Data binding, Repositories, Retrofit and more to build an app that reads content

Mohammad Ali Fouani 0 Nov 24, 2021
This application features - Modern Minimalistic Design, MVVM, Pagination, Hilt, Retrofit, Room, Data Store, Flow, Live Data, Navigation Component (Clean Architecture)

NewsFly NewsFly is a modern news android application which features virtually ALL recent and recommended android development tech stack and tools used

Ibrahim 121 Nov 4, 2022
Room - SleepQualityTracker app

Room - SleepQualityTracker app This is the toy app for Lesson 6 of the Android App Development in Kotlin course on Udacity. SleepQualityTracker The Sl

null 0 Jun 10, 2022
ROOM Database Example with MVVM in Kotlin[Fragments,Navigation]

RoomDatabase_SampleApp Room Database Sample App Overview Of This Room Database Application In this app, we can do operation on room database | Insert,

RUHUL AMIN CHOUDHURY 0 Nov 3, 2021
REST API with Retrofit, SQLite with Room, Hilt, MVVM, Jetpack Compose

Simple REST API Learn how to make an Android App that will call a REST API using Retrofit to retrieve some data that will be stored in SQLite using Ro

Yayo Arellano 26 Dec 23, 2022
A sample Album list app that shows how to use ViewModels and Room together with RxJava & Dagger2, in Kotlin by Clean Architecture.

Kotlin-MVVM-Hilt A sample Album list app that shows how to use ViewModels and Room together with RxJava & Dagger2, in Kotlin by Clean Architecture. Im

hpAndro 1 May 12, 2022
MVVM(Model View ViewModel) sample in Kotlin using the components ViewModel, LiveData and Retrofit library

kotlin-mvvm Languages: English, Spanish MVVM(Model View ViewModel) sample in Kotlin using the components ViewModel, LiveData, the libraries Retrofit,

Eduardo José Medina Alfaro 466 Jan 5, 2023
📚 Sample Android Components Architecture on a modular word focused on the scalability, testability and maintainability written in Kotlin, following best practices using Jetpack.

Android Components Architecture in a Modular Word Android Components Architecture in a Modular Word is a sample project that presents modern, 2020 app

Madalin Valceleanu 2.3k Dec 30, 2022
ListView Example with custom Adapter Using Kotlin in Android Studio

Kotlin-ListView ListView Example with custom Adapter Using Kotlin in Android Studio Steps to follow : Build ListView with Custom Adapter in Kotlin Add

null 0 Nov 5, 2021
This is An Android Project. in which we use SqLite Database. We perform Insert,delete,update and Show The existing data. operations using SqLite.

SqLite Database Keywords : SqLite, Android, Database This is An Android Project. in which we use SqLite Database. We perform Insert,delete,update and

Rudra_deep 1 Nov 7, 2021
A sample app that demonstrate how to build an Android application using the Uncle Bob's Clean Architecture approach

A sample app that demonstrate how to build an Android application using the Uncle Bob's Clean Architecture approach

Ahmed Shaban  Elhdad 2 Apr 8, 2022
A sample photo browsing app in Kotlin, Android using Picsum image API.

Picsum Photo App Functionality The app's functionality includes: Fetch a list of images from picsum photos api (https://picsum.photos/) and show them

Rafsan Ahmad 15 Nov 2, 2022
FTUE sample using Jetpack Navigation's Navigation-Compose, ViewModel, SavedStateHandle, Hilt

Jetpack Navigation's Navigation-Compose + Jetpack Compose + NavGraphs + SavedStateHandle + Dagger-Hilt + EventEmitter (toasts / navigation commands) T

Gabor Varadi 15 Dec 8, 2022
This is an example repository to demonstrate the good practices of using ViewModel and how usage of AndroidViewModel can make things worst in a codebase

ViewModel Good Practices ??‍♂️ This is a example repository to demonstrate the good practices of using ViewModel and how usage of AndroidViewModel can

Shreyas Patil 29 Sep 28, 2022
Displays a list of albums using latest libraries

Albums Application Demo Displays a list of albums using latest libraries Used Clean Architecture #Domain: Contains the definitions of the business log

null 0 Nov 3, 2021
TouchNotes - a note application using Kotlin

Touch Notes Touch Notes is a note application using androidx libraries, MVVM wit

Abhinav 3 Jan 8, 2022
A simple list-detail application using the Github API

GitHub Users Search Android application to search users via GitHub API Project demonstrates how to use Kotlin, Android Architecture Components, Dagger

Ndu Sunday 2 May 26, 2022
Example Android library project that works with jitpack.io

android-example Example Android library project that works with jitpack.io. See this Tutorial on how to publish an Android Library with JitPack. For m

Denys Denysenko 0 Dec 20, 2021
A collection of samples to discuss and showcase different architectural tools and patterns for Android apps.

Android Architecture Blueprints v2 Android Architecture Blueprints is a project to showcase different architectural approaches to developing Android a

Android 42k Jan 3, 2023