Développement Android Kotlin

VérifiéSûr

Développez des applications Android natives avec Kotlin, MVVM, Jetpack Compose, Retrofit et Room.

Spar Skills Guide Bot
DeveloppementIntermédiaire
02/08/2026
Claude CodeCursorWindsurfCopilotCodex
#android#kotlin#jetpack-compose#mvvm#retrofit

Recommandé pour

Synthèse automatique

Cette compétence guide la création d'applications Android natives en Kotlin, avec Retrofit, Hilt et des ViewModels MVVM exposant des StateFlow.

Points forts

  • Fournit des exemples complets et cohérents de modèles de données, d'interface Retrofit et de configuration du client réseau avec intercepteur d'authentification
  • Montre une implémentation MVVM propre avec MutableStateFlow/StateFlow et injection via @HiltViewModel
  • Couvre la gestion des états de chargement et d'erreur dans les ViewModels, un point souvent négligé

Limites

  • La description annonce Room, Jetpack Compose et l'architecture de navigation, mais le contenu fourni s'arrête avant de les traiter et semble tronqué
  • L'URL de base est codée en dur et l'accès au token passe par un PreferencesManager statique non défini
  • La gestion d'erreur est incohérente (println silencieux dans ItemsViewModel) et aucun test ni exemple d'interface Compose n'est fourni
Quand l'utiliser

À utiliser pour démarrer ou structurer une application Android Kotlin reposant sur Retrofit, Hilt et des ViewModels MVVM.

Quand l'éviter

À éviter si vous cherchez des exemples aboutis de Room, de navigation Compose ou d'interfaces Jetpack Compose, absents du contenu fourni.

Analyse de sécurité

Sûr
Score qualité76/100

The skill contains only instructional prose and Kotlin code examples. It does not instruct the agent to execute shell commands, download payloads, delete files, exfiltrate data, or disable safety mechanisms. The only notable security consideration is standard guidance around token handling in the sample interceptor, which is a code-quality concern rather than a listing risk.

Points d'attention
  • •Minor security note: the sample Retrofit interceptor attaches a bearer token to every request; real implementations should scope credentials to trusted hosts and prefer secure token storage.
Comment cette analyse est faite

Exemples

Set up an API layer
Create a Retrofit ApiService and Hilt NetworkModule for my Kotlin Android app, including a bearer-token interceptor and timeouts.
Build an MVVM ViewModel
Write a @HiltViewModel in Kotlin that loads a list of items from Retrofit and exposes items, isLoading and errorMessage as StateFlow.
Screen state handling
Refactor my Android ViewModel so loading and error states use StateFlow and errors are surfaced to the UI instead of being printed.

name: android-kotlin-development description: Develop native Android apps with Kotlin. Covers MVVM with Jetpack, Compose for modern UI, Retrofit for API calls, Room for local storage, and navigation architecture.

Android Kotlin Development

Overview

Build robust native Android applications using Kotlin with modern architecture patterns, Jetpack libraries, and Compose for declarative UI.

When to Use

  • Creating native Android applications with best practices
  • Using Kotlin for type-safe development
  • Implementing MVVM architecture with Jetpack
  • Building modern UIs with Jetpack Compose
  • Integrating with Android platform APIs

Instructions

1. Models & API Service

// Models
data class User(
  val id: String,
  val name: String,
  val email: String,
  val avatarUrl: String? = null
)

data class Item(
  val id: String,
  val title: String,
  val description: String,
  val imageUrl: String? = null,
  val price: Double
)

// API Service with Retrofit
interface ApiService {
  @GET("/users/{id}")
  suspend fun getUser(@Path("id") userId: String): User

  @PUT("/users/{id}")
  suspend fun updateUser(
    @Path("id") userId: String,
    @Body user: User
  ): User

  @GET("/items")
  suspend fun getItems(@Query("filter") filter: String = "all"): List<Item>

  @POST("/items")
  suspend fun createItem(@Body item: Item): Item
}

