Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Android Application development training Day 4


Published on

  • Be the first to comment

  • Be the first to like this

Android Application development training Day 4

  1. 1. 1Day 4Session 1Here are the few basics of the Connecting your device with the server , or accessing the data over theinternet ..To access the data over the HTTP protocol here are the few things to follow 1) Open connection 2) Connect to the server 3) Send a request 4) Receive the Response Shown in the following fig Request Device Response Server (Client ) HTTP access on AndroidAvailable APIAndroid contains the standard Java network package which can be used to access networkresources. Android also contains the Apache HttpClient library.The base class for HTTP network access in the package is the HttpURLConnection class.The preferred way of accessing the Internet is the HttpURLConnection classRequired PermissionTo access the Internet your application requires the android.permission.INTERNET permission.To check the network state your application requires theandroid.permission.ACCESS_NETWORK_STATE permission.Here is the simple example to Retreive @COPYRIGHTS BY Dhiraj P. karalkar (
  2. 2. 2URL : here we have set the to fetch the dataHttpURLConnection : An URLConnection used to send and receive data over the web. Data may be ofany type and length. This class may be used to send and receive streaming data whose length is notknown in advance.Her e is the small code written to read the dataHere is an example for you to check the Network connectionClass that answers queries about the state of network connectivity. It also notifies applications whennetwork connectivity changes. Get an instance of this class by callingContext.getSystemService(Context.CONNECTIVITY_SERVICE). @COPYRIGHTS BY Dhiraj P. karalkar (
  3. 3. 3 Notification and AlertWhat are Notifications? The name itself implies their functionality. They are a way of alerting a userabout an event that he needs to be informed about or even take some action on getting that information.Notification on Android can be done in any of the following ways:  Status Bar Notification  Vibrate  Flash lights  Play a soundFrom the Notification, you can allow the user to launch a new activity as well. Now we will look at statusbar notification as this can be easily tested on the emulator.To create a status bar notification, you will need to use two classes: Notification andNotificationManager.  Notification – defines the properties of the status bar notification like the icon to display, the test to display when the notification first appears on the status bar and the time to display.  NotificationManager is an android system service that executes and manages all notifications. Hence you cannot create an instance of the NotificationManager but you can retrieve a reference to it by calling the getSystemService() method.Once you procure this handle, you invoke the notify() method on it by passing the notification objectcreated.So far, you have all the information to display on the status bar. However, when the user clicks thenotification icon on the status bar, what detailed information should you show the user? This is yet to becreated. This is done by calling the method setLatestEventInfo() on the notification object. What needs tobe passed to this method, we will see with an example.Step 1: Procure a handle to the NotificationManager:Step 2: Create a notification object along with properties to display on the status barStep 3: Add the details that need to get displayed when the user clicks on the notification. In this case, Ihave created an intent to invoke the browser to show the website @COPYRIGHTS BY Dhiraj P. karalkar (
  4. 4. 4Step 4: Now show the notificationStep 5: To clear the notification .Session 2 Android SQLite Database and ContentProviderThere are 4 ways of storing data on the android platform:  Preferences  SQLite Database  Files  Network  Content ProvidersPreferences –Basically used for storing user preferences for a single application or across applications for a mobile.This is typically name-value pairs accessible to the context.Databases –Android supports creating of databases based on SQLite db. Each database is private to the applicationsthat creates itFiles –Files can be directly stored on the mobile or on to an extended storage medium. By default otherapplications cannot access it.Network –Data can be stored and retrieved from the network too depending on the availability.Content Providers are the only way to share data across Android applications. They store and retrievedata thus making it accessible to all. Android platform provides default implementations of contentproviders for data types like audio, video, images, contact information etc.Here we are taking the example to store the Contact Using the content providerFor the native content providers, these unique URIs are declared as constants in an interface. So, in ourprogram we will be using constants like People.CONTENT_URI which internally translates tocontent://contacts/peopleLet us now look at the code to view all the existing contacts: @COPYRIGHTS BY Dhiraj P. karalkar (
  5. 5. 5Here we are using the Activity.managedQuery(..) to create and execute a query against the providedURI. The comments against the parameters in the code is self-explanatory. This returns a cursor objectthat can be iterated using the two methods moveToFirst() and moveToNext().Here we need to understand 2 new classes: ContentResolver and ContentValues.A ContentResolver provides applications access to the content data / model.We can get a handle to a ContentResolver by calling the getContentResolver() method within theActivity. This provides methods to insert, update and delete data. In order to insert data, we need to provide it through a ContentValues object. A ContentValues Objectis nothing but a name, value pair where the name of the column is to be mentioned. So, we pass the URIand the ContentValues to insert() method which returns a unique URI with the new ID created.Once we get the ID of the new person/contact inserted, we insert his/her mobile phone details into therelated Phones table by using the returned insertUri.The insertUri which is unique to the new record is stored as a class variable to use it in the deletemethod later. The phoneUri is also stored for updating the same in the updateContact() method later. @COPYRIGHTS BY Dhiraj P. karalkar (
  6. 6. 6These methods only manipulate the freshly created record, for simplicity sake. They call upon theupdate() and delete() method on the ContentResolver.Please note that you must add the following permissions to the AndroidManifest.xml file to be able toaccess the contacts. SQLite DB In AndroidIf an application wants to store and retrieve data for its own use, without having to share the dataacross applications, it can access the SQLite DB directlyIn this example, we will do the following: o Create a database (typically a one time activity) o Create a table (typically a one time activity) o Insert values into the table o Retrieve the values from the table o Display the retrieved values as a List view o Delete all the records from the table before closing the connection to the databaseStep 1: Create a database @COPYRIGHTS BY Dhiraj P. karalkar (
  7. 7. 7This opens a database defined in the constant SAMPLE_DB_NAME, if it already exists. Else it creates adatabase and opens it.The second parameter is operating mode : MODE_PRIVATE meaning it is accessible to only this context.The other modes are and MODE_WORLD_WRITABLE. MODE_WORLD_READABLEStep 2: Create a Table:Here we are creating the tableExecute a single SQL statement that is NOT a SELECT or any other SQL statement that returns data.Step 3: Insert values into the table:Step 4: Retrieve valuesStep 5: Display the values as a listStpe 6: Delete the values from the tableIn this example we are using the list activity as the extended class , and displaying the added values intothe listview @COPYRIGHTS BY Dhiraj P. karalkar (
  8. 8. 8 Preferences In AndroidPreferences are typically name value pairs. They can be stored as “Shared Preferences” across variousactivities in an application (note currently it cannot be shared across processes). Or it can be somethingthat needs to be stored specific to an activity. One can store the objects in the preferences of any type .The context object lets you retrieve SharedPreferences through the methodContext.getSharedPreferences()In this example , we are adding two string values in the SharedPreferenceActivity and retrieving thesame in the ViewSharedPrefsFirst, we obtain a SharedPreferences object making it readable by all. The first parameter is a name of afile that stores my preferences. This automatically creates the xml file if it does not exist and then storesin the same.Create a new Editor for these preferences, through which you can make modifications to the data in thepreferences and atomically commit those changes back to the SharedPreferences object.We are adding the string into the shared preferences and commit them shown belowTo retrieve the shared preference data we are using preference object here and getString(..)To get the data @COPYRIGHTS BY Dhiraj P. karalkar (
  9. 9. 9Session 3 File Handling in AndroidAccess to the file system is performed via the standard classes.Android provides also helper classes for creating and accessing new files and directories.For example the getDir(String, int) method would create or access a directory.The openFileInput(String s) method would open a file for input and openFileOutput(String s, int)would create a file.The permission require for the file handling are  MODE_PRIVATE - No access for other applications  MODE_WORLD_READABLE - Read access for other applications  MODE_WORLD_WRITABLE - Write access for other applications  MODE_WORLD_READABLE | MODE_WORLD_WRITABLE - Read / Write accessHere is the small example to create a directory , create a file , write data in to the file and read the dataGets the Android external storage directory or create a directory using getExternalStorageState(). @COPYRIGHTS BY Dhiraj P. karalkar (
  10. 10. 10We are getting the absolute path of the directory using the folder.getabsolutepath() and creating thenew file in the directory by createNewFile()Now write the data into the same fileTo read the data here is the sourceNote : in this example we are creating dhiraj.txt file in the karalkar directoryIn the same way one can create any type of file in the file system @COPYRIGHTS BY Dhiraj P. karalkar (