QuestionQuestion

Transcribed TextTranscribed Text

Exercise 2: Data across application life cycles. When applications create or capture data from user inputs, those data will only be available during the lifetime of the application. You only have access to that data as long as the application is not yet killed by the runtime. When the application is shut down, all the data that has been created while the application was running will be lost. Android offers a variety of ways for us to persist data so that it can outlive the application lifetime and allow us access to the same data across application life cycles. In this tutorial we will explore the SharedPreferences storage option. SharedPreferences This is the simplest form of storage. It’s just a dictionary object that uses the key/value pair idiom. This is useful if your data is simple enough to be structured as a dictionary object (key/value pairs). Android stores these files internally as XML files. SharedPrefs only stores simple data types (e.g., String and primitive data types). It cannot store more complex data To create a SharedPreferences file, we need to use the getPreferences method while inside an Activity class and then specify the mode of access for the file. SharedPreferences sp = getPreferences(CONTEXT.MODE_PRIVATE); As per Android documentation, Context.MODE_PRIVATE is what we are supposed to use because the public mode has already been deprecated since API level 17. Next, we need an Editor object so we can start modifying data in the newly created file. SharedPreferences.Editor editor = sp.edit(); Now we can start putting in some data. edit.putString("name","Gandalf the Grey"); edit.putInt("age", 2019); The first parameter to the put commands is always the key, and the second parameter is the value. In the preceding example, “name” and “age” are the keys and “Gandalf the Grey” and 2019 are values, respectively. The put commands, by themselves, do not save the data to the file, so we need to use either the apply or the commit method. editor.apply(); // or editor.commit(); Either the commit or apply method will save the information and persist it in an XML file; there are only slight differences between these two methods. • commit—this is synchronous and returns a boolean value, it returns true if the write operation succeeded • apply—this also saves the data but does not return any value. It is executed asynchronously NOTE: You don’t need to specify a file name for the shared preferences file; the Android runtime will automatically assign a name for the newly created file. By convention, the newly created file follows the name of the activity class from where getPreferences was called from; for example, if you called getPreferences from MainActivity.java, the name of the shared preferences file will be MainActivity.xml Retrieving data from a shared preferences file is just as easy as creating it. To access the created shared preferences file, we use the same syntax when we created the file in the first place. SharedPreferences sp = getPreferences(CONTEXT.MODE_PRIVATE); The getPreferences method returns an instance of a SharedPreferences object. The first time this method is called, it will look for an XML file bearing the same name as the activity from which the method was called; if it doesn’t find that file, it will be created, but if the file already exist, it will be used instead. Since we already created the file the first time we called getPreferences, Android won’t be creating a new file, nor will it overwrite what we created before. Once we have a shared preferences object, we can extract data from it. sp.getString("name", "default value"); sp.getInt("age", 0); Now, let’s start our practical project. • Create a new project and name it “SharedPreferences”. • Design the UI details for the main layout file as shown below. 2 EditView, 2 Buttons and 1 TextView • The basic workflow for this app is as follows: 1. Type the last name and first name information in the two text fields. 2. When the “SAVE” button is clicked, extract the string values from the text fields. To do so, follow the next steps: o Create a shared preferences files (if one does not exist yet) o Push the last name and first name data into the shared pref file by using one of the put methods of editor object o Save the changes 3. When the “LOAD” button is clicked. Follow the next steps: o Retrieve the shared preferences file using the same syntax as when it was created o Retrieve the data on the file using one of the get methods o Show the retrieved data by setting the text attribute of a TextView object Strat coding now! • In the onCreate() method access the UI views and create two onClick() events for the two buttons. Button btnsave = (Button) findViewById(R.id.btnsave); Button btnload = (Button) findViewById(R.id.btnload); Continue coding … … • In the btnsave onClick() event, write the following code: SharedPreferences sp = getPreferences(Context.MODE_PRIVATE); ❶ SharedPreferences.Editor edit = sp.edit(); ❷ String lname = etlastname.getText().toString(); ❸ String fname = etfirstname.getText().toString(); edit.putString("lname", lname); ❹ edit.putString("fname", fname); edit.apply(); ❺ Toast.makeText(MainActivity.this, "Saved it", Toast.LENGTH_SHORT).show(); Save Button ❶ Creates the shared preferences file, if one doesn’t exist yet ❷ We can’t save data to the shared preferences file (yet); we need an interface object for it. The editor objects will do that job ❸ Retrieve whatever the user has typed on the EditText objects and assign them to String variables ❹ Use the editor object to persist data into the shared preferences file ❺ Commit the changes to the file • In the btnload onClick() event, write the following code: SharedPreferences sp = getPreferences(Context.MODE_PRIVATE); ❶ String lname = sp.getString("lname", "na"); ❷ String fname = sp.getString("fname", "na"); tv.setText(String.format("%s, %s", lname, fname)); ❸ Load Button ❶ Retrieve the shared preferences object by getting a reference to it. The syntax for creating a shared preferences object is the same as that for retrieving it. Android is clever enough to Note: Figure out that if the file doesn’t exist, you want to create, and if it does exist, you want to retrieve it ❷ Get the data out of the shared pref file using one of the get methods; store it in a String variable ❸ Set the text of the TextView object using the retrieved data from the shared pref file • Finalise the code, check for errors and run your application

Solution PreviewSolution Preview

These solutions may offer step-by-step problem-solving explanations or good writing examples that include modern styles of formatting and construction of bibliographies out of text citations and references. Students may use these solutions for personal skill-building and practice. Unethical use is strictly forbidden.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.sharedpreferences">

    <application
       android:allowBackup="true"
       android:icon="@mipmap/ic_launcher"
       android:label="@string/app_name"
       android:roundIcon="@mipmap/ic_launcher_round"
       android:supportsRtl="true"
       android:theme="@style/AppTheme">
       <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
       </activity>
    </application>

</manifest>...

By purchasing this solution you'll be able to access the following files:
Solution.zip.

$36.00
for this solution

or FREE if you
register a new account!

PayPal, G Pay, ApplePay, Amazon Pay, and all major credit cards accepted.

Find A Tutor

View available Java Programming Tutors

Get College Homework Help.

Are you sure you don't want to upload any files?

Fast tutor response requires as much info as possible.

Decision:
Upload a file
Continue without uploading

SUBMIT YOUR HOMEWORK
We couldn't find that subject.
Please select the best match from the list below.

We'll send you an email right away. If it's not in your inbox, check your spam folder.

  • 1
  • 2
  • 3
Live Chats