In this part of my Android tutorial I cover 3 ways to save data. We’ll look at Bundles, onSaveInstanceState, SharedPreferences, and PreferenceActivity. We’ll also be reviewing working with components, Intents, click listeners, onActivityResult and a bunch of other topics.
This will begin a series of tutorials in which I cover everything about Android that I have previously not covered.
If you like videos like this, it helps to tell Google Plus with a click here [googleplusone]
Code From the Video
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.newthinktank.derekbanas.savingstate" >
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MyActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".SettingsActivity"
android:label="@string/title_activity_settings" >
</activity>
</application>
</manifest>
activity_my.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MyActivity">
<TextView
android:text="@string/notesTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20sp"
android:id="@+id/notesTextView" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textMultiLine"
android:ems="10"
android:id="@+id/notesEditText"
android:layout_below="@+id/notesTextView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="15dp"
android:lines="6"
android:maxLines="6"
android:hint="@string/notesEditText"
android:gravity="top"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="109dp"
android:text="Settings"
android:id="@+id/btnSettings"
android:layout_below="@+id/notesEditText"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
</RelativeLayout>
strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">SavingState</string>
<string name="hello_world">Hello world!</string>
<string name="action_settings">Settings</string>
<string name="notesEditText">Enter notes</string>
<string name="notesTextView">Notes</string>
<string name="title_activity_settings">SettingsActivity</string>
</resources>
MyActivity.java
package com.newthinktank.derekbanas.savingstate;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Typeface;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MyActivity extends Activity {
EditText notesEditText;
Button btnSettings;
private static final int SETTINGS_INFO = 1;
// You can define what keys and values are passed to onCreate
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
notesEditText = (EditText) findViewById(R.id.notesEditText);
// 1. Make sure there is data to retrieve
if(savedInstanceState != null){
String notes = savedInstanceState.getString("NOTES");
notesEditText.setText(notes);
}
// 2. Retrieves the String stored in shared preferences or "EMPTY" if nothing
String sPNotes = getPreferences(Context.MODE_PRIVATE).getString("NOTES", "EMPTY");
if(!sPNotes.equals("EMPTY")){
notesEditText.setText(sPNotes);
}
// 3. Get a reference to the settings button
btnSettings = (Button) findViewById(R.id.btnSettings);
// 3. If the button is clicked create an intent to open the SettingsActivity class
btnSettings.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intentPreferences = new Intent(getApplicationContext(),
SettingsActivity.class);
// 3. Start the activity and then pass results to onActivityResult
startActivityForResult(intentPreferences, SETTINGS_INFO);
}
});
}
// 3. Called after the settings intent closes
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode, resultCode, data);
// 3. Check that the intent with the id SETTINGS_INFO called here
if(requestCode == SETTINGS_INFO){
updateNoteText();
}
}
// 3. Update the text changes in the EditText box
private void updateNoteText(){
// Shared key value pairs are here
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
// Check if the checkbox was clicked
if(sharedPreferences.getBoolean("pref_text_bold", false)){
// Set the text to bold
notesEditText.setTypeface(null, Typeface.BOLD_ITALIC);
} else {
// If not checked set the text to normal
notesEditText.setTypeface(null, Typeface.NORMAL);
}
// Get the value stored in the list preference or give a value of 16
String textSizeStr = sharedPreferences.getString("pref_text_size", "16");
// Convert the string returned to a float
float textSizeFloat = Float.parseFloat(textSizeStr);
// Set the text size for the EditText box
notesEditText.setTextSize(textSizeFloat);
}
// 1. Called before Android kills an application, but doesn't protect you
// if the user kills the app or restarts the device
@Override
protected void onSaveInstanceState(Bundle outState) {
// Save the value in the EditText using the key NOTES
outState.putString("NOTES",
notesEditText.getText().toString());
super.onSaveInstanceState(outState);
}
// 2. Will save key value pairs to SharedPreferences
private void saveSettings(){
// SharedPreferences allow you to save data even if the user kills the app
// MODE_PRIVATE : Preferences shared only by your app
// MODE_WORLD_READABLE : All apps can read
// MODE_WORLD_WRITABLE : All apps can write
// edit() allows us to enter key vale pairs
SharedPreferences.Editor sPEditor = getPreferences(Context.MODE_PRIVATE).edit();
// Add the key "NOTES" and assign it to the value
sPEditor.putString("NOTES", notesEditText.getText().toString());
// Save the shared preferences
sPEditor.commit();
}
// 2. Called if the app is forced to close
@Override
protected void onStop() {
saveSettings();
super.onStop();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.settings, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
preferences.xml
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<CheckBoxPreference
android:key="pref_text_bold"
android:title="Make Text Bold"
android:summary="Makes the note text bold"
android:defaultValue="false" />
<ListPreference
android:key="pref_text_size"
android:title="Text Size"
android:summary="Pick the text size"
android:entries="@array/text_size_entries"
android:entryValues="@array/text_size_values"
android:defaultValue="16"/>
</PreferenceScreen>
arrays.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="text_size_entries">
<item>16 pt</item>
<item>18 pt</item>
<item>20 pt</item>
<item>22 pt</item>
<item>24 pt</item>
<item>26 pt</item>
</string-array>
<string-array name="text_size_values">
<item>16</item>
<item>18</item>
<item>20</item>
<item>22</item>
<item>24</item>
<item>26</item>
</string-array>
</resources>
SettingsActivity.java
package com.newthinktank.derekbanas.savingstate;
import android.os.Bundle;
import android.preference.PreferenceActivity;
public class SettingsActivity extends PreferenceActivity {
@SuppressWarnings("deprecation")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Define the xml file used for preferences
addPreferencesFromResource(R.xml.preferences);
}
}