Building Your First App with Android Studio 2.0

Hints for using the first two Android training guides with Android Studio 2.0 and suggestions for extending your first app to programmatically check locale, use log statements, use screen orientation to test different layouts, and create a quick run-time build-version test using the Snackbar message.

Introduction

As the title suggests, this article is for developers who are new to the Android development platform. You need some knowledge of markup languages, but don’t have to be an expert in XML. It’s great if you know  Java, but as long as you’re familiar with other programming languages, you can build an Android application. Of course, you also need Android Studio 2.0 and the latest SDK.

The Internet has no shortage of resources for beginning Android developers, but I like the training guides on the Android developer website because they are thorough and let you jump right in and start coding. There are eight Getting Started guides, beginning with Building Your First App and including guides for supporting different devices, building a dynamic UI,  and using system permissions. (More experienced developers may like the 19 advanced educational categories, including writing for wearables and best practices for performance and security.)

The Building Your First App training guide contains a few elements that differ from what you see in Android Studio 2.0. Also, the next guide, Supporting Different Devices, left me wanting to do more. This article provides hints, suggestions, and resources to extend the first two training guides and help you make the most out of your first Android app.


Part 1: Hints for Building Your First App

In this guide, you first create an Android Studio project and run the initial “Hello World” application. Next, you build a simple user interface, and finally, make and call a second activity. Along the way, you also create and run virtual devices using the Android Virtual Device (AVD) Manager.

The following hints and resources should speed your progress and help keep you on a productive path.

Add Basic Activity not Blank Activity

In the Creating an Android Project lesson, step 6 says to Add an activity to <template> and select Blank Activity. As you can see from Figure 1, Blank Activity is not an option. The correct choice for this lesson is Basic Activity. If you instead add an Empty Activity, your file structure won’t match the rest of the instructions.

Figure 1

Design view allows drag-and-drop

Although the training guide uses the layout editor’s Text view to edit layout files, you can switch to Design view by clicking the Design button at the bottom of the window. The Design view allows you to drag elements, such as linear layouts and buttons, and drop them into your layout.

Margin tabs reveal additional panes

Several functions in Android Studio 2.0 are activated using tabs (Figure 2). For example, when you’re viewing a layout file, the Preview tab shows a visual view. Other tabs reveal the Project pane, Android Monitor, and more. Clicking a tab toggles the pane on and off, or you can click on the icon (arrow pointing to a closed pane) to hide the panes.

Figure 2

What to do about “possible NPE” warnings

When you review your Java code in Creating an Android Project, you’ll see sections highlighted in a light amber color. A warning pops up when you hover, indicating the code may produce java.lang.NullPointerException (NPE). The lint tool produces these warnings, which are designed to reduce structural issues in your code. If you are relatively new to programming, you may wonder if you need to fix this type of warning. Although the answer seems to be a matter of opinion, for creating your first app you can ignore possible NPE warnings that don’t produce an error.

UPDATE: I discovered an easy way to handle NPE exceptions and other errors. Hover over your error and click Alt+Enter to bring up a menu of choices. For NPE exceptions you can either Assert ‘fab != null’ or surround the code with ‘if (fab != null)’ to handle the exception.

Figure 2.5b

Instant Run is only for API levels 15 and higher

Instant Run updates your running application quickly, sometimes without even restarting. However, if you are developing on a device running API 14 or lower, Instant Run is not available. Instant Run is indicated by a yellow thunderbolt in front of the run icon and is visible only when a compatible device or emulator is connected.

What if the Run command is not working?

If clicking the Run icon doesn’t bring up the Select Deployment Target window, check to make sure your Run/Debug configuration is set to app.

It’s now easier to select your device

Choosing a device in Android Studio 2.0 is even easier than described in the training guide. A single window (Figure 3) provides access to connected devices as well as available emulators, or you can create a new emulator on-the-fly.

Figure 3


Part 2: Hints and Code Samples for Supporting Different Devices

The next Getting Started guide is called Supporting Different Devices. In this guide, you learn how to modify your app to support different languages, screens, and platform versions using layouts and values resources.

Here are some hints and resources to help you expand your first application.

How to create new resource subdirectories

Although I primarily use the Android view, I recommend using the Project view when creating new resource subdirectories. (Use the pull-down menu at the top of the Project pane to switch views.) The Project view shows the file directory structure and makes it easier to see the directories you create.

