Top Related Projects
Samples for Android Architecture Components.
A gardening app illustrating Android development best practices with migrating a View-based app to Jetpack Compose.
Official Jetpack Compose samples.
A sample audio app for Android
A fully functional Android app built entirely with Kotlin and Jetpack Compose
Quick Overview
The android/architecture-components-samples repository is a collection of samples demonstrating how to use Android Architecture Components and best practices in Android development. It showcases various components like ViewModel, LiveData, Room, and Navigation, providing developers with practical examples of implementing these components in real-world scenarios.
Pros
- Comprehensive examples covering multiple Architecture Components
- Well-structured and maintained by the official Android team
- Regularly updated to reflect the latest best practices and APIs
- Includes both Kotlin and Java implementations for most samples
Cons
- Some samples may be complex for beginners
- Not all samples are kept up-to-date with the latest libraries and patterns
- Limited coverage of edge cases or more advanced scenarios
- Some samples may lack detailed explanations or comments
Code Examples
- Using ViewModel and LiveData:
class MyViewModel : ViewModel() {
private val _data = MutableLiveData<String>()
val data: LiveData<String> = _data
fun loadData() {
_data.value = "Hello, Architecture Components!"
}
}
This example shows a basic ViewModel with LiveData, demonstrating how to expose immutable LiveData to the UI while keeping the mutable version private.
- Room database setup:
@Database(entities = [User::class], version = 1)
abstract class AppDatabase : RoomDatabase() {
abstract fun userDao(): UserDao
companion object {
@Volatile private var instance: AppDatabase? = null
fun getInstance(context: Context): AppDatabase {
return instance ?: synchronized(this) {
instance ?: buildDatabase(context).also { instance = it }
}
}
private fun buildDatabase(context: Context) =
Room.databaseBuilder(context, AppDatabase::class.java, "Sample.db")
.build()
}
}
This code sets up a Room database with a singleton pattern, ensuring only one instance of the database is created.
- Navigation component usage:
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
view.findViewById<Button>(R.id.navigate_button).setOnClickListener {
findNavController().navigate(R.id.action_homeFragment_to_detailFragment)
}
}
This example demonstrates how to use the Navigation component to navigate between fragments using the findNavController()
method.
Getting Started
To get started with the samples:
- Clone the repository:
git clone https://github.com/android/architecture-components-samples.git
- Open the project in Android Studio.
- Choose a sample from the project structure.
- Run the sample on an emulator or physical device.
For more detailed instructions, refer to the README.md file in each sample's directory.
Competitor Comparisons
Samples for Android Architecture Components.
Pros of architecture-components-samples
- Demonstrates best practices for Android architecture components
- Regularly updated with new samples and features
- Comprehensive coverage of various Android development scenarios
Cons of architecture-components-samples
- May be overwhelming for beginners due to the large number of samples
- Some samples might not be applicable to specific project requirements
- Requires a good understanding of Android architecture principles
Code Comparison
architecture-components-samples:
class UserViewModel(private val repository: UserRepository) : ViewModel() {
private val _user = MutableLiveData<User>()
val user: LiveData<User> = _user
fun loadUser(userId: String) {
viewModelScope.launch {
_user.value = repository.getUser(userId)
}
}
}
As the comparison is between the same repository, there is no different code to compare.
Summary
The architecture-components-samples repository is an excellent resource for Android developers looking to implement best practices and explore various architecture components. It offers a wide range of samples covering different scenarios, which can be both beneficial and potentially overwhelming. The repository's regular updates ensure that developers have access to the latest Android development techniques and patterns. However, it may require a solid foundation in Android development to fully utilize and understand the provided examples.
A gardening app illustrating Android development best practices with migrating a View-based app to Jetpack Compose.
Pros of Sunflower
- More focused and cohesive example of a single app
- Demonstrates modern Android development practices in a real-world scenario
- Regularly updated with the latest Android architecture components and libraries
Cons of Sunflower
- Less comprehensive in covering all architecture components
- May be overwhelming for beginners due to its complexity
- Limited to a single use case, which may not cover all developer needs
Code Comparison
Sunflower (PlantDetailFragment.kt):
private fun subscribeUi(adapter: PlantAdapter, binding: FragmentPlantDetailBinding) {
viewModel.plant.observe(viewLifecycleOwner) { plant ->
binding.plant = plant
plant?.let {
adapter.submitList(it.plantings)
}
}
}
Architecture Components Samples (BasicSample/UserActivity.kt):
private fun updateUserName() {
viewModel.userName.observe(this, Observer { userName ->
binding.userName.text = userName
})
}
Both examples demonstrate the use of ViewModel and LiveData, but Sunflower's implementation is more complex and showcases additional components like data binding and list adapters.
Official Jetpack Compose samples.
Pros of compose-samples
- Focuses on modern UI development with Jetpack Compose
- Provides more up-to-date examples of Android app architecture
- Demonstrates integration of Compose with other Jetpack libraries
Cons of compose-samples
- Limited coverage of traditional View-based UI development
- May be less suitable for developers maintaining legacy Android apps
- Smaller number of samples compared to architecture-components-samples
Code Comparison
architecture-components-samples (XML-based UI):
<TextView
android:id="@+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />
compose-samples (Jetpack Compose UI):
@Composable
fun Greeting(name: String) {
Text(text = "Hello $name!")
}
Summary
compose-samples is ideal for developers looking to adopt Jetpack Compose and modern Android development practices. It offers fewer but more focused examples. architecture-components-samples provides a broader range of samples covering various architecture components, making it valuable for developers working with both new and legacy Android projects. The code comparison highlights the shift from XML-based layouts to declarative UI in Kotlin.
A sample audio app for Android
Pros of uamp
- Focuses on a complete, real-world music player application
- Demonstrates media playback and audio-specific Android features
- Includes examples of UI testing and integration with Android Auto
Cons of uamp
- Less diverse in terms of architecture component examples
- May be overwhelming for beginners due to its complexity
- Fewer individual, focused samples for specific components
Code Comparison
uamp (MediaItemAdapter.kt):
override fun onBindViewHolder(holder: MediaViewHolder, position: Int) {
val item = getItem(position)
holder.item = item
holder.titleView.text = item.description.title
holder.subtitleView.text = item.description.subtitle
holder.imageView.setImageBitmap(item.description.iconBitmap)
}
architecture-components-samples (UserAdapter.kt):
override fun onBindViewHolder(holder: UserViewHolder, position: Int) {
val user = getItem(position)
holder.bind(user)
}
The uamp example shows more detailed view binding, while the architecture-components-samples code is more concise and relies on a separate bind function.
A fully functional Android app built entirely with Kotlin and Jetpack Compose
Pros of Now in Android
- Showcases a complete, production-ready app with modern Android development practices
- Implements Jetpack Compose for UI, demonstrating its usage in a real-world scenario
- Utilizes more recent libraries and patterns, such as Hilt for dependency injection
Cons of Now in Android
- More complex and potentially overwhelming for beginners
- Focuses on a single, opinionated architecture, which may not suit all project needs
- Requires more setup and understanding of advanced concepts to get started
Code Comparison
Architecture-components-samples:
@Dao
interface UserDao {
@Query("SELECT * FROM user")
fun getAll(): List<User>
@Insert
fun insertAll(vararg users: User)
}
Now in Android:
@Dao
interface TopicDao {
@Query("""
SELECT * FROM topics
WHERE id IN (:topicIds)
""")
fun getTopicEntities(topicIds: Set<String>): Flow<List<TopicEntity>>
@Upsert
suspend fun upsertTopics(topics: List<TopicEntity>)
}
The Now in Android example demonstrates more advanced usage of Room, including Flow and suspend functions for coroutines support.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
Android Architecture Components samples
A collection of samples using the Architecture Components:
Samples
-
BasicSample - Shows how to persist data using a SQLite database and Room. Also uses ViewModels and LiveData.
-
PersistenceContentProviderSample - Shows how to expose data via a Content Provider using Room.
-
GithubBrowserSample - An advanced sample that uses the Architecture components, Dagger and the Github API, in Kotlin.
-
BasicRxJavaSample - Shows how to use Room with RxJava 2. Also uses ViewModels.
-
PersistenceMigrationsSample - Shows how to implement migrations in Room.
-
BasicRxJavaKotlinSample - Shows how to use ViewModels and Room together with RxJava, in Kotlin.
-
PagingSample - Shows how to use the Paging library with Room, in Kotlin.
-
PagingNetworkSample - Shows how to use the Paging library with a backend API via Retrofit, in Kotlin.
-
NavigationBasicSample - Shows how to use Navigation to perform navigation and deep linking in Kotlin.
-
NavigationAdvancedSample - Shows how to handle multiple back stacks with Navigation and a BottomNavigationView.
-
LiveDataSample - Shows how to integrate Kotlin coroutines with Architecture Components such as
LiveData
. -
ViewBindingSample - Shows how to use view bindings in an activity and in fragments.
-
WorkManagerSample - Shows how to use WorkManager to do background work, in Kotlin.
-
WorkManagerMultiprocessSample - Shows how to use WorkManager in apps that manage multiple processes.
Reporting Issues
You can report an Issue on the samples using this repository. If you find an issue with the Architecture Components, report it using the Architecture Components Issue Tracker
License
Copyright 2018 The Android Open Source Project, Inc.
Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
Top Related Projects
Samples for Android Architecture Components.
A gardening app illustrating Android development best practices with migrating a View-based app to Jetpack Compose.
Official Jetpack Compose samples.
A sample audio app for Android
A fully functional Android app built entirely with Kotlin and Jetpack Compose
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot