Lecture 2 - Input, Storing Values, Output

home | previous | next

Overview

We will learn getting data from users and displaying some information on the screen. And we will learn how to store the data until users launch our application again.

Simple Input and Output

Exercise 2.1

Make a new project.
In the default activity, place widgets like follows:

EditText (editText1)
Button (button1)
TextView (textView1)

To do 1:
When the user clicks button1 after writing some text in editText1, display the text on textView1.

Storing data for future use

To store data, we usually use file system of the platform. If we want to store many data of different types in one file, we have to use some structure to write and read data. To make code simple, we just use a ready-made fuction of Android system.

Activity class has 2 methods for us to get SharedPreferences object.

SharedPreferences getSharedPreferences (String name, int mode)
SharedPreferences getPreferences (int mode)

Example 2.1

SharedPreferences pref = getPreferences(0);
SharedPreferences.Editor prefedit = pref.edit();
prefedit.putString("name", "Sangdeuk");
prefedit.putInt("age", 35);
prefedit.putBoolean("membership", true);
prefedit.commit();

Example 2.2

We retrieve data from pref.

SharedPreferences pref = getPreferences(0);
String name = pref.getString("name", "");
int age = pref.getInt("age", 0);
boolean membership = pref.getBoolean("membership", false);

Exercise 2.2

Use the project of exercise 2.1.

To do 1:
When the user clicks button1 after writing some text in editText1, display the text on textView1.

To do 2:
Store the text in the storage with SharedPreferences class.

To do 3:
When the user launches this application again, read the text from the storage and display it on textView1.

Related subjects

Resources

Links