android storage pdf by apk855

VIEWS: 13 PAGES: 16

More Info
									                 Data Storage


                          Copyright © 2012,apkdownloads.inl. All rights
DATA STORAGE-1
                                                             reserved
    • Android provides you a several options for saving
      and storing the application data.
    • It always depends whether your data should be
      visible to the other applications or private to your
      own application
    • Persisting data is an important topic in application
      development, as users expect to reuse the data
      sometime at a later stage.
    • For Android, there are primarily three basic ways of
      persisting data:
          Shared Preferences
          Traditional file systems.
          A relational database management system through the
           support of SQLite databases.
                                           Copyright © 2012,apkdownloads.inl. All rights
DATA STORAGE-2
                                                                              reserved
                        Shared 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 fi le, but you
    • have to perform some fi le management routines, such as
      writing the data to the fi le, 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 fi le
      becomes more onerous.
                                            Copyright © 2012,apkdownloads.inl. All rights
DATA STORAGE-3
                                                                               reserved
    • 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 it and its value will be saved
      automatically to an XML file for you.
    • To create the shared preferences use the following
      method.
          getSharedPreference(String name,int mode);
    • For Example:
         SharedPreference sp=getSharedPreference(“preferences”,0)
         0 – operating mode for the default operations.

                                               Copyright © 2012,apkdownloads.inl. All rights
DATA STORAGE-4
                                                                                  reserved
    • Get an editor for the SharedPreferences by using the
      following code.
          SharedPreferences.Editor spedit=sp.edit();
    • Put the key /value pair in spedit by using putString()
      method.
          spedit.putString(“username”, uname);
          spedit.putString(“password”, pwd);
    • After that commit()
          spedit.commit();
    • For getting he values stored on SharedPreferences
      use getString(String key,String msg) method.
    • Here the key specifies the key value given in the
      setString() method.
    • The msg specifies the alternative message if it is not
      finding the specified key.
                                                 Copyright © 2012,apkdownloads.inl. All rights
DATA STORAGE-5
                                                                                    reserved
                             Internal Storage

    • You can save files directly on the device's internal
      storage.
    • By default, files saved to the internal storage are
      private to your application and other applications
      cannot access them (nor can the user).
    • When the user uninstalls your application, these
      files are removed.
    • We make use of the File I/O for performing the read
      and write operations.
    • To Write an example program:
          We take one EditText to enter a String .
          If we want to store the entered String by writing it to a file
           we follow the steps.

                                                  Copyright © 2012,apkdownloads.inl. All rights
DATA STORAGE-6
                                                                                     reserved
    • First read the entered Text by using the following
      statement.
         • String str = textBox.getText().toString();
    • Write this string to a file by using the following code
         FileOutputStream fOut =openFileOutput(“textfile.txt”,
                                MODE_WORLD_READABLE);
         OutputStreamWriter osw = new OutputStreamWriter(fOut);
         //---write the string to the file---
         osw.write(str);
         osw.flush();
         osw.close();
         //---display file saved message---
         Toast.makeText(getBaseContext(),“File saved successfully!”,
                                Toast.LENGTH_SHORT).show();
         //---clears the EditText---
         textBox.setText(“”);
         }

                                                        Copyright © 2012,apkdownloads.inl. All rights
DATA STORAGE-7
                                                                                           reserved
    • For reading the file data use the following code:
         FileInputStream fIn = openFileInput(“textfile.txt”);
         InputStreamReader isr = new InputStreamReader(fIn);
         char[] inputBuffer = new char[READ_BLOCK_SIZE];
         String s = “”;
         int charRead;
         while ((charRead = isr.read(inputBuffer))>0)
         {
         //---convert the chars to a String---
         String readString =
         String.copyValueOf(inputBuffer, 0,charRead);
         s += readString;
         inputBuffer = new char[READ_BLOCK_SIZE];


                                                Copyright © 2012,apkdownloads.inl. All rights
DATA STORAGE-8
                                                                                   reserved
         }
         //---set the EditText to the text that has been
         // read---
         textBox.setText(s);
         Toast.makeText(getBaseContext(), “File loaded successfully!”,
                                    Toast.LENGTH_SHORT ).show();
         }




                                                           Copyright © 2012,apkdownloads.inl. All rights
