Initial Movies UI

Create data

Now we create some fake data to display Movies in the app. After we talk about databases, we'll convert the data into something real (and add Actors and Ratings).

Create a Movie class. For now we just hold a title and description, but we'll add more when we create our database.

Next, we create a MovieViewModel to hold a list of movies. View models prepare and provide data for our user interface to consume. Here we hardcode the data, but we'll change that in the database module.

Finally, we connect the view model to the MainActivity. Using the viewModels function creates a property delegate that will create an instance of the specified view model (if it doesn't exist), or fetch an existing one for the activity. This allows us to keep data across configuration changes, when the activity is destroyed and recreated.

Code Changes

CHANGED: /app/src/main/java/com/androidbyexample/movieui1/MainActivity.kt
package com.androidbyexample.movieui1

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.viewModelsimport androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import com.androidbyexample.movieui1.ui.theme.MovieUi1Theme

class MainActivity : ComponentActivity() {
private val viewModel by viewModels<MovieViewModel>()
override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { MovieUi1Theme { // A surface container using the 'background' color from the theme Surface( modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background ) { Greeting("Android") } } } } } @Composable fun Greeting(name: String, modifier: Modifier = Modifier) { Text( text = "Hello $name!", modifier = modifier ) } @Preview(showBackground = true) @Composable fun GreetingPreview() { MovieUi1Theme { Greeting("Android") } }
ADDED: /app/src/main/java/com/androidbyexample/movieui1/Movie.kt
package com.androidbyexample.movieui1
data class Movie( val title: String, val description: String,)
ADDED: /app/src/main/java/com/androidbyexample/movieui1/MovieViewModel.kt
package com.androidbyexample.movieui1import androidx.lifecycle.ViewModel
class MovieViewModel: ViewModel() { val movies: List<Movie> = listOf( Movie("The Transporter", "Jason Statham kicks a guy in the face"), Movie("Transporter 2", "Jason Statham kicks a bunch of guys in the face"), Movie("Hobbs and Shaw", "Cars, Explosions and Stuff"), Movie("Jumanji - Welcome to the Jungle", "The Rock smolders"), )}