// Network client setup
@Module
@InstallIn(SingletonComponent::class)
object NetworkModule {
  @Provides
  @Singleton
  fun provideRetrofit(): Retrofit {
    val httpClient = OkHttpClient.Builder()
      .addInterceptor { chain ->
        val original = chain.request()
        val requestBuilder = original.newBuilder()

        val token = PreferencesManager.getToken()
        if (token.isNotEmpty()) {
          requestBuilder.addHeader("Authorization", "Bearer $token")
        }

        requestBuilder.addHeader("Content-Type", "application/json")
        chain.proceed(requestBuilder.build())
      }
      .connectTimeout(30, TimeUnit.SECONDS)
      .readTimeout(30, TimeUnit.SECONDS)
      .build()

    return Retrofit.Builder()
      .baseUrl("https://api.example.com")
      .client(httpClient)
      .addConverterFactory(GsonConverterFactory.create())
      .build()
  }

  @Provides
  @Singleton
  fun provideApiService(retrofit: Retrofit): ApiService {
    return retrofit.create(ApiService::class.java)
  }
}

2. MVVM ViewModels with Jetpack

@HiltViewModel
class UserViewModel @Inject constructor(
  private val apiService: ApiService
) : ViewModel() {
  private val _user = MutableStateFlow<User?>(null)
  val user: StateFlow<User?> = _user.asStateFlow()

  private val _isLoading = MutableStateFlow(false)
  val isLoading: StateFlow<Boolean> = _isLoading.asStateFlow()

  private val _errorMessage = MutableStateFlow<String?>(null)
  val errorMessage: StateFlow<String?> = _errorMessage.asStateFlow()

  fun fetchUser(userId: String) {
    viewModelScope.launch {
      _isLoading.value = true
      _errorMessage.value = null

      try {
        val user = apiService.getUser(userId)
        _user.value = user
      } catch (e: Exception) {
        _errorMessage.value = e.message ?: "Unknown error"
      } finally {
        _isLoading.value = false
      }
    }
  }

  fun logout() {
    _user.value = null
  }
}

@HiltViewModel
class ItemsViewModel @Inject constructor(
  private val apiService: ApiService
) : ViewModel() {
  private val _items = MutableStateFlow<List<Item>>(emptyList())
  val items: StateFlow<List<Item>> = _items.asStateFlow()

  private val _isLoading = MutableStateFlow(false)
  val isLoading: StateFlow<Boolean> = _isLoading.asStateFlow()

  fun fetchItems(filter: String = "all") {
    viewModelScope.launch {
      _isLoading.value = true
      try {
        val items = apiService.getItems(filter)
        _items.value = items
      } catch (e: Exception) {
        println("Error fetching items: ${e.message}")
      } finally {
        _isLoading.value = false
      }
    }
  }

  fun addItem(item: Item) {
    viewModelScope.launch {
      try {
        val created = apiService.createItem(item)
        _items.value = _items.value + created
      } catch (e: Exception) {
        println("Error creating item: ${e.message}")
      }
    }
  }
}

3. Jetpack Compose UI

@Composable
fun MainScreen() {
  val navController = rememberNavController()

  NavHost(navController = navController, startDestination = "home") {
    composable("home") { HomeScreen(navController) }
    composable("profile") { ProfileScreen(navController) }
    composable("details/{itemId}") { backStackEntry ->
      val itemId = backStackEntry.arguments?.getString("itemId") ?: return@composable
      DetailsScreen(itemId = itemId, navController = navController)
    }
  }
}

@Composable
fun HomeScreen(navController: NavController) {
  val viewModel: ItemsViewModel = hiltViewModel()
  val items by viewModel.items.collectAsState()
  val isLoading by viewModel.isLoading.collectAsState()

  LaunchedEffect(Unit) {
    viewModel.fetchItems()
  }

  Scaffold(
    topBar = { TopAppBar(title = { Text("Items") }) }
  ) { paddingValues ->
    if (isLoading) {
      Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
        CircularProgressIndicator()
      }
    } else {
      LazyColumn(
        modifier = Modifier
          .padding(paddingValues)
          .fillMaxSize(),
        contentPadding = PaddingValues(8.dp)
      ) {
        items(items) { item ->
          ItemCard(
            item = item,
            onClick = { navController.navigate("details/${item.id}") }
          )
        }
      }
    }
  }
}

