Click here for step 1

Because You write Android apps in the Java programming language make sure you have JDK downloaded on your computer before you download the Android Studio app.

Below are instructions on how to set up and run Android Studio on Windows 11.

Please see the installation guides for MAC, and Linux users at

  1. ↩︎

Install Java Development Kit (JDK)

Install the Java Development Kit (JDK) on your computer– use the link below to download the JDK: Java Downloads | Oracle

System Enviromental Variables

  1. Search for System Environment Variables in the control panel on your computer

2. Select Path under System Variables and then click on New.

3. Click New  and enter the pathway to the Program Files > Java > jdk## > bin.

(Note: your pathway to this bin file in Java might look different depending on where you save it)

4. Then click OK

5. Still in System Environment Variables under User Variables click New

6. For Variable name exactly type in JAVA_HOME

7. For Variable value enter the pathway to Program files > java>jdk21 (not into the bin file)

8. Save all changes.

Install Android Studio

1. Download Android Studio from the link below.

Download Android Studio & App Tools – Android Developers

! Important  – Select Java as a main language during the Android Studio installation process.

2. Installation guides for different1

Common Installation Issues

Duplicate projects

If you see this issue on your laptop, Check out the following resolution strategies.

Solution 1

  1. Close the application and start entirely new project.

Solution 2

  1. Expand the “Gradle” directory.
  2. Open the file “build. gradle.kts  (Module:app)”
  3. Under dependencies{ }, ensure the following lines are included:

4. From there, sync the changes to Gradle

Execution failed

Solution 1

  1. If you are using iCloud. Try to create projects locally on your computer or using Git

Solution 2

  1. Check solution here:

 java – org.gradle.api.tasks.TaskExecutionException: Execution failed for task ‘:app:transformClassesWithDexForDebug’ – Stack Overflow

HAXM not installed

  1. Hower over upper bar to Device Manager

2. Click on Virtual

3. Click on Create Virtual Device

4. Select recommended virtual device. For this tutorial we will be using Pixel_3a_API_34_extension_level_7_x86

5. After you select virtual device click on Install HAXM

Click here for step 2
  1. In the Welcome to Android Studio dialog, click New Project.

2.  Select Basic Activity

3. Give a name to you project such as First Application

4. Make sure the Language is set to Java

5. Leave other defaults for ither fields

6. Click finish

Get Familiar with Android App

If you picked the “Basic Activity” template for your project, Android Studio has set up several files for you. You can check out the arrangement of these files in different ways, and one way is to look at the “Project” view in the Editor.

  • The Project view organizes your files and folders in a way that’s tailored for Android development. It offers a structure that makes it easy to navigate and work efficiently on your project.

    • com.example.myfirstapp
      : This directory holds the Java source code files for your application.
    • com.example.myfirstapp (androidTest): In this folder, you’d place your instrumented tests. These tests run on an Android device and begin with a basic test file.
    • com.example.myfirstapp (test): This directory is intended for your unit tests. Unlike instrumented tests, unit tests don’t require an Android device to run and start with a basic unit test file.
  • Expand the res folder: This folder serves as a repository for all your app resources, encompassing images, layout files, strings, icons, and styling. It includes the following subfolders:
  • drawable: All your app’s images will be stored in this folder.
  • In the layout folder, you’ll find UI layout files for your activities. Presently, your app has one activity with a layout file named activity_main.xml. Additionally, it includes content_main.xml, fragment_first.xml, and fragment_second.xml. These files define the structure and appearance of different parts of your app’s user interface.
  • menu: This folder contains XML files describing any menus in your app.
  • mipmap: This folder contains the launcher icons for your app.
  • navigation: This folder contains the navigation graph, which tells Android Studio how to navigate between different parts of your application.
  • values: This folder contains resources, such as strings and colors, used in your app.

Create your virtual emulator if there is none.

  1. In Android Studio, navigate to Tools > AVD Manager, or click the AVD Manager icon in the toolbar.
  2. Click Create Virtual Device. If you’ve previously created a virtual device, the window displays your existing devices, with the +Create Virtual Device button located at the bottom. The Select Hardware window presents a list of pre-configured hardware device definitions.
  3. Select a device definition, such as Pixel 3, and click Next. The specific device definition doesn’t significantly impact this code lab.
  4. In the System Image dialog, navigate to the Recommended tab and select the latest release. The choice of the latest release is important.
  5. If a Download link is visible next to the latest release, it indicates that the system image is not yet installed. Click the link to initiate the download, and proceed by clicking Next once the download is complete. The duration of this process depends on your internet connection speed
