Android Tutorial for Beginners: Part 2
An Android Tutorial that shows you how to make your first app app step-by-step, using Android Studio! By Darryl Bayliss.
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress, bookmark, personalise your learner profile and more!
Create accountAlready a member of Kodeco? Sign in
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress, bookmark, personalise your learner profile and more!
Create accountAlready a member of Kodeco? Sign in
Contents
Android Tutorial for Beginners: Part 2
55 mins
- Getting Started
- XML Layout Basics
- Relative Layouts
- Linear Layouts
- Accessing Views From Within Java
- Buttons and Listeners
- Adding a Visual and Nested Layouts
- Involving the Keyboard
- The ListView
- Detecting List Selections
- The Action Bar
- Sharing
- Remembering Your Name
- Displaying the Name Dialog
- Where to Go From Here?
Remembering Your Name
Everything you’ve done so far with regard to user input only persists while the app is running. But what about between sessions? Let’s see some data persistence in action, with a new feature that will record and remember your name each time you open the app.
There are a few good options on Android to persist data, and the simplest one is SharedPreferences
.
SharedPreferences
stores data in key-value pairs, meaning that you specify a name (the key) for a piece of data (the value) when you save it, and you can retrieve it later by using the original key.
Let’s see how it works in action, shall we?
First, add the following constants and variable to MainActivity.java (to the same place as the previous variables):
private static final String PREFS = "prefs";
private static final String PREF_NAME = "name";
SharedPreferences mSharedPreferences;
The above sets PREF
and PREF_NAME
at the top of the class. You’ll use PREF
as a filename to keep your SharedPreferences
in a single location. You’ll use PREF_NAME
as the key for storing your name in shared preferences.
Strings
that you’ll need/refer to multiple times. That way, if you need to change the string value later, you can do it in one place. You’ll also never have to worry about some weird spelling error creating bugs in your code.The final line adds a variable named mSharedPreferences
for storing a reference to the shared preferences class. You only need to access it in a few places, but it will be useful to hang onto it. Add the import into your Class if you haven’t already.
Next, add the following lines to the end of onCreate
:
// 7. Greet the user, or ask for their name if new
displayWelcome();
The new code calls a new method, displayWelcome
. So implement that by adding the following method at the end of the class:
public void displayWelcome() {
// Access the device's key-value storage
mSharedPreferences = getSharedPreferences(PREFS, MODE_PRIVATE);
// Read the user's name,
// or an empty string if nothing found
String name = mSharedPreferences.getString(PREF_NAME, "");
if (name.length() > 0) {
// If the name is valid, display a Toast welcoming them
Toast.makeText(this, "Welcome back, " + name + "!", Toast.LENGTH_LONG).show();
}
}
This also means that if the same task needs to be performed from elsewhere in code later on, you already have a handy method in place for it :]
displayWelcome
directly into onCreate
and it would still work, many people, your humble author included, prefer to keep method lengths reasonable by calling separate methods for a specific task.
This also means that if the same task needs to be performed from elsewhere in code later on, you already have a handy method in place for it :]
In the new method, the first thing you do is access SharedPreferences
, with MODE_PRIVATE
meaning that only your OMGAndroid app can access the data stored here. This means that your saved data will not get overwritten by another application which might have used the same key as you.
Then you simply ask the preferences object for whatever value is stored using the key PREF_NAME
. The second parameter for the method can be used to set a default value to be returned in case there is no value stored using the key you provide. So, you use an empty String
as the default value here.
Finally, you check to see if the retrieved String
actually has any content, and display a message if so. Your message takes the form of a Toast
, which is a short-lived pop-up message that appears for a bit and then fades away. Give the Toast
a message it should display, specify one of its built-in lengths to remain on the screen and then simply tell it to show
. Easy!
Displaying the Name Dialog
What you’ve set up so far will show your name if the application can retrieve it out of the preferences. But obviously, that’s no use to you yet since you have no mechanism in place to save your name in the first place!
You’ll use a Dialog
to achieve that. Dialogs
are small windows that alert the user. They may contain ways for the user to provide input or make choices. You’re going to use an AlertDialog
, specifically.
Add the following code to the end of displayWelcome
, creating an else
branch for the if
condition that’s already there:
} else {
// otherwise, show a dialog to ask for their name
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Hello!");
alert.setMessage("What is your name?");
// Create EditText for entry
final EditText input = new EditText(this);
alert.setView(input);
// Make an "OK" button to save the name
alert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Grab the EditText's input
String inputName = input.getText().toString();
// Put it into memory (don't forget to commit!)
SharedPreferences.Editor e = mSharedPreferences.edit();
e.putString(PREF_NAME, inputName);
e.commit();
// Welcome the new user
Toast.makeText(getApplicationContext(), "Welcome, " + inputName + "!", Toast.LENGTH_LONG).show();
}
});
// Make a "Cancel" button
// that simply dismisses the alert
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {}
});
alert.show();
}
The app will reach this else
condition when there is no valid name saved using the PREF_NAME
key. You use an AlertDialog.Builder
to give your AlertDialog
a title, a message, and an EditText
in the center for the user to type in their name.
Then, you add two buttons to the AlertDialog
: a positive and a negative button. The first thing you define for each is the text displayed on the button – “OK” and “Cancel” are pretty standard choices. The second thing you define for each button is an OnClickListener
.
This time your OnClickListener
s are specifically DialogInterface.OnClickListener
s, and you are defining them right away. Notice how the parameters for onClick
are slightly different.
For the positive button’s listener, onClick
does quite a bit. First, it reads the name that the user typed into the dialog’s EditText
.
It then saves that name into SharedPreferences
using a helper called a SharedPreferences.Editor
. You simply tell the editor what to save and where, tell it to commit the changes, and that’s it!
Finally, it displays a Toast
identical to the other welcoming one.
The negative button’s listener is far simpler: it does nothing! Nothing!
Run your app and check out your Dialog
.
Type in your name, press OK and see the Toast
greeting. From now on, your app will remember your name and greet you each time you launch it!