# Building an Android App

As technology and styles of work evolve, the need for apps to support mobile is as important as ever. In 2023, Android had around 70% market share, so the need for developers to understand how to develop apps for Android is vital.

In this tutorial, you will learn the basics of getting started with your first Android app, using the programming language Kotlin. Although historically, native Android apps have been written in Java, Kotlin was upgraded to the official language for Android by Google in 2019.

## Prerequisites
In order to follow along with this tutorial, you will need to have downloaded and installed Android Studio. This is the official IDE for Android development and comes with all the tools you will need to get started. Windows, MacOS, and Linux support it, as well.

> You won’t need an Android device to run your apps, thanks to the use of the Android Emulator, which comes with Android Studio. You will be guided through setup when you first open up Android Studio.

## Creating the project
The first step is to create the application. You can do this from the “Welcome to Android Studio” page that appears when you open Android Studio for the first time.

> If you have opened it before and don’t see this window but instead a list of recent projects, you can create a new project from the **File** menu.

 1. Click **New Project**, which starts a wizard to guide you through
    creating a new project.
2. In the **Templates** window, make sure the **Phone and Tablet** option is selected on the left. Select Empty Activity and then click
    Next.

3. Give your project a name. I chose "Hello Android".    

For Package name, this can be left as the default, if you want. In the future, you might update it to reflect your company name, making sure to leave the app name on the end. I know the backward nature of the Package name can seem confusing but it is just something to note, if you update it.

Minimum SDK: If you make an app in the future intended for users, you might choose an earlier version of Android to support more devices, but this isn’t necessary for this tutorial, so update it to a newer version. I went with API 33, aka “Tiramisu.” Android gives all their operating system (OS) versions names shared with sweet things, all in alphabetical order.

> Fun fact: I created my first ever Android app back when the OS version was nicknamed Jelly Bean!

You can leave the other values as default, although you may choose to update the **Save** location. Once done, press the **Finish** button.

It will then open your new application inside the main Android Studio window. It can take a minute or two to index and build everything, so if you don’t see much straight away, don’t worry. Once completed, you will see the ```MainActivity.kt``` file open in the editor and the project structure on the left.

## Running the app for the first time
Although we haven’t made any code changes yet, the Empty Activity template comes with a basic UI already. So let’s run our app and see what it looks like out of the box.

 1. Select the **Run** button that looks like a play button at the top of the Android Studio window. Or you can select the hamburger menu in the top left and go to **Run -> Run ‘app’**.
 2. Once it has been built and deployed, you will see it running in the Running Devices area to the right of the editor window. Out of the box, it just says “Hello Android.”

Congratulations! You have your first running native Android app!

## Updating the UI
Now your app is running, let’s take a look at how to make some changes to the UI.
Android supports two types of UI: XML-based layouts and Jetpack Compose, known as Compose. Compose is now the recommended solution for Android, and this is what our new app is using, so we will continue to use it.

Compose uses composable functions to define UI components. You can see this in action in the I’m code inside ```MainActivity.kt``` where there is a function called ```Greeting``` with the attribute ```@Composable```. It takes in a string for a name and modifier and uses those inside a text element.

We are going to update the greeting function to now include a way to enter some text and a button to click that will update the label to say “Hello” to the name you enter in the text box.

Replace the existing code from ```class MainActivity : ComponentActivity() {``` onward with the following:
```kotlin
class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            HelloAndroidTheme {
                // A surface container using the 'background' color from the theme
                Surface(
                    modifier = Modifier.fillMaxSize(),
                    color = MaterialTheme.colorScheme.background
                ) {
                    Greeting()
                }
            }
        }
    }
}

@Composable
fun Greeting() {

    var message by remember { mutableStateOf("")}
    var greeting by remember { mutableStateOf("") }

    Column (Modifier.padding(16.dp)) {
        TextField(
            value = message,
            onValueChange = { message = it },
            label = {Text("Enter your name..")}
        )
        Button(onClick = { greeting = "Hello, $message" }) {
            Text("Say Hello")
        }
       Text(greeting)
    }

}

@Preview(showBackground = true)
@Composable
fun GreetingPreview() {
    HelloAndroidTheme {
        Greeting()
    }
}

```

Let’s now take a look at what has changed.
### OnCreate

We have removed the passing of a hardcoded name value here as a parameter to the Greeting function, as we will now get that from the text box.

### Greeting
 We have added two function-scoped variables here for holding the values we want to update dynamically. 

We then start defining our components. Now we have multiple components visible, we want to apply some layout and styling to them, so we have created a column so the three sub-components appear vertically. Inside the column definition, we also pass padding of 16dp.

Our column layout contains a TextField for entering text. The value property is linked to our message variable. The onValueChanged property says that when the value of the box is changed, assign it to the message variable so it is always up to date. It also has a label property, which acts as a placeholder hint to the user.

Next is the button. This has an onClick property where we define what happens when the button is clicked. In this case, it sets the value of the greeting variable to be “Hello,” plus the message.

Lastly, we have a text component to display the greeting. Each time the button is clicked and the greeting variable is updated, that text field will update on the screen.

### GreetingPreview

This is a function that allows you to preview your UI without running it on a device or emulator. It is very similar to the OnCreate function above where it specifies the default HelloAndroidTheme and then our Greeting component.

If you want to view the preview of your code, you can click the button in the top right corner of the editor window, to the left of the **Running Devices** area that shows a hamburger icon with a rectangle with rounded corners next to it. This is the split view button. It splits the view between your code and the preview.

### Imports
If Android Studio is giving you error messages in the code, it might be because you are missing some import statements at the top of the file.

Expand the imports section at the top and replace it with the following:

```kotlin
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Button
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextField
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.input.TextFieldValue
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.mongodb.helloandroid.ui.theme.HelloAndroidTheme
```
You will need to update the last import statement to make sure that your package name matches as it may not be com.mongodb.helloandroid, for example.

## Testing the app

Now that we have updated the UI, let’s run it and see our shiny new UI. Click the **Run** button again and wait for it to deploy to the emulator or your device, if you have one connected.

Try playing around with what you enter and pressing the button to see the result of your great work!

## Summary
There you have it, your first Android app written in Kotlin using Android Studio, just like that! Compose makes it super easy to create UIs in no time at all.

If you want to take it further, you might want to add the ability to store information that persists between app sessions. MongoDB has an amazing product, called Atlas Device Sync, that allows you to store data on the device for your app and have it sync to MongoDB Atlas. You can read more about this and how to get started in our Kotlin Docs.