@Composable
fun ItemCard(item: Item, onClick: () -> Unit) {
  Card(
    modifier = Modifier
      .fillMaxWidth()
      .padding(8.dp)
      .clickable { onClick() }
  ) {
    Row(modifier = Modifier.padding(16.dp)) {
      Column(modifier = Modifier.weight(1f)) {
        Text(text = item.title, style = MaterialTheme.typography.headlineSmall)
        Text(text = item.description, style = MaterialTheme.typography.bodyMedium)
        Text(text = "$${item.price}", style = MaterialTheme.typography.bodySmall)
      }
      Icon(imageVector = Icons.Default.ArrowForward, contentDescription = null)
    }
  }
}

@Composable
fun ProfileScreen(navController: NavController) {
  val viewModel: UserViewModel = hiltViewModel()
  val user by viewModel.user.collectAsState()
  val isLoading by viewModel.isLoading.collectAsState()

  LaunchedEffect(Unit) {
    viewModel.fetchUser("current-user")
  }

  Scaffold(
    topBar = { TopAppBar(title = { Text("Profile") }) }
  ) { paddingValues ->
    if (isLoading) {
      Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
        CircularProgressIndicator()
      }
    } else if (user != null) {
      Column(
        modifier = Modifier
          .padding(paddingValues)
          .fillMaxSize()
          .padding(16.dp)
      ) {
        Text(text = user!!.name, style = MaterialTheme.typography.headlineMedium)
        Text(text = user!!.email, style = MaterialTheme.typography.bodyMedium)

        Spacer(modifier = Modifier.height(24.dp))

        Button(
          onClick = { viewModel.logout() },
          modifier = Modifier.fillMaxWidth()
        ) {
          Text("Logout")
        }
      }
    }
  }
}

@Composable
fun DetailsScreen(itemId: String, navController: NavController) {
  Scaffold(
    topBar = {
      TopAppBar(
        title = { Text("Details") },
        navigationIcon = {
          IconButton(onClick = { navController.popBackStack() }) {
            Icon(Icons.Default.ArrowBack, contentDescription = "Back")
          }
        }
      )
    }
  ) { paddingValues ->
    Column(
      modifier = Modifier
        .padding(paddingValues)
        .fillMaxSize()
        .padding(16.dp),
      horizontalAlignment = Alignment.CenterHorizontally,
      verticalArrangement = Arrangement.Center
    ) {
      Text("Item ID: $itemId", style = MaterialTheme.typography.headlineSmall)
    }
  }
}

Best Practices

✅ DO

  • Use Kotlin for all new Android code
  • Implement MVVM with Jetpack libraries
  • Use Jetpack Compose for UI development
  • Leverage coroutines for async operations
  • Use Room for local data persistence
  • Implement proper error handling
  • Use Hilt for dependency injection
  • Use StateFlow for reactive state
  • Test on multiple device types
  • Follow Android design guidelines

❌ DON'T

  • Store tokens in SharedPreferences
  • Make network calls on main thread
  • Ignore lifecycle management
  • Skip null safety checks
  • Hardcode strings and resources
  • Ignore configuration changes
  • Store passwords in code
  • Deploy without device testing
  • Use deprecated APIs
  • Accumulate memory leaks

Du fichier au premier essai

Le téléchargement contient exactement le contenu affiché sur cette fiche. Cette copie peut différer de la dernière version du dépôt source.

Consulter la source et ses fichiers annexes

Ce téléchargement contient uniquement SKILL.md. Les scripts, références, modèles et dépendances éventuels ne sont pas inclus. Récupérez les fichiers nécessaires depuis la source en conservant leur arborescence avant de poursuivre.

1. Télécharger le fichier

Télécharger SKILL.md

Depuis la racine d’un projet de test, enregistrez le fichier sous .skill-downloads/android-kotlin-development-msba3n0n/SKILL.md, ou utilisez la commande suivante. Ce dossier sert à examiner la skill avant son installation.

Commande pour macOS/Linux ou WSL : un shell POSIX et curl sont nécessaires. Sous Windows sans WSL, utilisez le bouton de téléchargement et créez le dossier manuellement.