To create a new subdirectory, right-click on any of the app directories in Project view and select New followed by Android resource directory. When the New Resource Directory window opens (Figure 4), choose the Resource type (e.g., values for different languages or layouts for different screens). Next, choose one or more Available qualifiers that describe the resource, such as locale/language, screen dimensions, or orientation.  (You can also open the new resource window using the File menu, after clicking on one of the app directories.)

Figure 4

Where is my new resource subdirectory?

The new resource subdirectory is visible immediately in the Project view. However, it is not visible in the Android view until you add at least one resource file. (The Android view groups your files into useful categories, and until there is something to group, the new directory is hidden.) As soon as you add a resource file (e.g., strings.xml) both the directory and file become visible in the Android view.

How can I check a different locale?

You’ve added a string.xml file for a different language, but does it work? Changing the locale programmatically is not recommended for production applications, but it’s an interesting exercise for your first app.

To test a different locale, insert the code in Table 1 at the beginning of your MyActivity.java OnCreate method (using a locale defined in your project). Run your app. You should see translated versions of your app_name, edit_message, and other strings corresponding to the new locale.

Note the use of the setTitle method in the test code. Although other elements change, the app_name remains in English unless you manually reset it.

Table 1. Programmatically Testing Different Locales
@Override
protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);

  // Test changing locale

  Log.i(TAG, "Before Locale = " + getResources().getConfiguration().locale);

  Locale locale = new Locale("de");
  Locale.setDefault(locale);
  Configuration config = new Configuration();
  config.locale = locale;
  getBaseContext().getResources().updateConfiguration(config,
          getBaseContext().getResources().getDisplayMetrics());

  //Refresh the app title
  setTitle(R.string.app_name);

  Log.i(TAG, "After Locale = " +   getResources().getConfiguration().locale);

  // End test code

  setContentView(R.layout.activity_my);
  Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
  setSupportActionBar(toolbar);
Locale-changing test code excerpted from StackOverflow.

Use Log statements to debug code

In the above code sample, I used two log statements that are output to the LogCat tool. (If LogCat isn’t visible, click the Android Monitor tab.) I used an information type (i) log statement, but other options are available, including warnings (w) and errors (e).

The first string in the log statement is the tag, which is limited to 23 characters. (The Android developer website recommends using a constant for log tags.) Use the tag to filter messages when you view them in LogCat. You can also select specific message types using the LogCat drop-down menu.

The second string in the log statement is your message. The message can contain both strings and code. For example, I added getResources().getConfiguration().locale to return the current locale. I used log statements to determine the correct test code location needed for my application to open with the desired language.

Use orientation to test different screen layouts

Because orientation is a different screen layout, creating a separate landscape or portrait layout is a quick way to practice making your first app work with different screens.

First, open the New Resource Directory window, then select the Orientation qualifier, and choose Landscape. After creating the new directory, add a copy of your content_my.xml file, keeping the name the same. (Just like with different string.xml files for different languages, you have multiple layout files — each in a separate directory with a different set of qualifiers.)

Next, modify content_my.xml in the layout-land folder (or modify content_my.xml (land), if using the Android view). Your change can be as simple as adding a TextView element that says “Landscape” or adding an image. (These changes will only be displayed when your phone—or emulator—is in landscape mode.)

Finally, run your app, change the orientation, and verify that your new screen is selected.

Using more complex layout configurations

When you create a new resource directory, Android Studio 2.0 appends as many qualifiers as you choose to the directory name. For example, selecting both X-High Density and Landscape creates a new resource directory called layout-land-xhdpi. Any layout changes in this directory display only on devices that are approximately 320dpi or higher and are in landscape orientation. You can run your app on one of the ldpi, mdpi, or hdpi emulators in landscape orientation to verify it uses the default and not the xhdpi layout.

Adding bitmaps

Add a bitmap to your project by right-clicking on the resource directory and selecting New/Image Asset. In the Configure Image Asset window, choose Action Bar and Tab Icons from the drop-down menu and enter a name for your image. (Your name must use all lowercase alphanumeric characters or underscores.)

Next, choose the Clipart Asset Type, then click the Clipart icon to select an image, and finally change the Trim, Padding, or Theme as desired. Notice Android Studio creates four versions of your image, corresponding to the four standard densities: mdpi, hdpi, xhdpi, and xxhdpi. Click Next and Finish to add your image to the drawables directory.

