Wednesday, June 26, 2013

Android App Development notes 3

DataStorage:
   persistent storage of data

persistent storage:
  1)Shared preferences- stores key value pair in xml
            can save states of UI or UI data   
            Limit:Only primitive datatypes [booleans,floats,ints,
                            longs and strings]
            getSharedPreferences(filename,mode)->can be shared by other activities & and other activities
            getPreferences()->cant be used by other activities

    Ex:read from the preferences:
    SharedPreferences prefs = getSharedPreferences("UserFilename",0);
    boolean bSignIn = prefs.getBoolean("staySignIn",false);//false is the default value if the value doesnt exist

    write to preferences:
    onStop() fn:
    SharedPreferences prefs = getSharedPreferences("UserFilename",0);
    prefs.putBoolean("staySignIn",bSignIn);
    prefs.commit();//To store the value
   
    xml file path:data/data/com.app/shared_prefs/UserFilename.xml
    once we uninstall application, shared_preferences file will be deleted.
  2)Internal Storage
    -Save files directly on the device's internal storage

  3)External storage
   
  4)SQLite databases
    Helper classes: SQLiteOpenHelper,SQLiteDatabase,Cursor
    Any DB
    4.1) Create DB
    4.2) Create table with schema
    4.3)Insert,Update,Delete,query
   
       4.1,4,2 can be performed by SQLiteOpnenHelper class
       4.3 can be performed by SQLiteDatabase class    

  It will create data/data/com.app/shared_prefs/UserFilename.db. we can pull it from device
and can see the data using any SqlReader.




ContentProviders -required to make your DB as public
         -access to contacts possible by contacts contentprovider

Implement new content provider:
=================================
  1) set up system for storing the data with SQLiteOpenHelper & SQLiteDatabase to manage DB operations
  2) Extend the ContentProvider class to provide access to the data
  3) Declare the contentprovider in AndroidManifest.xml


  ContentProvider implementor, ContentProvider client

  ContentProvider client refer via Content URI. Ex "content://contacts/people"


 content://com.example.transportationprovider/trains/122


 content://-standard prefix
 com.example.transportationprovider - authority part of URI, identity of DB, it identified the content provider
 trains - identifier of table name
 122 - rowid of the table

  Declare the contentprovider in AndroidManifest.xml:
    <provide name= "TransportationProvider" authorities="com.example.transportationprovider" ... >


Ex:
    android.provider.ContactsContract.Contacts.CONTENT_URI

ContentProvider must implement
  1)query(Uri...) - From this URI, it has to identify which table client requires...
  2)Insert()
  3)update()
  4)delete()
  5)getType()
  6)onCreate()


ContentProvider client use ContentResolver class.

    ContentResolver cr = getContentResolver();
        cr.query(CONTENT_URI,...);
    cr.insert(CONTENT_URI...);
 
From CONTENT_URI's authority, it will find out which class & perform query() or insert()... operations.




Querying a contentprovider:

For querying a contentprovider, ContentProvider Client requires 3 information;
   1)what is the content_URI of ContentProvider
   2)Column names of ContentProvider
   3)what are all the datatypes of ContentProvider
    so that he can decide whether to use cursor.getString or cursor.getInt() or cursort.getBoolean()

   1) ContentResolver.query()
   2) Activity.managedQuery()
    - Best practice is invoking managedQuery() from Activity. so that cursor will be aligned to
      lifecycle of an activity

Uri insertedRowIdUri=  contentResolver.insert()//returns the URi of row id

To delete the row,
    contentResolver.delete(rowIdUri)
Delete multiple rows:
    contentResolver.delete(condition);

 
MediaStore is a content provider to acccess multimedia.


SQLiteDatabase.query() has where class and selectionArgs;

we can give our conditions like this in where clause;
   

    String where = "username='sundar'";
              or
        String where = "username='" + stringSundar+"'";
   
If we have multipe where conditions, do the following:
    String where = "username=? AND password=?";
        String selectionArgs[] = {"sundar","password"};

& pass it in query( ...where,selectionArgs...);





Security in Android:
  1) it is above Linux. it has all features like one process cannot access another process's memory
  2) permissions {READ_CONTACTS, internet  permission};
        while instlallation, if that application is using CONTACTS or
        when we allow, the permission is granted and APK will be installed.
        permission is granted during installation time by package installer.
        uses_permission tag.
        we can also create new permissions using permission tag.

  3) Every Android App. should be signed with digital certificate
        [Application signing is must]
 

How to sign the application in Android:
1) we can create our own digital certificate [self signed certificate]
2) Normal application is certified with debug certificate.
   otherwise it wont run in emulator
3)To release it in google playstore, we should not use debug certificate.

    3.1)Create private and public key [keystore]
        3.2)sign application with certificate
   
   
   
 
 

if we want to make my activity public, we have to declare IntentFilter for that activity.

<activity name ="sundar">
  <Intent-Filter>
    <action name = "com.sundar.app.sundar">
    <category    = DEFAULT> //without DEFAULT category it is not working.
    <data>


if anyone trigger/send this action "com.sundar.app.sundar", the activity "sundar" will be launched.


permission = normal -> autogranted during installation
             dangerous ->request the user response while installation
         Signature -> if two activities have the same certificate,one activity can access another activity
              or the inbuilt application.
             secure system functions, our activity, service,contentprovider and broadcast receiver by
             including android:permission attribute.
      

   
          
Sign certificate in the application:
 1) File->export->Export Android Application->Select the application
 2) select create new keystore 

if my application validity will expire tomorrow, what will happen if I installed my application today ? will it run
or it wont run?

Android application validity,
Multiple applications can have the same keystore.
Certificate validity is checked at the time of installation only. not every time it is running.
So if I have installed today, it will run fine tomorrow also. Tomorrow if any device is trying to install
it, it wont install because of validity expiration.



if we have not added uses-permission for reading contacts, if we try to read contacts,
it will give security exception and show force close dialog.


How to secure public activity:
==============================
    using permissions.
Server application has to create the permission using permission tag to allow access the activity.
Client application should use uses-permission tag to launch the server application's activity.

       



While creating the permission, the user should add it as signature level permission. so that the created permission
can be accessed


Resources:
============   
     7 primary resource types;
    1) Simple values - /res/values/
             - R.<resource type>.<name of resource>

        Externalizing strings helps to localize it    
        Reuse it easily
               

    2) Drawables -   
        3) Layouts
        4) Animations
    5) Menu
    6) Styles
    7) Raw
    8) XML

    Resource files should contain lowercase letters,numbers,peroids(.) and underscores (_).

    Resource inside resource access can be done by     @<ResourceType>/<ResourceName>.


Animation:
===========
    1)Tweened animation
        -ops:rotate,stretch,move,fade
    2)Frame animation-> sequence of animations in order


Menu XMLs can be loaded by MenuInflater class.



Resources:
=============

ResourceType ResourceName


filename as resourceName
 layout
 drawable
 menu
 animation

name as resourcename
  string
  color
  dimen
  styles


Resources can be accessed by
  1) R.in java code
  2) in XML
        @<resourceType>/<ResourceName>


AAPT will create R class.

 For each resource type, there is a subclass in  R class.

  Syntax:[packagename.]R.<resource_type>.<resource_name>


Resource res = getResources() //get resources object

String[] planets= res.getStringArray(R.array.planets_array);
String title    = res.getText(R.string.main_title);



if we are using resource in another resource,

    syntax:@[packagename:]resourceType.resourceName

Native resources can be found from android.R class.

Localization:
    res/values/strings.xml
    res/values-fr/strings.xml
    res/values-fr-rCA/strings.xml



 
     

   

     

No comments: