Store User Data Using Simple Text Files and APIs in Android

Abbas Suterwala
Share

Android apps have a wide variety of features, functionalities, and purposes. These various Android apps require similarly varied support from Android system APIs. Many apps require storing data in short-term memory that lasts only as long as the app is running. But, some apps need to store data or user preferences persistently, so that user data and user preferences are maintained indefinitely. In this article, we are going to demonstrate how we can store data in files, and also how can we store user preferences using Android APIs. We’ll create two small apps: one to store an read a file from user input, and one to store user preferences.

Creating the UI of the File Store App

Lets start by creating a simple app that shows an text editor and allows the user can input any text to be saved as a file.The saved text will be saved within the text editor next time the application is started by reading from the storage file.

First, we’ll create the UI for the app. Within the UI we are going to create a text editor and a save button on screen.

The layout for this UI is as follows:

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

android:orientation="vertical"

android:layout_width="fill_parent"

android:layout_height="fill_parent"

>

<TextView

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:text="Enter the text"

/>

<EditText

android:id="@+id/textbox"

android:singleLine="false"

android:gravity="top"

android:lines="10"

android:layout_width="fill_parent"

android:layout_height="wrap_content"/>

<Button android:id="@+id/save"

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:text="Save the notes"

android:onClick="saveClicked"/>

</LinearLayout>

Above, we create a text view using the tag <TextView>, which just displays the text as “Enter The Text”.

Next, we create an editor to take in the text from the user. We create this using the <EditText> tag, and because we want the text to be multi-line, we also set the properties android:singleLine=“false” and android:lines=“10” on the EditText. Then, we create a button using the <Button> tag, which will be used to save the modified text to a file.

Once the layout is created, we’ll use the function onCreate to set this layout of the content view as follows:

public class FileDemo extends Activity {

/** Called when the activity is first created. */

private final static String STORETEXT="storetext.txt";

private EditText txtEditor;

@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

txtEditor=(EditText)findViewById(R.id.textbox);

}

}

Now, if we run the app, the UI will look as follows:

Saving the File

Once the UI is done, we need to add functionality to save the text contents to a file upon pressing the “Save” button. To do this, the code is as follows:

public void saveClicked(View v) {

try {

OutputStreamWriter out=

new OutputStreamWriter(openFileOutput(STORETEXT, 0));

out.write(txtEditor.getText().toString());

out.close();

Toast

.makeText(this, "The contents are saved in the file.", Toast.LENGTH_LONG)

.show();

}

catch (Throwable t) {

Toast

.makeText(this, "Exception: "+t.toString(), Toast.LENGTH_LONG)

.show();

}

}

Once “Save” is clicked, the function saveClicked is called. In the function saveClicked, we open a file using the Android API openFileOutput by passing it the name of the file to open, which we defined in our class as

private final static String STORETEXT="storetext.txt";

Then, we create an object of OutputStreamWriter using the output of openFileOutput.

Finally, we get the text of the text editor and pass it to the write method of our OutputStreamWriter to write it to the file. Once the text is written to the file, we show a Toast to indicate that the text is saved. Below, the Toast reads “The contents are saved in the file.”

Reading the Text File Upon App Load

Now, let’s write a function that reads this newly-created file and populates the text editor with the contents of the file. We will call this function in the onCreate function so that as soon as the app launches, the editor is filled with the information from the file. The function is as follows:

public void readFileInEditor()

{

try {

InputStream in = openFileInput(STORETEXT);

if (in != null) {

InputStreamReader tmp=new InputStreamReader(in);

BufferedReader reader=new BufferedReader(tmp);

String str;

StringBuilder buf=new StringBuilder();

while ((str = reader.readLine()) != null) {

buf.append(str+"n");

}

in.close();

txtEditor.setText(buf.toString());

}

}

catch (java.io.FileNotFoundException e) {

// that's OK, we probably haven't created it yet

}

catch (Throwable t) {

Toast

.makeText(this, "Exception: "+t.toString(), Toast.LENGTH_LONG)

.show();

}

}

