Convert Figma logo to code with AI

android logoarchitecture-components-samples

Samples for Android Architecture Components.

23,423
8,284
23,423
195

Top Related Projects

Samples for Android Architecture Components.

17,635

A gardening app illustrating Android development best practices with migrating a View-based app to Jetpack Compose.

Official Jetpack Compose samples.

13,082

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

  1. 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.

  1. 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.

  1. 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:

  1. Clone the repository:
    git clone https://github.com/android/architecture-components-samples.git
    
  2. Open the project in Android Studio.
  3. Choose a sample from the project structure.
  4. 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.

17,635

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.

13,082

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 Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

Android Architecture Components samples

A collection of samples using the Architecture Components:

Samples

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.