Click here for step 3

Get familiar with the layout

Find and open the layout folder (app > res > layout) on the left side in the Project panel

Note: In your Android app, think of each screen like a page, and these pages are made by little building blocks called fragments. The screen showing “Hello first fragment” is made by a special building block called FirstFragment.

Layouts are created in XML, a type of code. You can design and change your layout by either writing XML code or using an easy-to-use visual editor.

Pallette – is where you can find what assets you want to add to the design (Buttons, Textview, Image

In the “Component Tree,” you can see the assets, such as buttons and TextViews, currently added to the screen. This view illustrates how these components are organized in relation to each other, providing a visual representation of the layout structure.

For example, because we have only 2 assets on the first screen we have in the project, we can see Button_first and textview_first. Because we have only two assets

In the center is the Design editor (3), which shows a visual representation of what the contents of the file will look like when compiled into an Android app. You can view the visual representation, the XML code, or both.

In  the upper right corner of the Design editor, above Attributes (4), find the three icons that look like this: 

These represent Code (code only), Split (code + design), and Design (design only) views.

Try selecting the different modes. Depending on your screen size and work style, you may prefer switching between Code and Design, or staying in Split view.

If your Component Tree disappears, hide and show the Palette.

Practice using the layout menu in the top left of the design toolbar to display the design view, the blueprint view, and both views side by side

Explore and resize the Component Tree

In fragment_first.xml, look at the Component Tree. If it’s not showing, switch from Split screen mode to Design. Click on Component Tree bottom left corner of the screen.

In the Component Tree, notice that the root of the view hierarchy is a ConstraintLayout view.

Explore both code layout

To see code, still in fragment_first.xml switch to Code or Split view using the icons in the upper right corner.

In the XML code, notice that the root element is <androidx.constraintlayout.widget.ConstraintLayout>. The root element contains a <TextView> element and a <Button> element.

Change Property Value

  1. In the code editor, examine the properties in the TextView element.

2. Click on the string in the text property, and you’ll notice it refers to a string resource, “@string/lorem_ipsum”

3. Right-click on the property and click Go To > Declaration

4. It will open values/strings.xml file with the string highlighted

5. Delete the long text.

6. Change the value of the string property to Hello World!.

7. Change string name to hello_first_fragment.

8. Switch back to fragment_first.xml

9. Since we changed the name of the string we need to change first_fragmnet.xml as well

10. When you type in @string in Android Studio, it will provide suggestions. Among them, you will find hello_first_fragment. This is a reference to a string resource named hello_first_fragment defined in your project’s resources.

  11. Go to Design view and go to Components; you will find the textview name has been changed to hello_first_fragment.

In the text field of the TextView in Attributes, notice it still refers to the string resource @string/hello_first_fragment. Having the strings in a resource file has several advantages. You can change the value of string without having to change any other code. This simplifies translating your app to other languages, because your translators don’t have to know anything about the app code.

Run the app to see the change you made in strings.xml. Your app now shows “Hello World!”.

Change text display properties

When you click on textview_first in the Component Tree, it will display the correct Attribute panel specific to the TextView assets. Similarly, if you click on button_next in the Component Tree, it will bring up an Attribute panel in the top left of the screen, but it will be specific to Button_first. Each element in the Component Tree has its own designated Attribute panel tailored to its properties and settings.

  1. In the layout editor, in the list of attributes, under Common Attributes, and expand the text appearance field. 

2. Change some of the text appearance properties. For example, change the font family, increase the text size, and select bold style.

3. Change the text color. Click in the textColor field, and enter g.

A menu pops up with possible completion values containing the letter g. This list includes predefined colors.

4. Select @android:color/white and press Enter.

5. Go wild, make changes you want to. (rotate, change colors, etc)

6. Look at the XML for the TextView. You see that the new properties have been added.

7. Run your app again and see the changes applied to your Hello World! string

Click here for step 4

Add color resources

  1. In the Project panel on the left, double-click on res > values > colors.xml to open the color resource file.

2. The colors.xml file opens in the editor, where three colors are already defined, visible in your app layout

3. Go back to fragment_first.xml to view the XML code for the layout.

4. Inside the TextView code, add a new property called android:background, and start typing its value as @color.

5. A menu will appear, offering predefined color resources:

Add a new color to use as the screen background color

  1. Back in colors.xml, Add a new color resource in colors.xml for the screen background.

<color name=”screenbackground”>EF44A7</color>

2. Go back to fragment_first.xml.

3. In the Component Tree, select the ConstraintLayout. 

4. In the Attributes panel, select the background property and press Enter.(if you do not see, use search feature) Type “c” in the field that appears.

5. In the menu of colors that appears, select @color/screenBackground. Press Enter to complete the selection.

6. If you are not satisfied with the color or don’t know the hex number, go to Attributes, Background, and click on Custom. Make any additional adjustments as needed.

Add/Remove Constraints

To make the background match the whole screen and adjust the Next button placement, then adjsut texview_first placement:

Adjust the Next button

  1. Go to Component Tree and select button_next

2. Then Attributes for button_next will appear on the left

3. Go to Layout and Constrained Widget

4. The square represents the selected view. Each of the grey dots represents a constraint, to the top, bottom, left, and right; You can click on them to delete or to add constraints

5. Play Around with the constraint value by adding or subtracting values by typing into the 4 sides of the box and see how the position of the next button changes in the blueprint screen of the android

6. In fragment_first.xml, select the button_next in the Component Tree.

7. Look for any jagged lines in the Layout Editor connecting the Next button to other elements.

8. Click on the jagged lines to select them.

9. Press the Delete key on your keyboard to remove these jagged constraints.

By doing this, you ensure that the Next button is not constrained in a way that would place it on top of the TextView.

10. Once constraint is removed bring (drag and drop) next button to below the texview.

11. Open fragment_first.xml in Android Studio  and find and select the button_next in the Design view

12. Locate the small circle at the top of the button_next (representing its top edge).

13. Click on this top circle and drag a line down to the bottom circle of textview_first (representing the bottom edge of the TextView).

By doing this, you’re creating a vertical constraint, connecting the top of the Next button to the bottom of the TextView. Adjust the line for proper alignment.

See below

         14. You may see a warning, “Not Horizontally Constrained“. To fix this, add a constraint from the left side of the button to the left side of the screen.

Adjust the Textview_first element

Since our background is currently set to wrap around textview_first, but we want it to match the size of the screen, follow these steps:

  1. Navigate to Attributes panel > Constraint Widget that belongs to textview_first.

2. Set the top constraint to 180 and the bottom constraint to 420, or adjust the values as needed to best fit the screen.

3. By doing this, you’re specifying constraints for textview_first that will help the background match the size of the screen. Modify the values until you achieve the desired appearance.

4. This is how the updated Constraint Widget looks like this

5. Run the app to check changes

Click here for step 5
  1. Locate the Palette window in the top-left corner of the screen within fragment_first.

2. Click on different categories in the Palette and scroll through the items to explore available options.

3. Find and select “Button,” typically positioned near the top of the Palette.

4. Drag the (ONE) Button and drop it onto the design view, positioning it underneath the TextView and close to the other button.

Add a constraint to the new button

  1. Hover your cursor over the circle at the top of the Button.

2. Click and drag the circle at the top of the Button to the circle at the bottom of the TextView.

3. If you see a warning like “Not Horizontally Constrained,” add a constraint from the left side of the Button to the left side of the screen.

4. Additionally, add a constraint to link the bottom of the Button to the bottom of the screen.

5. Following these steps will help you create the necessary constraints for the Button, ensuring proper alignment in your design.

Adjust the Next button

  1. Move the next button to the left side of the screen. You can manually drag and drop.

2. Change String Resources for New Button

3. In the fragment_first.xml layout file, notice additional code lines appeared for the new button.

Notice that the text "Button" is directly in the layout field, instead of referencing a string resource as the TextView does. This will make it harder to translate your app to other languages.

4. To fix this, click the highlighted code. A light bulb appears on the left.

5. In the dialog box that appears, change the resource name to toast_button_text and the resource value to Toast and click OK.

6. Go to the res > values > strings.xml file. Notice that a new string resource has been added, named toast_button_text.

7. Run the app to make sure it displays as you expect it to.

Update the Next button

The Next button already has its text in a string resource, but you’ll make some changes to the button to match its new role, which will be to generate and display a random number.

  1. As you did for the Toast button, change the id of the Next button from button_first to random_button in the Attributes panel.

2. If you get a dialog box asking to update all usages of the button, click Yes. This will fix any other references to the button in the project code.

3. In strings.xml, right-click on the next string resource.

4. Select Refactor > Rename… and change the name to random_button_text.

5. Click Refactor to rename your string and close the dialog.

6. Change the value of the string from  >Next> to >Random<

Add a third button

  1. In the Attributes panel, change the id of the Next button from button_first to random_button.

2. f asked to update all usages, click “Yes” to fix other references in the project code.

3. In strings.xml, right-click on the next string resource.

4. Choose “Refactor > Rename…” and rename it to random_button_text.

5. Click “Refactor” to apply the changes.

6. Modify the string value from “>Next>” to “>Random<“.

Following these steps ensures the Next button is adjusted for its new role of generating and displaying a random number.

The buttons should now have the following text and id~s:

Buttontextid
Left buttonToast@+id/toast_button
Middle buttonCount@+id/count_button
Right buttonRandom@+id/random_button

Update the appearance of your app to your taste

You can add new color resources

  1. Add a new color named buttonBackground. Use the value #4B4E5E, which is pink color

<color name=”buttonBackground”>#4B4E5E </color>

2. In the layout, add a background color to each of the buttons. (You can either edit the XML in fragment_first.xml or use the Attributes panel, whichever you prefer.)

Update the appearance of the TextView

  1. Remove the background color of the TextView, either by clearing the value in the Attributes panel or by removing the android:background attribute from the XML code

2. When you remove the background, the view background becomes transparent.

3. Change the rotation of the TextView to to normal (if it’s not already).

4. Change the value of the TextView_first to show 0 (the number zero).

Click here for step 6

You have added buttons to your app’s main screen, but currently the buttons do nothing. In this task, you will make your buttons respond when the user presses them.

Enable auto imports

  1. In Android Studio, open the settings editor by going to File > Settings > Editor > General.

2. Select Auto Imports. In the Java section, ensure that “Add Unambiguous Imports on the fly” is checked.

Toast Button

Task: In this step, you will attach a Java method to the Toast button to show a toast when the user presses the button. A toast is a short message that appears briefly at the bottom of the screen.

  1. Open FirstFragment.java (app > java > com.example.android.myfirstapp > FirstFragment).

Note: do not confuse FirstFragment.java with fragment_first.xml

2. This class has only two methods, onCreateView() and onViewCreated(). These methods execute when the fragment starts.

3. As mentioned earlier, the id for a view helps you identify that view distinctly from other views. Using the findViewByID() method, your code can find the random_button using its id, R.id.random_button

4. Use the findViewById() method to locate a view by its id. For instance, find the random_button using:

Button randomButton = getView().findViewById(R.id.random_button);

5. Set a click listener on the view. For example, for the random_button:

6. Attach a listener that performs an action when the button is clicked (navigation, for instance).

7. Just below, set up a click listener for the toast_button:

8. Find the toast_button using findViewById().

9. Attach a listener to create and display a toast when the button is clicked.

By following these steps, you’ll set up click listeners for the random_button and toast_button. Adjust as needed for your specific requirements.

Here is the code:

view.findViewById(R.id.toast_button).setOnClickListener(new View.OnClickListener() {
   @Override
   public void onClick(View view) {
       Toast myToast = Toast.makeText(getActivity(), "Hello toast!", Toast.LENGTH_SHORT);
       myToast.show();
   }
});

10. Add the code inside the onViewCreated

11. Run the app and press the Toast button. Do you see the toasty message at the bottom of the screen?

Count Button

Task: Update the Count button so that when it is pressed, the number on the screen increases by 1.

  1. In FirstFragment.java, add a click listener for the count_button below the other click listeners in onViewCreated().

2. Because it has a little more work to do, have it call a new method, countMe().

view.findViewById(R.id.count_button).setOnClickListener(new View.OnClickListener() {
   @Override
   public void onClick(View view) {
       countMe(view);
   }
});

3. In the FirstFragment class, add the method countMe() that takes a single View argument. This method will be invoked when the Count button is clicked and the click listener called.

private void countMe(View view) {
}

4. Get the value of the showCountTextView. You will define that in the next step.

 ...
    // Get the value of the text view
    String countString = showCountTextView.getText().toString();

5. Convert the value to a number, and increment it.

...
    // Convert value to a number and increment it
    Integer count = Integer.parseInt(countString);
    count++;

6. Display the new value in the TextView_first by programmatically setting the text property of the 

...
   // Display the new value in the text view.
   showCountTextView.setText(count.toString());

Here is the whole method:

private void countMe(View view) {
   // Get the value of the text view
   String countString = showCountTextView.getText().toString();
   // Convert value to a number and increment it
   Integer count = Integer.parseInt(countString);
   count++;
   // Display the new value in the text view.
   showCountTextView.setText(count.toString());
}

Cache the TextView for repeated use

Instead of calling findViewById() in every click of the button, you can improve performance by finding the view once and saving it for later use. This is more efficient than repeatedly calling the relatively time-consuming findViewById() method.

  1. In the FirstFragment class before any methods, add a member variable for showCountTextView of type TextView.

TextView showCountTextView;

2. In onCreateView(), you will call findViewById() to get the TextView that shows the count. The findViewById() method must be called on a View where the search for the requested ID should start, so assign the layout view that is currently returned to a new variable, fragmentFirstLayout, instead.

// Inflate the layout for this fragment

View fragmentFirstLayout = inflater.inflate(R.layout.fragment_first, container, false)

3. Call findViewById() on fragmentFirstLayout, and specify the id of the view to find, textview_first. Cache that value in showCountTextView.

...
    // Get the count text view
    showCountTextView = fragmentFirstLayout.findViewById(R.id.textview_first

4. Return fragmentFirstLayout from onCreateView().

return fragmentFirstLayout;

Here is the whole method and the declaration of showCountTextView:

TextView showCountTextView;

@Override
public View onCreateView(
       LayoutInflater inflater, ViewGroup container,
       Bundle savedInstanceState
) {
   // Inflate the layout for this fragment
   View fragmentFirstLayout = inflater.inflate(R.layout.fragment_first, container, false);
   // Get the count text view
   showCountTextView = fragmentFirstLayout.findViewById(R.id.textview_first);

   return fragmentFirstLayout;
}

5. Run your app. Press the Count button and watch the count update.

Click here for step 7

Until now, you’ve worked on the initial screen of your app. Next, you’ll enhance the Random button to show a random number between 0 and the current count on a second screen.

Add a TextView for the random number

  1. Open fragment_second.xml (app > res > layout > fragment_second.xml) and switch to Design View if needed.

Notice that it has a ConstraintLayout that contains a TextView and a Button.

Add second textview box

  1. Add TextView from the palette and drop it near the middle of the screen. This TextView will be used to display a random number between 0 and the current count from the first Fragment.

2. Set the id to @+id/textview_random (textview_random in the Attributes panel.)

3. Constrain the top edge of the new TextView to the bottom of the first TextView, the left edge to the left of the screen, and the right edge to the right of the screen, and the bottom to the top of the Previous button.

4. Set both width and height to wrap_content.

5. Set the textColor to @android:color/white, set the textSize to 72sp, and the textStyle to bold.

6. If you get a warning “Not Horizontally Constrained,” add a constraint from the start of the button to the left side of the screen and the end of the button to the right side of the screen.

Here is the XML code for the TextView that displays the random number:

Update the old TextView  box to display the header

  1. Change the id to textview_header in the Attributes panel.

2. Set the width to match_constraint, but set the height to wrap_content, so the height will change as needed to match the height of the content.

3. Set top, left and right margins to 24dp. Left and right margins may also be referred to as “start” and “end” to support localization for right to left languages.

4. Remove any bottom constraint.

5. In strings.xml, change hello_second_fragment to “Here is a random number between 0 and %d.”

6. Use Refactor > Rename… to change the name of hello_second_fragment to random_heading.

7. Change Background Color (you will be able to change in XML or in Attributes panne in second_fragment.xml

Examine the navigation graph

Open nav_graph.xml (app > res > navigation > nav_graph.xml).

In the navigation editor, you have the flexibility to rearrange elements. For instance, if the fragments are displayed with SecondFragment to the left, drag FirstFragment to the left of SecondFragment to arrange them in the order that matches your workflow.

Enable SafeArgs

  1. Open Gradle Scripts > build.gradle (Project: My First App)

2. In build.grdile (Myapplication file) add the highlighted code

buildscript {
repositories {
google()
}
dependencies {
val nav_version = "2.7.6"
classpath("androidx.navigation:navigation-safe-args-gradle-plugin:$nav_version")

}
}

3. Add the code below to the build.gradile (Module app file ) in plugins

id(“androidx.navigation.safeargs”)

Create the argument for the navigation action.

  1. In the navigation graph, click on FirstFragment, and look at the Attributes panel to the right. (If the panel isn’t showing, click on the vertical Attributes label to the right.)

2. In the Actions section, it shows what action will happen for navigation, namely going to SecondFragment.

3. Click on SecondFragment, and look at the Attributes panel.

4. The Arguments section shows Nothing to show.

5. Click on the + in the Arguments section.

6. In the Add Argument dialog, enter myArg for the name and set the type to Integer, then click the Add button.

Send the count to the second fragment

  1. Open FirstFragment.java (app > java > com.example.myfirstapp > FirstFragment)

2. Find the method onViewCreated() and notice the code that sets up the click listener to go from the first fragment to the second.

3. Replace the code in that click listener with a line to find the count text view, textview_first

int currentCount = Integer.parseInt(showCountTextView.getText().toString());

4. Create an action with currentCount as the argument to actionFirstFragmentToSecondFragment().

FirstFragmentDirections.ActionFirstFragmentToSecondFragment action = FirstFragmentDirections.actionFirstFragmentToSecondFragment(currentCount);

5. Add a line to find the nav controller and navigate with the action you created.

NavHostFragment.findNavController(FirstFragment.this).navigate(action);

6. Here is the whole method, including the code you added earlier:

public void onViewCreated(@NonNull View view, Bundle savedInstanceState) {
   super.onViewCreated(view, savedInstanceState);

   view.findViewById(R.id.random_button).setOnClickListener(new View.OnClickListener() {
       @Override
       public void onClick(View view) {
           int currentCount = Integer.parseInt(showCountTextView.getText().toString());
           FirstFragmentDirections.ActionFirstFragmentToSecondFragment action = FirstFragmentDirections.actionFirstFragmentToSecondFragment(currentCount);
           NavHostFragment.findNavController(FirstFragment.this).navigate(action);
       }
   });

   view.findViewById(R.id.toast_button).setOnClickListener(new View.OnClickListener() {
       @Override
       public void onClick(View view) {
           Toast myToast = Toast.makeText(getActivity(), "Hello toast!", Toast.LENGTH_SHORT);
           myToast.show();
       }
   });

   view.findViewById(R.id.count_button).setOnClickListener(new View.OnClickListener() {
       @Override
       public void onClick(View view) {
           countMe(view);
       }
   });
}

Update SecondFragment to compute and display a random number

  1. In SecondFragment.java, in the onViewCreated() method below the line that starts with super, add code to get the current count, get the string and format it with the count, and then set it for textview_header.

Integer count = SecondFragmentArgs.fromBundle(getArguments()).getMyArg();
String countText = getString(R.string.random_heading, count);
TextView headerView = view.getRootView().findViewById(R.id.textview_header);
headerView.setText(countText);

2. Get a random number between 0 and the count.

Random random = new java.util.Random();
Integer randomNumber = 0;
if (count > 0) {
   randomNumber = random.nextInt(count + 1);
}

3. Add code to convert that number into a string and set it as the text for textview_random

TextView randomView = view.getRootView().findViewById(R.id.textview_random);
randomView.setText(randomNumber.toString());

4. Run the app. Press the Count button a few times, then press the Random button.