Wednesday, September 19, 2012

Data storage -Shared preferences

Data storage -Shared preferences - Hallo sahabat Google Android Developer Tutorial, Pada Artikel yang anda baca kali ini dengan judul Data storage -Shared preferences, kami telah mempersiapkan artikel ini dengan baik untuk anda baca dan ambil informasi didalamnya. mudah-mudahan isi postingan yang kami tulis ini dapat anda pahami. baiklah, selamat membaca.

Judul : Data storage -Shared preferences
link : Data storage -Shared preferences

Baca juga


Data storage -Shared preferences



 Data Storage Schemes in Android-Shared preferences

               Android provides several schemes for you to save persistent application data.The solution you choose depends on your specific needs, such as  Whether the data should be private to your application or accessible to other applications.How much space your data requires.
Data Storage Schemes
  1. Shared preferences
Store primitive data in key-value pairs
  1. Internal storage
Store private data on the device memory
  1. External storage
Store public data on the shared external storage.
  1. SQLite databases
Store structured data in a private database.
  1. Network connection
Store data on the web with your own network server

Saving and loading user preferences
Android provides the SharedPreferences object to help you save simple application data. For
example, your application may have an option to allow users to specify the font size of the text displayed in your application. In this case, your application needs to remember the size set by the user so that the next time he or she uses the application again, your application can set the size appropriately. In order to do so, you have several options. You can save the data to a file, but you have to perform some file management routines, such as writing the data to the file, indicating how many characters to read from it, and so on. Also, if you have several pieces of information to save, such as text size, font name, preferred background color, and so on, then the task of writing to a file becomes more onerous.An alternative to writing to a text file is to use a database, but saving simple data to a database is overkill,both from a developer’s point of view and in terms of the application’s run-time performance.
Using the SharedPreferences object, however you save the data you want through the use of key/value pairs.  Specify a key for the data you want to save, and then both key and its value will be saved automatically to an XML file.
The Demonstrative project portrays the usage of SharedPreferences feature in Android using an Activity which will retain the text typed in the editText with its set font size through seekBar.
1.Create  Android project with details as listed in table below
Property name
Property value
Project name
SRM_DatastorageSharedPreferences_Tutorial
Package name
in.ac.srmuniv.sharedpreferencestutorial
Activity name
SharedPreferencesActivity
Layout xml name
main
    2.Copy the code  to the file main.xml in res/layout folder 
      <?xmlversion="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"
          >
         
      <SeekBar
          android:id="@+id/SeekBar01"
          android:layout_width="fill_parent"
          android:layout_height="wrap_content"/>
         
      <TextView 
          android:id="@+id/TextView01"   
          android:layout_width="fill_parent"
          android:layout_height="wrap_content"
          android:text="@string/hello"/>
             
      <EditText
          android:id="@+id/EditText01"
          android:layout_width="fill_parent"
          android:layout_height="wrap_content"/>
         
      <Button
          android:id="@+id/btnSave"
          android:text="Save"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"/>   

      </LinearLayout>

      3. 3.Copy the code in SharedPreferencesActivity .java. Activity.
      packagein.ac.srmuniv.sharedpreferencestutorial;

      importandroid.app.Activity;
      importandroid.content.SharedPreferences;
      importandroid.os.Bundle;
      importandroid.view.View;
      importandroid.widget.Button;
      import android.widget.EditText;
      importandroid.widget.SeekBar;
      importandroid.widget.SeekBar.OnSeekBarChangeListener;
      importandroid.widget.Toast;

      public classSharedPreferencesActivity extendsActivity {
                 
          privateSharedPreferences prefs;
          privateString prefName = "MyPref";
          privateEditText editText;
          privateSeekBar seekBar;
          privateButton btn;
         
          private static finalString FONT_SIZE_KEY = "fontsize";
          private static finalString TEXT_VALUE_KEY = "textvalue";
         
          /** Called when the activity is first created. */
          @Override
          public voidonCreate(Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);
              setContentView(R.layout.main);
                     
              editText = (EditText) findViewById(R.id.EditText01);
              seekBar = (SeekBar) findViewById(R.id.SeekBar01);
              btn = (Button) findViewById(R.id.btnSave);
             
              btn.setOnClickListener(newView.OnClickListener() {
                  public voidonClick(View v) {
                             
                              //---get the SharedPreferences object---
                              //prefs= getSharedPreferences(prefName, MODE_PRIVATE);
                              prefs = getPreferences(MODE_PRIVATE);
                             
                      SharedPreferences.Editor editor = prefs.edit();
                     
                      //---save the values in the EditText view to preferences---               
                      editor.putFloat(FONT_SIZE_KEY, editText.getTextSize()); 
                      editor.putString(TEXT_VALUE_KEY, editText.getText().toString());
                      
                      //---saves the values---
                      editor.commit();      
                     
                      //---display file saved message---
                      Toast.makeText(getBaseContext(),
                          "Font size saved successfully!",
                          Toast.LENGTH_SHORT).show();
                  }
              });       
             
              //---load the SharedPreferences object---
              //SharedPreferences prefs= getSharedPreferences(prefName, MODE_PRIVATE);
              prefs = getPreferences(MODE_PRIVATE);
             
              //---set the TextView font size to the previously saved values---
              floatfontSize = prefs.getFloat(FONT_SIZE_KEY, 12);
             
              //---init the SeekBar and EditText---
              seekBar.setProgress((int) fontSize);
              editText.setText(prefs.getString(TEXT_VALUE_KEY, ""));
              editText.setTextSize(seekBar.getProgress());
             
              seekBar.setOnSeekBarChangeListener(newOnSeekBarChangeListener() {                           
                                          @Override
                                          public voidonStopTrackingTouch(SeekBar seekBar) {                                                                                           
                                          }
                                         
                                          @Override
                                          public voidonStartTrackingTouch(SeekBar seekBar) {                                           
                                          }
                                         
                                          @Override
                                          public voidonProgressChanged(SeekBar seekBar, intprogress,
                                                                  booleanfromUser) {
                                                      //---change the font size of the EditText---
                                                      editText.setTextSize(progress);
                                          }
                              });
          }
      }
      4.No need to modify Androidmanifest.xml
      5. Run the application on the Android Emulator/device.

      6. Enter some text into the EditText view and then change its font size by adjusting the SeekBar view (see Figure 2). Click Save.

      7. Press back button to kill the Activity/Application.Re invoke the application ,the application now displays the same text that you entered earlier using the same font size set earlier.

      How It Works
      To use the SharedPreferences object, you use the getSharedPreferences() method, passing it the name of the shared preferences file (in which all the data will be saved), as well as the mode in which it should be opened:
      private SharedPreferences prefs;
      ...
      //---get the SharedPreferences object---
      prefs = getSharedPreferences(prefName, MODE_PRIVATE);
      SharedPreferences.Editor editor = prefs.edit();

      The MODE_PRIVATE constant indicates that the shared preference file can only be opened by the application that created it. The Editor class allows you to save key/value pairs to the preferences file by exposing methods such as the following:
      ➤➤ putString()
      ➤➤ putBoolean()
      ➤➤ putLong()
      ➤➤ putInt()
      ➤➤ putFloat()
      When you are done saving the values, call the commit() method to save the changes:
      //---save the values in the EditText view to preferences---
      editor.putFloat(FONT_SIZE_KEY, editText.getTextSize());
      editor.putString(TEXT_VALUE_KEY, editText.getText().toString());
      //---saves the values---
      editor.commit();
      When the activity is loaded, you first obtain the SharedPreferences object and then retrieve all the values saved earlier:
      //---load the SharedPreferences object---
      SharedPreferences prefs = getSharedPreferences(prefName, MODE_PRIVATE);
      //---set the TextView font size to the previously saved values---
      float fontSize = prefs.getFloat(FONT_SIZE_KEY, 12);
      //---init the SeekBar and EditText---
      seekBar.setProgress((int) fontSize);
      editText.setText(prefs.getString(TEXT_VALUE_KEY, “”));
      editText.setTextSize(seekBar.getProgress());

      The shared preferences file is saved as an XML file in the /data/data/ <package_name> /shared_prefs folder (see Figure 3).
       
      Figure 3 DDMS perspective -File Explorer

      Its content is shown here (formatted for clarity):
      <?xml version='1.0' encoding='utf-8' standalone='yes' ?>
      <map>
      <string name="textvalue">SRM University this Sentence  is to be saved</string>
      <float name="fontsize" value="41.0" />
      </map>
      Using getPreferences()
      In the previous section, you used the used the SharedPreferences object by supplying it with a
      name, like this:
      //---get the SharedPreferences object---
      prefs = getSharedPreferences(prefName, MODE_PRIVATE);
      In this case, the information saved inside the SharedPreferences object is visible to all the activities within the same application. However, if you don’t need to share the data between activities, you  can use the getPreferences() method, like this:
      //---get the SharedPreferences object---

      prefs = getPreferences(MODE_PRIVATE);
      The getPreferences() method does not require a name, and the data saved is restricted to the activity that created it. In this case, the filename used for the preferences file will be named after the activity that created it (see Figure 6-4).The getPreferences() method does not require a name, and the data saved is restricted to the activity that created it. In this case, the filename used for the preferences file will be named after the activity that created it (see Figure 4).
       Figure 4 DDMS perspective -File Explorer


      Demikianlah Artikel Data storage -Shared preferences

      Sekianlah artikel Data storage -Shared preferences kali ini, mudah-mudahan bisa memberi manfaat untuk anda semua. baiklah, sampai jumpa di postingan artikel lainnya.

      Anda sekarang membaca artikel Data storage -Shared preferences dengan alamat link https://googleandroiddevelopertutorial.blogspot.com/2012/09/data-storage-shared-preferences.html

      Artikel Terkait

      Data storage -Shared preferences
      4/ 5
      Oleh

      Berlangganan

      Suka dengan artikel di atas? Silakan berlangganan gratis via email