Make Your First Android App: Part 2/3

Learn to enhance the app you created in the first part on how to make your first Android app and to add new UI controls to add new functionality. By Matt Luedke.

Leave a rating/review
Save for later
Share
You are currently viewing page 6 of 7 of this article. Click here to view the first page.

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.

Note: It’s a good practice to use variables for 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.

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 code:

	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 :]

Note: While you could conceivably place all the code from 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.

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 OnClickListeners are specifically DialogInterface.OnClickListeners, 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.

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!

Matt Luedke

Contributors

Matt Luedke

Author

Over 300 content creators. Join our team.