If you can't read please download the document
Upload
vivek-bhusal
View
1.362
Download
1
Embed Size (px)
Citation preview
Android Apps Development TrainingDay 4
Android Storage
How do you save your application data ?SharedPreferences*Storage in key-value pairs.
Internal StorageStorage on device memory
External StorageStorage on shared external storage
SQLite Databases*Store structured data in a private database
Network ConnectionsStore data on web
SharedPreferences
The way android stores users preferences
But why SharedPreferences ? Ease of implementation
Faster in terms of coding
Accessibility of key values
Suitable for the small thingse.g. Game difficulty level, user name, user accounts, etc.
I got your back buddy !
SharedPreferences
Every thing is saved in terms of key-valuee.g. NAME, AndroidPhoneNumber, 1234
For the implementation we will be using the:SharedPreferencesGeneral framework to save and retrieve persistent key-value pairs
EditorInterface used for modifying values in a SharedPreferences object
Use of commit() or apply() to make changes persist
Implementation
public class ProjectPreference{SharedPreferences pref;Editor editor;Context _context;int PRIVATE_MODE = 0;private static final String PREF_NAME = prefmyapp;... (A)public ProjectPreference(Context context){this._context = context;pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);editor = pref.edit();
} ... (B)
Accessing the SharedPreferences thisway gives you more flexibilityWe are creating a separate class here
A: Define Variables
Suppose we have a contact to save:Name
Address
Number
Declare them:public static final String KEY_NAME = name;public static final String KEY_ADD = address;public static final String KEY_NUM = number;
B: Define Getters and Setters
Defining setters and gettersvoid for setterspublic void setName(String key, String value){editor.putString(key, value);editor.commit();
}
for getters public String getName(String key){return pref.getString(key, );
}
You candefine your defaultvalues here
Accessing SharedPreferences
Create an objectProjectPreference SM;
InitializeSM = new ProjectPreference(Class.this);
Access variables and methodsSM.getName(SM.KEY_NAME);
Set valuesSM.setName(SM.KEY_NAME, Android);
Building the application
SQLite Database
SQLite is innate in every Android deviceNo need for extra setup etc.
We only have to define the SQL statements for creating and updating the database
All commands regarding creating tables, inserting values etc. are the same as in SQL
SharedPreferenes
VS
SQLite
SQLite provides capability of more complex storageStorage for large number of data
Higher capabilitiese.g. in the loadshedding app we notice that we do not have to update the app every time a new schedule arrives.
SQLite in Android
Android should use a DBHelperextends SQLiteOpenHelper classTwo main methods:onCreate()Creates the database, parameters needed:DATABASE_NAME
DATABASE_VERSION
onUpgrade()Updates the current database depending upon:DATABASE_VERSION
All operations regarding the database is to be performed by the SQLiteDatabase object
Either the:getWritableDatabase() : Write mode
getReadableDatabase() : Read mode
used with the SQLiteDatabase object. SQLiteDatabase db = this.getWritableDatabase()db.insert(...)
While using the SELECT operations we use the Cursor objectCursor is something similar to an iteratorif(cursor.moveToFirst()){do { } while(cursor.moveToLast())
}
Also during the query we use a rawQuery() method
In insert operations we use the ContentValues object.ContentValues values = new ContentValues( );values.put("name" , "ABC");values.put("phoneNumber" , "123");db.insert(table, null, values);
While programming create the following functions:Getting a single row
Getting all rows
Getting row count
Updating row
Deleting row
For better SQLite implementation
Create both:Data Model classWith all the setters and getters
Data HandlerExtending the SQLiteOpenHelper
Implementing SQLite
Insert userdata intodatabaseRedirect user into another activityshowing the database
AsyncTask
What is threading ?The way any computing device responds to its commands
Android only uses a main thread by default for its application
The main thread processes the following:Application UI
User inputs to the application
Is this enough?
While processing heavy/ time consuming task, the UI will freeze until the task is completeBad practice
For these tasks open a separate threadASYNCTASK
Asynctask is android's multitasker
Methods inside the AsyncTaskOnPreExecute()Generally used to load the progress bar
doInBackground(Params... )All the logic is dumped here
OnProgressUpdate()Called when publishProgress() is called in the doInBackground()
onPostExecute(Result)Gives out the desired result
Using the AsyncTaskExtend the AsyncTaskclass Abc extends AsyncTaskParams: the input, what you pass into the AsyncTask
Progress: on updates, passed to onProgressUpdate()
Result: the output from doInBackground() returned to the onPostExecute()
Call on the AsyncTasknew Abc.execute(Params);