In this function, we first open the file with the API openFileInput, and then we create an InputStream from it. From that, we create an InputStreamReader and a BufferedReader. Using the BufferedReader, we read line after line the text of the storage file, and we store the text in the buffer. Once the whole file is read, we send the text into the editor. Now, if the application is run, the application will load the the editor filed with the contents of the file, as shown below.

Shared Preferences Introduction

Shared preferences allow you to store key => value pairs of different settings that you want within your Android app, even if the app session is closed. You can store a number of native preference types, such as Boolean, int, strings, etc. Below, we are going to create a small app in which the user can store the preference of whether he wants the activities background color as blue or red.

Creating a UI for storing Preferences

First, we must create the UI of the app. The layout for the app will be as follows:

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

android:orientation="vertical"

android:layout_width="fill_parent"

android:layout_height="fill_parent"

android:id="@+id/myScreen"

>

<TextView

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:text="Please select the preference of background color"

/>

<RadioGroup

xmlns:android="http://schemas.android.com/apk/res/android"

android:orientation="vertical"

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:id="@+id/prefgroup"

>

<RadioButton android:id="@+id/blue"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Blue" />

<RadioButton android:id="@+id/red"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Red" />

</RadioGroup>

<Button android:id="@+id/savepreferences"

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:text="Save Preferences"

android:onClick="savepreferencesClicked"

/>

</LinearLayout>

Above, we create a linear layout and then add a TextView to display the message that asks the user to select his background color preference. Then, we create a radio button group with two radio button to give the two color options to the user. Lastly, we create a button that will save the user’s color preference upon being pressed..

If we run the app now, the UI will look like this:

Saving the Preferences

Now, lets see how we can save the preference that the user has selected. The code to save the preference is as follows in the function  saveBgColorPreference.

public void saveBgColorPreference()

{

RadioGroup g = (RadioGroup) findViewById(R.id.prefgroup);

int selected = g.getCheckedRadioButtonId();

RadioButton b = (RadioButton) findViewById(selected);

String selectedValue = (String) b.getText();

SharedPreferences myPrefs = this.getSharedPreferences("myPrefs", MODE_WORLD_READABLE);

SharedPreferences.Editor prefsEditor = myPrefs.edit();

prefsEditor.putString("bgcolor", selectedValue);

prefsEditor.commit();

}

In this function, we get the RadioGroup, and we find the ID of the radio button that was selected. Then, we get the text of the selected radio button to check which color the user has selected. Then, we get the SharedPreferences object using the function getSharedPreferences. Because we want to edit the shared preferences, we have to get the SharedPreferences.Editor and then call the function putString on it to write the string and then call commit to finish the writing transaction. This will store the color value within the stored preferences.

Using the Saved Preferences to Change Properties of the App

Now that we’ve written code to store the user’s color preference, we will write a function setColorOnPreference to actually change the background color according to the preference. The function is as follows:

public void setColorOnPreference()

{

mScreen = (LinearLayout) findViewById(R.id.myScreen);

SharedPreferences myPrefs2 = this.getSharedPreferences("myPrefs", MODE_WORLD_READABLE);

String prefName = myPrefs2.getString("bgcolor", "Blue");

if(prefName.equals("Blue"))

mScreen.setBackgroundColor(0xff0000ff);

else

mScreen.setBackgroundColor(0xffff0000);

}

In this function we get the linear layout using its ID. Then, we get the shared preferences object using the function getSharedPreferences. Then, using the function getString, we get the background color preference.

If the background color is blue, we set the background to blue. Otherwise, we set it to red.

Now, upon pressing the button, we will call the function savepreferencesClicked, which is as follows:

public void savepreferencesClicked(View v) {

saveBgColorPreference();

setColorOnPreference();

}

In order to start the app with the desired background color (of the users choice), we will call setColorOnPreference in onCreate as follows:

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

setColorOnPreference();

}

Now, if we run the app it will look as follows:

Now, if we select and change the color to red and save it the app will make (and store as a user preference) the following color change:

Conclusion

Android APIs provide good support for developers who want to share persistent data between two different sessions of an Android application. Using files and preferences APIs, we can store user data and preferences to make the application more personalized and practical for the end users. The flexibility with which the APIs are designed has made their use very simple, and apps can be developed very quickly using these powerful APIs. So, happy Android app development!

CSS Master, 3rd Edition