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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
<?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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
<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
1 2 3 4 5 6 7 8 9 10 11 |
<?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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 |
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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
<?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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
<?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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
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); } } |
Leave a Reply