Your first Android app, from the ground up
Understand activities, connect a layout, and make your first button do something.
What you’ll learn
Before you start
- Android Studio with an installed Android SDK
- A Java-based Empty Views Activity project
1. Start with a Views project
Create a Java-based Empty Views Activity in Android Studio. This lesson uses platform Activity to keep the example focused. If your generated project uses AppCompat, retain its dependency and theme or adapt the superclass deliberately.
The example package is com.example.counter. Match your project's namespace, or update the package declaration. Use an installed Android SDK and keep your generated Gradle configuration.
2. Describe the screen
Open res/layout/activity_main.xml. Give the TextView and Button unique IDs. A vertical LinearLayout places them one above the other; gravity="center" centers the group.
Use dp for padding and sp for text size so the interface responds to density and the user's font settings.
3. Connect the activity
Call setContentView before findViewById. The activity loads the XML, finds each view, and registers a click listener. Convert the integer to a string before calling setText; the integer overload expects a string resource ID.
4. Preserve the counter
The activity reads the saved count in onCreate and writes it in onSaveInstanceState. This handles activity recreation such as a device rotation. It is not permanent storage: use a database or preferences for data that must persist between sessions.
Expected output
The screen starts at 0. Each tap on Add one increments the visible number. Rotating the device keeps the current value when Android restores the activity state.
Troubleshooting
- Cannot resolve R: check XML errors and the module namespace first.
- NullPointerException: confirm you loaded the correct layout and the IDs match.
- Resources.NotFoundException: pass
String.valueOf(count)tosetText, rather than the integer itself. - App does not appear in launcher: check the exported launcher activity in the manifest.
Try it yourself
Add a reset button. Set the counter to zero and update the TextView in its click listener. Then test rotation and confirm both buttons still work.
Explore the source files
package com.example.counter;
import android.app.Activity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
private int count = 0;
@Override
protected void onCreate(Bundle state) {
super.onCreate(state);
setContentView(R.layout.activity_main);
if (state != null) count = state.getInt("count", 0);
TextView label = findViewById(R.id.counter);
Button button = findViewById(R.id.increment);
label.setText(String.valueOf(count));
button.setOnClickListener(view -> {
count++;
label.setText(String.valueOf(count));
});
}
@Override
protected void onSaveInstanceState(Bundle state) {
state.putInt("count", count);
super.onSaveInstanceState(state);
}
}