Download Android Application Development Lecture 13

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts

Serializability wikipedia , lookup

DBase wikipedia , lookup

Microsoft Access wikipedia , lookup

IMDb wikipedia , lookup

Entity–attribute–value model wikipedia , lookup

Oracle Database wikipedia , lookup

Btrieve wikipedia , lookup

SQL wikipedia , lookup

Microsoft SQL Server wikipedia , lookup

Extensible Storage Engine wikipedia , lookup

Functional Database Model wikipedia , lookup

Open Database Connectivity wikipedia , lookup

Ingres (database) wikipedia , lookup

Concurrency control wikipedia , lookup

PL/SQL wikipedia , lookup

Database wikipedia , lookup

Versant Object Database wikipedia , lookup

Microsoft Jet Database Engine wikipedia , lookup

Relational model wikipedia , lookup

Clusterpoint wikipedia , lookup

ContactPoint wikipedia , lookup

Database model wikipedia , lookup

Transcript
Lecture 13
Android Application Development
Data Management
Instructor
Muhammad Owais
[email protected]
Cell: 03215500223
Saving Data
Options to save persistent application data:
[1] Shared Preferences:
Store private primitive data in key-value pairs.
[2] Internal Storage:
Store private data on the device memory.
[3] External Storage:
Store public data on the shared external storage.
[4] SQLite Databases:
Store structured data in a private database.
[5] Network Connection:
Store data on the web with your network server.
Storage Option
File
•
•
Represents a file system entity identified by a
pathname
Storage areas classified as internal or external
• Internal memory usually used for
application private files
• External memory used for public files
File Storage
File API
•
•
•
•
boolean isDirectory()
• Return true if this File represents a
directory
String getAbsolutePath()
• Returns the absolute path to this File
boolean setReadable(boolean readable)
• Sets read permission on this File
Many others. See documentation.
File Storage
Writing an Internal File
File Storage
// Open file. Get FileOutputStream
FileOutputStream fos =
openFileOutput(fileName, MODE_PRIVATE);
PrintWriter pw = new PrintWriter( new
BufferedWriter(new
OutputStreamWriter(fos)));
// Write to file
pw.println(…);
…
// Close file
pw.close();
Reading an Internal File
File Storage
// Open file. Get FileIntputStream
FileInputStream fis =
openFileInput(fileName);
BufferedReader fr = new BufferedReader( new
InputStreamReader(fis)));
// Read from file
String line=“ ”;
While( null! = (line=fr.readLine()) ) {
// Process data
}
// Close file
fr.close();
Cache File
File Storage
• Cache files are temporary files that may be deleted by
the system when storage is low
• File Context.getCacheDir()
• Returns absolute path to an application-specific
directory that can be used for temporary files
• Files removed when application uninstalled
External Memory Files
File Storage
• Removable media may appear/disappear without
warning
• String Environment.getExternalStorageState()
• MEDIA_MOUNTED - present & mounted with
read/write access
• MEDIA_MOUNTED_READ_ONLY - present & mounted
with read-only access
• MEDIA_REMOVED - not present
• Need permission to write external files
• <uses-permission android:name=
“android.permission.WRITE_EXTERNAL_STORAGE" />
External Memory Files (Code)
File Storage
private final String fileName = "myIcon.png";
@Override
public void onCreate(Bundle savedInstanceState) {
…
if (Environment.MEDIA_MOUNTED.equals(Environment
.getExternalStorageState())) {
File outFile = new File(
getExternalFilesDir(Environment.DIRECTORY_PICTURES
), fileName);
try {
BufferedOutputStream os = new
BufferedOutputStream( new
FileOutputStream(outFile));
BufferedInputStream is = new
BufferedInputStream(getResources()
.openRawResource(R.raw.icon));
copy(is, os); } catch (FileNotFoundException e) {
e.printStackTrace(); } } }
External Memory Files (Code…)
File Storage
private void copy(InputStream is, OutputStream os)
{
final byte[] buf = new byte[1024];
int numBytes;
try {
while (-1 != (numBytes = is.read(buf))) {
os.write(buf, 0, numBytes);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Saving Cache Files
File Storage
• Context.getExternalCacheDir() returns a File representing
external storage directory for cache files
• Files removed when application uninstalled
SharedPreferences
• A persistent map
• Holds key-value pairs of primitive data types
• Automatically managed across application uses
• Often used for long-term storage of customizable
application data such as user preferences, e.g.,
• User ID
• Favorite Wifi networks
Preferences
SharedPreferences
Preferences
SharedPreferences
Preferences
1. Preferences in Android are used to keep track of application
and user preferences.
2. In any application, there are default preferences that can
accessed through the PreferenceManagerinstance and its
related method getDefaultSharedPreferences(Context)
3. With the SharedPreferenceinstance one can retrieve the
intvalue of the any preference with the getInt(String key,
intdefVal).
4. In our case, we can modify the SharedPreferenceinstance in
our case using the edit()and use theputInt(String key,
intnewVal)
Activity SharedPreferences
•
•
Preferences
Activity.getPreferences (int mode)
•
Mode: MODE_PRIVATE,
•
MODE_WORLD_READABLE or
•
MODE_WORLD_WRITEABLE
Returns a SharedPreference object for the current Activity
Application SharedPreferences
•
Preferences
Context.getSharedPreferences (String name, int mode)
•
name – name of SharedPreference file
•
mode – MODE_PRIVATE,
MODE_WORLD_READABLE or
MODE_WORLD_WRITEABLE
•
Returns named SharedPreference object for this context
Writing SharedPreferences
• Call SharedPreferences.edit()
• Returns a SharedPreferences.Editor instance
• Add values with SharedPreferences.Editor
• Commit values with
• SharedPreferences.Editor.commit()
Preferences
Reading SharedPreferences
• Use SharedReferences methods, e.g.,
• getAll()
• getBoolean()
• getString()
Preferences
SharedPreferences
Preferences
public class SharedPreferenceReadWriteActivity extends
Activity{
private static String HIGH_SCORE = "high_score";
public void onCreate(Bundle savedInstanceState) {
…
final SharedPreferences prefs =
getPreferences(MODE_PRIVATE);
final TextView highScoreText = (TextView)
findViewById(R.id.highScoreTextView);
highScoreText.setText(String.valueOf(prefs.getInt(HIGH_SCO
RE, 0)));
final TextView playText = (TextView)
findViewById(R.id.textView2);
final Button go = …
public void onClick(View v) {
SharedPreferences
Preferences
public void onClick(View v) {
Random r = new Random();
int val= r.nextInt(1000);
playText.setText(String.valueOf(val));
if (val > prefs.getInt(HIGH_SCORE, 0)) {
highScoreText.setText(String.valueOf(val));
SharedPreferences.Editor editor = prefs.edit();
editor.putInt(HIGH_SCORE, val);
editor.commit();
}
}
SharedPreferences (Cont.)
Preferences
public class PreferencesActivityExample extends Activity {
SharedPreferences prefs;
final static String USERNAME = "uname";
public void onCreate(Bundle savedInstanceState) { …
prefs = PreferenceManager
.getDefaultSharedPreferences(this);
final Button button = …
public void onClick(View v) {
startActivity(new Intent(
PreferencesActivityExample.this,
LoadPreferencesActivity.class));
} });
}
SharedPreferences (Cont.)
Preferences
public class LoadPreferencesActivity extends PreferenceActivity
{
final SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(this);
addPreferencesFromResource(R.xml.user_prefs);
final EditTextPreference uNamePref = (EditTextPreference)
getPreferenceScreen() .findPreference(
PreferencesActivityExample.USERNAME);
uNamePref.setSummary(prefs.getString(PreferencesActivityEx
ample.USERNAME, ""));
prefs.registerOnSharedPreferenceChangeListener(new
OnSharedPreferenceChangeListener() {
@Override
public void onSharedPreferenceChanged(SharedPreferences
sharedPreferences,String key) {
uNamePref.setSummary(prefs.getString(PreferencesActivityEx
ample.USERNAME, ""));
}
}); } }
user_prefs.xml
Preferences
<PreferenceScreen
xmlns:android="http://schemas.android.com/apk/res/android"
android:key = "@+id/pref_screen">
<EditTextPreference
android:negativeButtonText="Cancel"
android:dialogMessage="Enter Your User Name"
android:dialogTitle="User Name"
android:positiveButtonText="Submit"
android:title="User Name"
android:key="uname">
</EditTextPreference>
</PreferenceScreen>
Preferences Activity
Preferences
• {Previous Code} Deprecated in API Level 11
• Now we use Fragments(Will discuss in Notifications)
SQLite
1. Saving Data into Database
a) Introduction to SQLite
b) SQLiteOpenHelper: Database Creation
c) CRUD [Create Read Update Delete]
2. Using a Pre-populated Database
3. Some optimizations
Database SQLite
Saving Data into a Database
Database SQLite
SQLite is a software library that implements SQL database engine
1. Self-contained:
Requires very minimal support from external libraries or from
the operating system. (well suited for embedded devices)
2. Serverless:
No separate server process like most SQL database implementations
(MySql, Oracle etc.). The process that wants to access the database reads
and writes directly from the database files on disk.
3. Zero-configuration:
Does not need to be "installed". There is no "setup" procedure. There is
no server process that needs to be started, stopped, or configured. No
need for an administrator to create a new database instance or assign
access permissions to users.
4. Transactional:
All changes and queries appear to be Atomic, Consistent, Isolated, and
Durable (ACID)
Saving Data into a Database
Database SQLite
Features:
1. Self-contained, Serverless, Zero-configuration and Transactional
2. A complete database is stored in a single cross-platform disk file.
3. Supports terabyte-sized databases and gigabyte-sized strings and blobs.
4. Small code footprint
5. Faster than popular client/server database engines for most operations.
6. Simple, easy to use API.
7. Written in ANSI-C.
8. Cross-platform: Unix (Linux, Mac OS-X, Android, iOS) and Windows
(Win32, WinCE, WinRT) are supported out of the box. Easy to port to
other systems.
9. Comes with a standalone command-line interface (CLI) client that can
be used to administer SQLite databases.
Saving Data into a Database
Basic database concepts:
1. What is SQL?
SQL stands for Structured Query Language
SQL lets you access and manipulate databases
2. What Can SQL do?
SQL can execute queries against a database
SQL can retrieve data from a database
SQL can insert records in a database
SQL can update records in a database
SQL can delete records from a database
SQL can create new databases
SQL can create new tables in a database
SQL can create stored procedures in a database
SQL can create views in a database
SQL can set permissions on tables, procedures, and views
Database SQLite
Saving Data into a Database
Database SQLite
3. Relational Database Management System (RDBMS)
1. RDBMS stands for Relational Database Management
System.
2. RDBMS is the basis for SQL, and for all modern
database systems such as MS SQL Server, IBM DB2,
Oracle, MySQL, Microsoft Access and SQLite.
3. The data in RDBMS is stored in database objects called
tables.
4. A table is a collection of related data entries and it
consists of columns and rows.
Saving Data into a Database
3. RDBMS Example
Database SQLite
Saving Data into a Database
3. RDBMS Example
Database SQLite
Saving Data into a Database
5. Database Operations
1. Database creation
2. Table(s) creation
3. Insert Record(s)
4. Update Record(s)
5. Delete Record(s)
6. Query
7. Drop Table(s)
8. Alter Table(s)
Database SQLite
6. SQL Commands
SELECT - extracts data from a database
UPDATE - updates data in a database
DELETE - deletes data from a database
INSERT INTO - inserts new data into a database
CREATE DATABASE - creates a new database
ALTER DATABASE - modifies a database
CREATE TABLE - creates a new table
ALTER TABLE - modifies a table
DROP TABLE - deletes a table
SQLite Android
Database SQLite
Table Creation
CREATE TABLE IF NOT EXISTS `employee` (
`EmployeeID` int(11) NOT NULL
AUTO_INCREMENT,
`Name` varchar(50) NOT NULL,
`Address` varchar(100) NOT NULL,
`PhoneNumber` varchar(11) NOT NULL,
`Designation` varchar(50) NOT NULL,
PRIMARY KEY (`EmployeeID`)
);
Database SQLite
Insert Record
INSERT INTO employee (EmployeeID, Name,
Address, PhoneNumber, Designation) VALUES
(NULL, 'Hasan', 'Mirpur, Dhaka', '01745534',
'Developer');
INSERT INTO employee (EmployeeID, Name,
Address, PhoneNumber, Designation) VALUES
(NULL, 'Rahim', 'Motijheel, Dhaka', '01956635',
'Designer');
Database SQLite
Query Record
Database SQLite
SELECT * FROM employee;
SELECT Name, Address FROM employee;
SELECT * FROM employee WHERE EmployeeID = 1;
SELECT * FROM employee WHERE Designation =
‘Developer’;
Saving Data into a Databases
SQLite in Android
Opening a Database
(Android code)
Database SQLite
public class DatabaseOpenHelper extends
SQLiteOpenHelper {
final private static String CREATE_CMD =
"CREATE TABLE artists (" +
DatabaseExampleActivity._ID + "
INTEGER PRIMARY KEY AUTOINCREMENT, "
+ DatabaseExampleActivity.ARTIST_NAME + "
TEXT NOT NULL)";
final private static String NAME = "artist_db";
final private static Integer VERSION = 1;
public DatabaseOpenHelper(Context context) {
super(context, NAME, null, VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_CMD); }
Using a Database
(Android code)
Database SQLite
public class DatabaseExampleActivity extends
ListActivity {
final static String TABLE_NAME = "artists";
final static String ARTIST_NAME = "name";
final static String _ID = "_id";
final static String[] columns = { _ID, ARTIST_NAME};
static SQLiteDatabase db = null;
Using a Database
(Android code)
Database SQLite
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
DatabaseOpenHelper dbHelper = new
DatabaseOpenHelper(this);
db = dbHelper.getWritableDatabase();
insertArtists();
// Sorry Lady Gaga :-(
deleteLadyGaga();
Cursor c = readArtists();
setListAdapter(new SimpleCursorAdapter(this,
R.layout.list_layout, c, columns, new
int[] { R.id._id, R.id.name }));
}
Using a Database
(Android code)
Database SQLite
private void insertArtists() {
ContentValues values = new ContentValues();
values.put(ARTIST_NAME, "Lady Gaga");
db.insert(TABLE_NAME, null, values);
values.clear();
values.put(ARTIST_NAME, "Johnny Cash");
db.insert(TABLE_NAME, null, values);
values.clear();
values.put(ARTIST_NAME, "Ludwig von
Beethoven");
db.insert(TABLE_NAME, null, values);
}
Using a Database
(Android code)
Database SQLite
private Cursor readArtists() {
return db.query(TABLE_NAME, columns,
null, new String[] {}, null, null, null);
}
private int deleteLadyGaga() {
return db.delete(TABLE_NAME,ARTIST_NAME+"=?",
new String [] {"Lady Gaga"});
}
Questions?