DATA STORAGE-9
                                                                                              reserved
                     External Storage (SD CARD)
    • The previous programs explained you to store the data in
      the form of files as internal storage.
    • Some times, it will be very useful to store the data in the
      form of files as external storage. i.e. in permanent
      memory i.e. in SD card.
    • We use the same File I/O to perform the operations.
    • But the file we save it to the SD CARD location.
         File myFile = new File("/sdcard/mysdfile.txt");
         myFile.createNewFile();
         FileOutputStream fOut = new FileOutputStream(myFile);
         OutputStreamWriter            myOutWriter       =                       new
            OutputStreamWriter(fOut);

         myOutWriter.append(txtData.getText());
         myOutWriter.close();
         fOut.close();
         Toast.makeText(getBaseContext(),"Done         writing                     SD
            'mysdfile.txt'",Toast.LENGTH_SHORT).show();
         txtData.setText("");
                                                  Copyright © 2012,apkdownloads.inl. All rights
DATA STORAGE-10
                                                                                     reserved
                                SQLite Database
     • All the previous techniques explains you to store the
       data by using the traditional data storage
       mechanisms.
     • Android supports a relational database. i.e. SQLite.
     • The database that you create for an application is
       only accessible to itself, other applications will not
       access it.
     • By using SQLite database, we can do the following
       tasks:
             We can create or open a database.
             We can create the table.
             We can insert the values in the table.
             We can retrieve the records.
             We can update the records.
             We can delete the records.
                                                       Copyright © 2012,apkdownloads.inl. All rights
DATA STORAGE-11
                                                                                          reserved
    • For working with the SQLite Database we use the
      following class.
         android.database.sqlite.SQLiteDatabase;
          Use the following code to create the Database reference
         SQLiteDatabase db=null;
          Use the following method to or open the database
         openOrCreateDatabase(String dbname, int mode, null);
          For Example:
         openOrCreateDatabase(“mydb”,MODE_PRIVATE,null);
          We use the execSQL(String query) method for executing the
           following SQL statements.
              —   create
              —   insert
              —   update
              —   delete
                                               Copyright © 2012,apkdownloads.inl. All rights
DATA STORAGE-12
                                                                                  reserved
   Example:
     db.execSQL(“insert into student values(‘abc’,’123’)”);
   • For retrieving the records from the table we use the
     following method.
     query(String table, String[] columns, String selection, Str
     ing[] selectionArgs, String groupBy, String having, String
     orderBy)

        Parameter   Description
        Columns     A list of which columns to return. Passing null will return all
                    columns, which is discouraged to prevent reading data from
                    storage that isn't going to be used.
        selection   A filter declaring which rows to return, formatted as an SQL
                    WHERE clause (excluding the WHERE itself). Passing null will
                    return all rows for the given table.
                                                            Copyright © 2012,apkdownloads.inl. All rights
DATA STORAGE-13
                                                                                               reserved
    Parameter       Description
    selectionArgs   You may include ?s in selection, which will be replaced by
                    the values from selectionArgs, in order that they appear in
                    the selection. The values will be bound as Strings.
    groupBy         A filter declaring how to group rows, formatted as an SQL
                    GROUP BY clause (excluding the GROUP BY itself). Passing
                    null will cause the rows to not be grouped.
    Having          A filter declare which row groups to include in the cursor, if
                    row grouping is being used, formatted as an SQL HAVING
                    clause (excluding the HAVING itself). Passing null will cause
                    all row groups to be included, and is required when row
                    grouping is not being used
    orderBy         How to order the rows, formatted as an SQL ORDER BY
                    clause (excluding the ORDER BY itself). Passing null will use
                    the default sort order, which may be unordered.

                                                     Copyright © 2012,apkdownloads.inl. All rights
DATA STORAGE-14
                                                                                        reserved
   Example:
       SQLiteDatabase mydb=null;
       mydb=openOrCreateDatabase(“sudentdb,MODE_PRIVATE, null);
       myDB.execSQL("CREATE TABLE IF NOT EXISTS "
                       + “ studentdetials”
                       + " (LastName VARCHAR, FirstName VARCHAR,"
                       + " Country VARCHAR, Age INT(3));");
       myDB.execSQL("INSERT INTO "
           + MY_DATABASE_TABLE
           + " (LastName, FirstName, Country, Age)"
           + VALUES ('suresh', 'gandham', 'india', 28);");
       String []columns = {"LastName", "FirstName", "Country", "Age"};
       Cursor c = myDB.query(MY_DATABASE_TABLE,columns,null,null,null,null,null);
   •   Here the Cursor object is used to read the details retrieved by the query() method.
   •   The results are retrieved as result set.
   •   Cursor object is used to retrieve the results.
   •   By default Cursor object reference points to the row before the first row.

                                                             Copyright © 2012,apkdownloads.inl. All rights
DATA STORAGE-15
                                                                                                reserved
    • To make the Cursor object to point to the first row,
      we use the following method.
          c.moveToFirst();
          This method returns false if the cursor is empty.
    • To check whether any other record is existing in the
      table we use the following method.
          c.moveToNext();
          This method returns false if there in no next record.
    • To close the db connection we use the following
      method.
          db.close();




                                                  Copyright © 2012,apkdownloads.inl. All rights
DATA STORAGE-16
                                                                                     reserved

								
To top