As a test, add an ImageView widget to one of your layouts, and use the android:src property to reference your Clipart asset. Change the layout width and height properties, as necessary. (If you add an Image type asset and the image is too small, try adding the android:scaleType property, set the value to fitXY, and then change the layout width and height values until the image is the size you want.)

Figure 5

Does my app use the Android Support Library?

The Supporting Different Platform Versions lesson recommends using the Android Support Library (actually several libraries) to provide the most functionality over a wide variety of Android versions. How do you know if your project is using these support libraries? One way is to check the import statements in your Java files. Statements that begin with import android.support refer to a support library. The Android Studio 2.0 Basic Activity uses two support libraries: the Design Support library and the v7 AppCompat library.

Another place to check your project’s support libraries is in the app/build.gradle file which shows support libraries as dependencies:

dependencies {
  compile fileTree(dir: 'libs', include: ['*.jar'])
  testCompile 'junit:junit:4.12'
  compile 'com.android.support:appcompat-v7:23.3.0'
  compile 'com.android.support:design:23.3.0'
}

Minimum and target API levels are not set in AndroidManifest.xml

Although the training guide describes setting API level attributes in the manifest file, the minSdkVersion and targetSdkVersion are now set in app/build.gradle:

defaultConfig {
  applicationId "com.example.myfirstapp"
  minSdkVersion 8
  targetSdkVersion 23
  versionCode 1
  versionName "1.0"
}

After you change the minimum or target API levels, you’ll need to sync your project files and rebuild your project. First, choose Tools/Android/Sync Project with Gradle Files and then Build/Rebuild Project.

Quick runtime test of build version

You can use the Snackbar message in the floating action button code to create a quick test of the system version by replacing the string with

"Build version is " + Build.VERSION.SDK_INT. 

The integer SDK_INT allows you to retrieve the system API level. Here is the complete code snippet:

fab.setOnClickListener(new View.OnClickListener() {
  @Override
  public void onClick(View view) {
      Snackbar.make(view, "Build version is " + Build.VERSION.SDK_INT, Snackbar.LENGTH_LONG)
              .setAction("Action", null).show();
  }
});

Android Studio does not recognize Theme.Transparent

If you attempt to change your activity theme in the manifest file, you’ll discover the file uses string resources, not string literals. For example, the theme for MyActivity is @style/AppTheme.NoActionBar, which is defined in styles.xml. This theme is a customization of the base application theme (AppTheme) which inherits properties from Theme.AppCompat.Light.DarkActionBar found in the Android Support v7 AppCompat library.

You change themes by editing them in the styles.xml file. However, if you try changing the parent theme to Theme.Transparent (as shown in the training guide) you get a warning that Android Studio doesn’t recognize that theme.

This behavior arises because the Basic Activity template uses the AppCompat library. If you look at the beginning of your Java class declarations, you’ll see Activity extends the class AppCompatActivity. The AppCompat library allows you to use the action bar on older devices and also provides access to Material Design elements (such as themes) that are otherwise available only on devices running API 21 and above.

You can still change the theme of your first app by choosing a theme from the AppCompat library. Although not all options make a visible difference, Theme.AppCompat.Light.Dialog.Alert will make your app look like a floating dialog box.

To change themes in style.xml, begin typing Theme.AppCompat as the parent theme for the base application, and then make a selection from the autocomplete pop-up. Run your app. (Use Ctrl+Enter to show the list of available themes if they don’t automatically pop up.)

You can also customize your theme by adding items to styles.xml. Changing text size is one way to make a visible change in your app. Add a textSize item and experiment with different values. Using 24sp makes a noticeable difference in your app’s font sizes. (Use scaleable pixels (sp) for text elements, so they work with users’ accessibility settings.) For example, use 

<item name="android:textSize">@dimen/size_of_text</item>

where size_of_text is set in dimens.xml:

<dimen name="size_of_text">24sp</dimen>dimen>

Additional Resources

Managing Projects with Android Studio describes creating an app, creating a module, setting up and referencing a library module, and talks more about the Android Project view.

Android Studio Overview discusses the project structure, the Gradle build system, debugging and profile tools including memory and CPU monitors, additional debugging tools (Systrace and Traceview), and annotations.


Your turn!

Post any additional thoughts, questions, or tips in the comments and have some fun with Android Studio 2.0!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s