mkdir -p '.skill-downloads/android-kotlin-development-msba3n0n' && curl --fail --show-error --location 'https://skills-guides.com/api/skills/android-kotlin-development-msba3n0n/download' --output '.skill-downloads/android-kotlin-development-msba3n0n/SKILL.md.part' && mv '.skill-downloads/android-kotlin-development-msba3n0n/SKILL.md.part' '.skill-downloads/android-kotlin-development-msba3n0n/SKILL.md'

2. Vérifier les prérequis

Lisez SKILL.md avant de l’utiliser. Si le fichier cite des scripts ou services externes, examinez-les et préparez les accès nécessaires dans votre environnement de test.

Aucune section de prérequis reconnue dans ce fichier. Cela ne signifie pas qu’il est autonome : les bibliothèques, outils et accès peuvent être cités ailleurs dans le contenu ou dans le dépôt source.

Les plateformes de la fiche sont des indications du catalogue. Les chemins ci-dessous suivent la documentation des outils ; ils ne prouvent pas que cette skill y a été exécutée. Aucune version minimale de ces outils n’est attestée pour cette fiche.

3. Charger la skill

Après vérification, copiez le dossier complet dans le projet avec l’une des commandes ci-dessous, puis ouvrez une nouvelle session de l’outil. La commande s’arrête si un dossier du même nom existe déjà : comparez les fichiers avant de le remplacer.

Claude Code
test -f '.skill-downloads/android-kotlin-development-msba3n0n/SKILL.md' && test -s '.skill-downloads/android-kotlin-development-msba3n0n/SKILL.md' && mkdir -p '.claude/skills' && test ! -e '.claude/skills/android-kotlin-development' && cp -R '.skill-downloads/android-kotlin-development-msba3n0n' '.claude/skills/android-kotlin-development'

Cursor
test -f '.skill-downloads/android-kotlin-development-msba3n0n/SKILL.md' && test -s '.skill-downloads/android-kotlin-development-msba3n0n/SKILL.md' && mkdir -p '.cursor/skills' && test ! -e '.cursor/skills/android-kotlin-development' && cp -R '.skill-downloads/android-kotlin-development-msba3n0n' '.cursor/skills/android-kotlin-development'

Codex
test -f '.skill-downloads/android-kotlin-development-msba3n0n/SKILL.md' && test -s '.skill-downloads/android-kotlin-development-msba3n0n/SKILL.md' && mkdir -p '.agents/skills' && test ! -e '.agents/skills/android-kotlin-development' && cp -R '.skill-downloads/android-kotlin-development-msba3n0n' '.agents/skills/android-kotlin-development'

OpenSkills

OpenSkills doit déjà être installé. La procédure locale install/read est contrôlée avec OpenSkills 1.5.0, qui exige Node.js ≥ 20.6.0. Aucun slug du catalogue n’est résolu automatiquement.

Installation officielle d’OpenSkills
openskills install './.skill-downloads/android-kotlin-development-msba3n0n'

openskills read 'android-kotlin-development-msba3n0n'

La lecture doit afficher le contenu du fichier installé et son dossier de base. Elle ne lance ni la skill ni ses dépendances.

Pour un agent qui lit AGENTS.md, synchronisez ensuite l’index. Cette commande modifie AGENTS.md : relisez le diff avant de l’utiliser.

openskills sync

Mode manuel ou autre outil : joignez SKILL.md à une conversation, ou ouvrez-le dans un agent capable de lire les fichiers. Ajoutez les ressources annexes nécessaires. Il n’existe pas de dossier universel reconnu par tous les outils.

4. Faire un premier essai

Utilisez une entrée courte et fictive : un endpoint d’API, un petit document ou un brief d’interface. Dans une nouvelle conversation, joignez le fichier ou donnez son chemin à l’agent, puis adaptez cette demande :

Lis .skill-downloads/android-kotlin-development-msba3n0n/SKILL.md et applique ses instructions à cet exemple : [décrire une entrée de test]. Indique les fichiers, dépendances ou accès qui manquent. Produis le résultat demandé par la skill sans inventer de données ni exécuter de script non examiné.

Résultat attendu : une sortie correspondant aux instructions de la skill, ou une liste précise des prérequis manquants. Une simple confirmation de lecture ne valide pas le premier usage. Si une ressource externe est indisponible, ce parcours reste à tester.

Skills similaires