Our First Android Application

Even though the HelloWorld program is trivial in introduces a wealth of new ideas -- the framework, activities, manifest, intents, UI, resources such as layouts, strings, etc. I know all just to print Hello World! There is a lot to take in regarding the Android program plumbing but an important separation principal presented in the single HelloWorld is the separation between UI design in XML and the program.

Next, we consider a more complex with multiple UIs, activities and intents -- it's called MyFirstApp and the code is linked in so you can download and run it.

What this lecture covers:

Checkout the demo project

Download the demo the MyFirstApp.zip app to go with these notes. 

I recommend that you code this project up from the notes rather than just open the project in Android Studio and run it -- but feel free to do that if you really want. As a rule I will include all source code examples and projects used in course when I can.

Open an existing Android project in Android Studio

To open each of the demo projects we give out, you will need to do this:

Clean a project

If for some reason there are errors try a clean. This is always a good thing to do if there are spurious errors in a project you know is clean.

Go to Build->Clean Project.

Hope that helped.

MyFirstApp

This application moves things forward. First it includes two activities. The main activity starts the second activity using an intent. When the user inputs a message on the UI of the first activity and clicks send the message is bundled up in an intent and the display activity started -- which displays the message on its own UI. Take a look at the screen dumps below: the first one is the UI rendered by the MainActivity UI, next the user enters a message and clicks the Send button -- and wham -- the DisplayMessageActivity is started to display the message in a larger -- sort of uncool -- font. There is a lot more to this simple program. Note, the menus for each UI is different. You can navigate back using the back button (or back swipe).

This program -- MyFirstApp -- is taken from the Android developers with minor modifications.

The MainActivity's UI

Open the app/java/ com.xd.myfirstkotlinapp folder and look at the MainActivity.kt code.

Create a linear layout

The MainActivity's layout file is at app/res/layout/activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">

Add a text field

<EditText
android:layout_width="150dp"
android:layout_height="wrap_content"
android:id="@+id/edit_message"
android:layout_weight="2"
android:hint="@string/edit_message" />

Add String Resources

By default, your Android project includes a string resource file at app/res/values/strings.xml. Add a new string named "edit_message" and set the value to "Enter a message." (You can delete the "hello_world" string.)

While you’re in this file, also add a "Send" string for the button you’ll soon add, called "button_send".

<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">My First App</string>
<string name="edit_message">Enter a message</string>
<string name="button_send">Send</string>
</resources>

Add a button

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="6"
android:onClick="onClick" //respond to click event
android:text="@string/button_send"/>

Format the Input box

<EditText
android:layout_width="150dp"
android:layout_height="wrap_content"

... />

Final XML

Open the activity_main.xml file from the res/layout/ directory.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">

<EditText
android:layout_width="150dp"
android:layout_height="wrap_content"
android:id="@+id/edit_message"
android:layout_weight="2"
android:hint="@string/edit_message" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="6"
android:onClick="onClick"
android:text="@string/button_send"/>
</LinearLayout>

Building an Intent

Open the MainActivity class (located in the project's app/java/com.xd.myfirstkotlinapp/ directory) and add the corresponding method:

package com.xd.myfirstkotlinapp

import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.EditText


class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
setTitle("xd yang")
}

fun onClick(view: View){
val intent: Intent = Intent(this, DisplayMessageActivity::class.java)
val editText = findViewById(R.id.edit_message) as EditText
val message: String = editText.text.toString()
intent.putExtra(EXTRA_MESSAGE, message)
startActivity(intent)
}

companion object{
val EXTRA_MESSAGE = "extra_msg"
}
}

Starting another activity

To start an activity, call startActivity() and pass it your Intent. The system receives this call and starts an instance of the Activity specified by the Intent.

With this new code, the complete onClick() method that's invoked by the Send button now looks like this:

    fun onClick(view: View){
val intent: Intent = Intent(this, DisplayMessageActivity::class.java)
val editText = findViewById(R.id.edit_message) as EditText
val message: String = editText.text.toString()
intent.putExtra(EXTRA_MESSAGE, message)
startActivity(intent)
}

Now you need to create the DisplayMessageActivity class in order for this to work.

Create another activity -- DisplayMessageActivity

To create a new activity using Android Studio:

Right click app, find New->Activity->Empty Activity and click to open the create activity dialog. Fill in the activity details:

Finally click Finish.

The DisplayMessageActivity class should now look like this:


package com.xd.myfirstkotlinapp

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle

class DisplayMessageActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activitydisplay_message)
}
}

Add it to the manifest

Take a look at the XML for the new activity .DisplayMessageActivity in the manifest. The code is self explanatory.


<application ... >
...
<activity android:name=".DisplayMessageActivity" />
</application>

Running the app

You can run the app now, but not much happens. Clicking the Send button starts the second activity but it uses a default "Hello world" layout provided by the template. You'll soon update the activity to instead display a custom text view.

Receive the Intent

In the DisplayMessageActivity class’s onCreate() method, get the intent and extract the message delivered by MainActivity:

class DisplayMessageActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_display_message)

val message: String? = intent.getStringExtra(MainActivity.EXTRA_MESSAGE)
}
}

Display the Message

To show the message on the screen, create a TextView widget and set the text using "textView.text".

The complete onCreate() method for DisplayMessageActivity now looks like this:

class DisplayMessageActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_display_message)

val message: String? = intent.getStringExtra(MainActivity.EXTRA_MESSAGE)
val textView: TextView = findViewById(R.id.my_textview1)
textView.text = message
}
}

You are done, now run your Android firstapp!

You should see the following screens on your phone or emulator

Application Logging using Log.d()

You can put print or log statements your code. You might want to confirm for example that an intent fired by one activity is received by another. You can use println() or Log.d() to do this. For Log.d(), you have to first create a TAG in your code and then call Log.d() with the tag.

In the code snippet below that you need to import android.util.Log, set up the TAG, and then call Log.d()

class DisplayMessageActivity : AppCompatActivity() {
private
static final String TAG = "debug:";

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_display_message)

...
Log.d(TAG, "Got Intent")
println("debug: Got Intent")
...
}
}

Using LogCat to view application output

An easy way to monitor the output from println() and Log.d() is to use the LogCat utility. LogCat is integrated into Android Studio. You’ll find the LogCat by clicking the Android tab at the bottom of Android Studio. The following screenshot shows the code to print logs in LogCat and viewing logs from the LogCat window.

Once you click on run and enter input you will see to logs printed out from the application: one when the user clicks send at the UI; and one when DisplayMessageActivity receives the Intent and prints the message, as shown above.

This is a simple example of logging applications. Much more sophisticated logging can be done. More on this later.