Important Announcement
PubHTML5 Scheduled Server Maintenance on (GMT) Sunday, June 26th, 2:00 am - 8:00 am.
PubHTML5 site will be inoperative during the times indicated!

Home Explore CU-MCA-SEM-VI-Advanced mobile application development

CU-MCA-SEM-VI-Advanced mobile application development

Published by Teamlease Edtech Ltd (Amita Chitroda), 2021-11-02 12:53:52

Description: CU-MCA-SEM-VI-Advanced mobile application development

Search

Read the Text Version

UNIT - 4: DATA STORAGE STRUCTURE 4 Learning Objectives 4.11 Introduction 4.12Internal Storage 4.13 External Storage 4.14 Adapters 4.15 Array Adapter in Android 4.16 Base Adapter List View 4.17 List View and List Activity 4.18 Custom List View 4.19 Grid View Using Adapter 4.20 Gallery using Adapter 4.21 Summary 4.22 Keywords 4.23 Learning Activity 4.24 Unit End Questions 4.25 References 4.0 LEARNING OBJECTIVES After studying this unit, you will be able to:  Describe the internal and external storage of Android  Accessing files on external storage  Use adapter for different type of view in Android  Explain the importance of adapter in Android  Create different activity using adapter 4.1 INTRODUCTION Android provides several options for you to save persistent application data. The solution you choose depends on your specific needs, such as whether the data should be private to your application or accessible to other applications (and the user) and how much space your data requires. Your data storage options are the following:  Shared Preferences 51 CU IDOL SELF LEARNING MATERIAL (SLM)

Store private primitive data in key-value pairs.  Internal Storage Store private data on the device memory.  External Storage Store public data on the shared external storage.  SQLite Databases Store structured data in a private database.  Network Connection Store data on the web with your own network server. Android provides a way for you to expose even your private data to other applications — with a content provider. A content provider is an optional component that exposes read/write access to your application data, subject to whatever restrictions you want to impose. 4.2 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. To create and write a private file to the internal storage: 1. Call openFileOutput()with the name of the file and the operating mode. This returns a FileOutputStream. 2. Write to the file with write(). 3. Close the stream with close(). For example: String FILENAME = \"hello_file\"; String string = \"hello world!\"; FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE); fos.write(string.getBytes()); fos.close(); To read a file from internal storage: 1. Call openFileInput()and pass it the name of the file to read. This returns a FileInputStream. 52 CU IDOL SELF LEARNING MATERIAL (SLM)

2. Read bytes from the file with read(). 3. Then close the stream with close(). Other useful methods : getFilesDir() Gets the absolute path to the filesystem directory where your internal files are saved. getDir() Creates (or opens an existing) directory within your internal storage space. deleteFile() Deletes a file saved on the internal storage. fileList() Returns an array of files currently saved by your application. Modes of Internal Storage 1. MODE_PRIVATE — In private mode the data stored earlier is always overridden by the current data i.e every time you try to commit a new write to a file which removes or override the previous content. We have used MODE_PRIVATE in the example at the end of this article. 2. MODE_APPEND — In this mode the data is append to the existing content i.e keep adding data. 4.3 EXTERNAL STORAGE Every Android-compatible device supports a shared “external storage” that you can use to save files. This can be a removable storage media (such as an SD card) or an internal (non- removable) storage. Files saved to the external storage are world-readable and can be modified by the user when they enable USB mass storage to transfer files on a computer. External files can disappear if the user mounts the external storage on a computer or removes the media, and there’s no security enforced upon files you save to the external storage. All applications can read and write files placed on the external storage and the user can remove them. Accessing files on external storage: If you’re using API Level 8 or greater, use getExternalFilesDir()to open a Filethat represents the external storage directory where you should save your files. This method takes a typeparameter that specifies the type of subdirectory you want, such asDIRECTORY_MUSICand DIRECTORY_RINGTONES(pass nullto receive the root of your application’s file directory). This method will create the appropriate directory if necessary. By specifying the type of directory, you ensure that the Android’s media scanner 53 CU IDOL SELF LEARNING MATERIAL (SLM)

will properly categorize your files in the system (for example, ringtones are identified as ringtones and not music). If the user uninstalls your application, this directory and all its contents will be deleted. If you’re using API Level 7 or lower, use getExternalStorageDirectory(), to open a Filerepresenting the root of the external storage. You should then write your data in the following directory: /Android/data/<package_name>/files/ The <package_name>is your Java-style package name, such as “com.example.android.app“. If the user’s device is running API Level 8 or greater and they uninstall your application, this directory and all its contents will be deleted. 4.4 ADAPTERS  In Android, Adapter is a bridge between UI component and data source that helps us to fill data in UI component.  It holds the data and send the data to an Adapter view then view can takes the data from the adapter view and shows the data on different views like as ListView, GridView, and Spinner etc.  For more customization in Views we uses the base adapter or custom adapters.  To fill data in a list or a grid we need to implement Adapter.  Adapter’s acts like a bridge between UI component and data source. Here data source is the source from where we get the data and UI components are list or grid items in which we want to display that data. 54 CU IDOL SELF LEARNING MATERIAL (SLM)

There are the some commonly used Adapter in Android used to fill the data in the UI components. BaseAdapter – It is parent adapter for all other adapters ArrayAdapter – It is used whenever we have a list of single items which is backed by an array Custom ArrayAdapter – It is used whenever we need to display a custom list SimpleAdapter – It is an easy adapter to map static data to views defined in your XML file Custom SimpleAdapter – It is used whenever we need to display a customized list and needed to access the child items of the list or grid. 4.5 ARRAYADAPTER IN ANDROID  Whenever we have a list of single items which is backed by an Array, we can use ArrayAdapter. For instance, list of phone contacts, countries or names.  Here is how android ArrayAdapter looks : ArrayAdapter(Context context, int resource, int textViewResourceId, T[] objects)  Custom ArrayAdapter In Android: ArrayAdapter is also an implementation of BaseAdapter, so if we want more customization then we can create a custom adapter and extend ArrayAdapter in that Since array adapter is an implementation of BaseAdapter, so we can override all the function’s of BaseAdapter in our custom adapter. 55 CU IDOL SELF LEARNING MATERIAL (SLM)

Below Custom adapter class MyAdapter extends ArrayAdapter in that: public class MyAdapter extends ArrayAdapter { public MyAdapter(Context context, int resource, int textViewResourceId, List objects) { super(context, resource, textViewResourceId, objects); } @Override public int getCount() { return super.getCount(); } @Override public View getView(int position, View convertView, ViewGroup parent) { return super.getView(position, convertView, parent); } } 4.6 BASE ADAPTERS LIST VIEW  BaseAdapter is a common base class of a general implementation of an Adapter that can be used in ListView, GridView, Spinner etc.  Whenever we need a customized list in a ListView or customized grids in a GridView we create our own adapter and extend base adapter in that.  Base Adapter can be extended to create a custom Adapter for displaying a custom list item. ArrayAdapter is also an implementation of BaseAdapter.  Example : public class CustomAdapter extends BaseAdapter { @Override public int getCount() { return 0; } @Override 56 public Object getItem(int i) { CU IDOL SELF LEARNING MATERIAL (SLM)

return null; } @Override public long getItemId(int i) { return 0; } @Override public View getView(int i, View view, ViewGroup viewGroup) { return null; } 4.7 LIST VIEW AND LIST ACTIVITY  Android ListView is a view which contains the group of items and displays in a scrollable list. ListView is implemented by importing android.widget.ListView class. ListView is a default scrollable which does not use other scroll view.  ListView uses Adapter classes which add the content from data source (such as string array, array, database etc) to ListView. Adapter bridges data between an AdapterViews and other Views (ListView, ScrollView etc). ListView Attributes Following are the important attributes specific to GridView Sr.No Attribute & Description 1 android:id This is the ID which uniquely identifies the layout. 2 android:divider This is drawable or color to draw between list items. 3 android:dividerHeight This specifies height of the divider. This could be in px, dp, sp, in, or mm. 4 android:entries Specifies the reference to an array resource that will populate the ListView. 57 CU IDOL SELF LEARNING MATERIAL (SLM)

5 android:footerDividersEnabled When set to false, the ListView will not draw the divider before each footer view. The default value is true. 6 android:headerDividersEnabled When set to false, the ListView will not draw the divider after each header view. The default value is true. List Activity Following is the content of the modified main activity file src/com.example.ListDisplay/ListDisplay.java. This file can include each of the fundamental life cycle methods. package com.example.ListDisplay; import android.os.Bundle; import android.app.Activity; import android.view.Menu; import android.widget.ArrayAdapter; import android.widget.ListView; public class ListDisplay extends Activity { // Array of strings... String[] mobileArray = {\"Android\",\"IPhone\",\"WindowsMobile\",\"Blackberry\", \"WebOS\",\"Ubuntu\",\"Windows7\",\"Max OS X\"}; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ArrayAdapter adapter = new ArrayAdapter<String>(this, R.layout.activity_listview, mobileArray); ListView listView = (ListView) findViewById(R.id.mobile_list); 58 listView.setAdapter(adapter); } } CU IDOL SELF LEARNING MATERIAL (SLM)

Following will be the content of res/layout/activity_main.xml file − <LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:orientation=\"vertical\" tools:context=\".ListActivity\" > <ListView android:id=\"@+id/mobile_list\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" > </ListView> </LinearLayout> Following will be the content of res/values/strings.xml to define two new constants − <?xml version=\"1.0\" encoding=\"utf-8\"?> <resources> <string name=\"app_name\">ListDisplay</string> <string name=\"action_settings\">Settings</string> </resources> Following will be the content of res/layout/activity_listview.xml file <?xml version=\"1.0\" encoding=\"utf-8\"?> <!-- Single List Item Design --> <TextView xmlns:android=\"http://schemas.android.com/apk/res/android\" android:id=\"@+id/label\" android:layout_width=\"fill_parent\" android:layout_height=\"fill_parent\" android:padding=\"10dip\" android:textSize=\"16dip\" android:textStyle=\"bold\" > </TextView> 59 CU IDOL SELF LEARNING MATERIAL (SLM)

Figure 4.1 Output of List Activity 4.8 CUSTOM LIST VIEW  After creating simple ListView, android also provides facilities to customize our ListView.  As the simple ListView, custom ListView also uses Adapter classes which added the content from data source (such as string array, array, database etc). Adapter bridges data between an AdapterViews and other Views  Example of Custom ListView  In this custom listview example, we are adding image, text with title and its sub-title. package com.example.test.listviewwithimage; import android.app.Activity; import android.view.LayoutInflater; 60 import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; CU IDOL SELF LEARNING MATERIAL (SLM)

import android.widget.ImageView; import android.widget.TextView; public class MyListAdapter extends ArrayAdapter<String> { private final Activity context; private final String[] maintitle; private final String[] subtitle; private final Integer[] imgid; public MyListAdapter(Activity context, String[] maintitle,String[] subtitle, Integer[] imgid) { super(context, R.layout.mylist, maintitle); // TODO Auto-generated constructor stub this.context=context; this.maintitle=maintitle; this.subtitle=subtitle; this.imgid=imgid; } public View getView(int position,View view,ViewGroup parent) { LayoutInflater inflater=context.getLayoutInflater(); View rowView=inflater.inflate(R.layout.mylist, null,true); TextView titleText = (TextView) rowView.findViewById(R.id.title); ImageView imageView = (ImageView) rowView.findViewById(R.id.icon); TextView subtitleText = (TextView) rowView.findViewById(R.id.subtitle); 61 CU IDOL SELF LEARNING MATERIAL (SLM)

titleText.setText(maintitle[position]); imageView.setImageResource(imgid[position]); subtitleText.setText(subtitle[position]); return rowView; }; } 4.9 GRID VIEW USING ADAPTERS  A GridView is a type of AdapterView that displays items in a two-dimensional scrolling grid. Items are inserted into this grid layout from a database or from an array.  The adapter is used for displaying this data, setAdapter() method is used to join the adapter with GridView.  The main function of the adapter in GridView is to fetch data from a database or array and insert each piece of data in an appropriate item that will be displayed in GridView.  This is how the GridView structure looks like. XML Attributes of GridView android:numColumns: This attribute of GridView will be used to decide the number of columns that are to be displayed in Grid. android:horizontalSpacing: This attribute is used to define the spacing between two columns of GridView. android:verticalSpacing: This attribute is used to specify the spacing between two rows of GridView. Example : 62 Step 1: Creating a New Project Step 2: Modify activity_main.xml file CU IDOL SELF LEARNING MATERIAL (SLM)

<?xml version=\"1.0\" encoding=\"utf-8\"?> <androidx.constraintlayout.widget.ConstraintLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\"> <!-- android:numColumns=2 is the number of columns for Grid View android:horizontalSpacing is the space between horizontal grid items.--> <GridView android:id=\"@+id/idGVcourses\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:horizontalSpacing=\"6dp\" android:numColumns=\"2\" android:verticalSpacing=\"6dp\" /> </androidx.constraintlayout.widget.ConstraintLayout> Step 3: Create an XML layout file for each item of GridView Create an XML file for each grid item to be displayed in GridView. Click on the app > res > layout > Right-Click > Layout Resource file and then name the file as card_item. <?xml version=\"1.0\" encoding=\"utf-8\"?> <!--XML implementation of Card Layout--> <androidx.cardview.widget.CardView xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" android:layout_width=\"match_parent\" android:layout_height=\"120dp\" android:layout_gravity=\"center\" android:layout_margin=\"5dp\" app:cardCornerRadius=\"5dp\" app:cardElevation=\"5dp\"> <LinearLayout android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:orientation=\"vertical\"> 63 CU IDOL SELF LEARNING MATERIAL (SLM)

<ImageView android:id=\"@+id/idIVcourse\" android:layout_width=\"100dp\" android:layout_height=\"100dp\" android:layout_gravity=\"center\" android:src=\"@mipmap/ic_launcher\" /> <TextView android:id=\"@+id/idTVCourse\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:text=\"@string/app_name\" android:textAlignment=\"center\" /> </LinearLayout> </androidx.cardview.widget.CardView> Step 4: Create a Modal Class for storing Data Modal Class is the JAVA Class that handles data to be added in each GridView item of GridView. For Creating Modal Class.  Now click on app > java > apps package name > Right-Click on it.  Then Click on New > Java Class. Name your Java Class file as CourseModel. Below is the code for the CourseModel.java file public class CourseModel { // string course_name for storing course_name // and imgid for storing image id. private String course_name; private int imgid; public CourseModel(String course_name, int imgid) { this.course_name = course_name; this.imgid = imgid; } public String getCourse_name() { 64 return course_name; CU IDOL SELF LEARNING MATERIAL (SLM)

} public void setCourse_name(String course_name) { this.course_name = course_name; } public int getImgid() { return imgid; } public void setImgid(int imgid) { this.imgid = imgid; } } Step 5: Create an Adapter Class Adapter Class adds the data from Modal Class in each item of GridView which is to be displayed on the screen. For Creating Adapter Class.  Now click on app > java > apps package name > Right-Click on it.  Then Click on New > Java Class.  Name your Java Class file as CourseGVAdapter. Below is the code for the CourseGVAdapter.java file. import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import java.util.ArrayList; public class CourseGVAdapter extends ArrayAdapter<CourseModel> { public CourseGVAdapter(@NonNull Context context, ArrayList<CourseModel> courseModelArrayList) { 65 CU IDOL SELF LEARNING MATERIAL (SLM)

super(context, 0, courseModelArrayList); } @NonNull @Override public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) { View listitemView = convertView; if (listitemView == null) { // Layout Inflater inflates each item to be displayed in GridView listitemView = LayoutInflater.from(getContext()).inflate(R.layout.card_item, parent, false); } CourseModel courseModel = getItem(position); TextView courseTV = listitemView.findViewById(R.id.idTVCourse); ImageView courseIV = listitemView.findViewById(R.id.idIVcourse); courseTV.setText(courseModel.getCourse_name()); courseIV.setImageResource(courseModel.getImgid()); return listitemView; } } Step 6: Modify the MainActivity.java file Now in this file, we will perform all backend operations that will be adding data to GridView. Below is the code for the MainActivity.java file. import android.os.Bundle; import android.widget.GridView; import androidx.appcompat.app.AppCompatActivity; import java.util.ArrayList; public class MainActivity extends AppCompatActivity { GridView coursesGV; @Override 66 CU IDOL SELF LEARNING MATERIAL (SLM)

protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); coursesGV = findViewById(R.id.idGVcourses); ArrayList<CourseModel> courseModelArrayList = new ArrayList<CourseModel>(); CourseModel(\"DSA\", courseModelArrayList.add(new CourseModel(\"JAVA\", R.drawable.ic_gfglogo)); CourseModel(\"C++\", courseModelArrayList.add(new CourseModel(\"Python\", R.drawable.ic_gfglogo)); CourseModel(\"Javascript\", courseModelArrayList.add(new CourseModel(\"DSA\", R.drawable.ic_gfglogo)); courseModelArrayList.add(new R.drawable.ic_gfglogo)); courseModelArrayList.add(new R.drawable.ic_gfglogo)); courseModelArrayList.add(new R.drawable.ic_gfglogo)); CourseGVAdapter adapter = new CourseGVAdapter(this, courseModelArrayList); coursesGV.setAdapter(adapter); } } 4.10 GALLERY USING ADAPTERS  In Android, Gallery is a view used to show items in a center locked, horizontal scrolling list and user will select a view and then user selected view will be shown in the center of the Horizontal list.  The items in Gallery are added using Adapter just like in ListView or GridView.  Note :Gallery class was deprecated in API level 16. This widget is no longer supported. Other horizontally scrolling widgets include HorizontalScrollView and ViewPager from the support library. Basic Gallery XML Code: <Gallery android:id=\"@+id/simpleGallery\" android:layout_width=\"fill_parent\" 67 CU IDOL SELF LEARNING MATERIAL (SLM)

android:layout_height=\"wrap_content\"/ >  Adapter Used To Fill Images In Gallery:  Adapters works as a bridge between AdapterView and data source. For filling data(images) in Gallery we need to use Adapters. BaseAdapter is parent adapter for all other adapters so we mainly used it for displaying data in Gallery list.  BaseAdapter is a common base class of a general implementation of an Adapter that can be used in ListView, GridView, Gallery etc. Base Adapter can be extended to create a custom Adapter for displaying a custom list items.  Here is the code of Custom Adapter when we extends the BaseAdapter in that: public class CustomAdapter extends BaseAdapter { @Override public int getCount() { return 0; } @Override public Object getItem(int i) { return null; } @Override public long getItemId(int i) { return 0; } @Override public View getView(int i, View view, ViewGroup viewGroup) { return null; }  In the above code snippet we see the overrided methods of BaseAdapter which are used to set the data in a list, grid or a Gallery. From there we mainly used two functions getCount() and getView().  getView(): This method called automatically for all items of Gallery (similar to list view in which getView() method called for each item of ListView)  getCount(): This method returns the total number of items to be displayed in a list. It counts the value from array list size() method or an array’s length. Steps For Implementation Of Android Gallery View  Get the reference of Gallery in class using findViewById() method, or you can also create an object dynamically.  Create an array of Images and call the adapter using Gallery view’s object. 68 CU IDOL SELF LEARNING MATERIAL (SLM)

 Create a Custom adapter class which extends BaseAdapter to bind the Gallery view with a series of ImageViews. Important Methods Of Gallery In Android: Some important methods of Gallery that may be called in order to manage the Gallery. 1. setAnimationDuration(int): This method is used to set the duration for how long a transition animation should run (in milliseconds) when layout has changed. Below we set the duration for how long a transition animation should run when layout has changed. Gallery simpleGallery = (Gallery) findViewById(R.id.simpleGallery); // get the reference of Gallery simpleGallery.setAnimationDuration(3000); . setSpacing(int): This method is used to set the spacing between items in a Gallery. Below we set the spacing between the items of Gallery. Gallery simpleGallery = (Gallery) findViewById(R.id.simpleGallery); // get the reference of Gallery simpleGallery.setSpacing(5); Attributes of Gallery: id: id attribute is used to uniquely identify a Gallery <Gallery android:id=\"@+id/simpleGallery\" android:layout_width=\"fill_parent\" android:layout_height=\"wrap_content\"/ > padding: This attribute is used to set the padding from left, right, top or bottom side of a Gallery. paddingRight: This attribute is used to set the padding from the right side of a Gallery. paddingLeft: This attribute is used to set the padding from the left side of a Gallery. paddingTop: This attribute is used to set the padding from the top side of a Gallery. paddingBottom: This attribute is used to set the padding from the bottom side of a Gallery. Padding: This attribute is used to set the padding from the all the side’s of a Gallery. <Gallery 69 android:id=\"@+id/simpleGallery\" CU IDOL SELF LEARNING MATERIAL (SLM)

android:layout_width=\"fill_parent\" android:layout_height=\"wrap_content\" android:padding=\"10dp\"/> background: This attribute is used to set the background of a Gallery. We can set a color or a drawable in the background of a Gallery: <Gallery android:id=\"@+id/simpleGallery\" android:layout_width=\"fill_parent\" android:layout_height=\"wrap_content\" android:background=\"#000\" /> animationDuration: This attribute is used to set the duration for how long a transition animation should run (in milliseconds) when layout has changed. We can also set the animation duration programmatically means in java class by using setAnimationDuration(int). <Gallery android:id=\"@+id/simpleGallery\" android:layout_width=\"fill_parent\" android:layout_height=\"wrap_content\" android:animationDuration=\"3000\" /> 4.11 SUMMARY  Android provides a way for you to expose even your private data to other applications — with a content provider. A content provider is an optional component that exposes read/write access to your application data, subject to whatever restrictions you want to impose.  Every Android-compatible device supports a shared “external storage” that you can use to save files. This can be a removable storage media (such as an SD card) or an internal (non-removable) storage. Files saved to the external storage are world- readable and can be modified by the user when they enable USB mass storage to transfer files on a computer.  An Adapter object acts as a bridge between an AdapterView and the underlying data for that view. The Adapter provides access to the data items. ArrayAdapter is also an implementation of BaseAdapter, so if we want more customization then we can create a custom adapter and extend ArrayAdapter in that Since array adapter is an implementation of BaseAdapter, so we can override all the function’s of BaseAdapter in our custom adapter 70 CU IDOL SELF LEARNING MATERIAL (SLM)

 The Adapter is also responsible for making a View for each item in the data set. 4.12 KEYWORDS  Internal Storage: they are inside the computer case. ... Internal storage allows the data and applications to be loaded very rapidly into memory, ready for use.  SQLite Database: SQLite Database is an open-source database provided in Android which is used to store data inside the user's device in the form of a Text file. We can perform so many operations on this data such as adding new data, updating, reading, and deleting this data  Android Gallery : In Android, Gallery is a view that can show items in a center locked, horizontal scrolling list, and hence the user can able to select a view, and then the user selected view will be shown in the center of the Horizontal list.  ListView: Android ListView is a ViewGroup that is used to display the list of items in multiple rows and contains an adapter that automatically inserts the items into the list.  Adapters: An Adapter object acts as a bridge between an AdapterView and the underlying data for that view. The Adapter provides access to the data items. 4.13 LEARNING ACTIVITY 1. Explain internal storage ___________________________________________________________________________ ___________________________________________________________________________ 2. Explain external storage ___________________________________________________________________________ ___________________________________________________________________________ 4.14 UNIT END QUESTIONS 71 A. Descriptive Questions Short Questions: 1. Explain the process ow write and read from internal storage 2. Explain the concept of accessing file from external storage. 3. What is adapter? 4. Explain array adapter in android. 5. Explain attribute and description of list view. CU IDOL SELF LEARNING MATERIAL (SLM)

Long Questions: 1. Explain the content of res/layout/activity_main.xml and res/values/strings.xml in list view. 2. Describe custom list view in detail. 3. How grid view used as adapter? 4. How XML layout is created using grid view? 5. Create a Modal Class for storing Data B. Multiple Choice Questions 1. __________ method is used to set the duration for how long a transition animation should run. a. setAnimationDuration(int) b. settimeDuration(int) c. setAnimationDuration(float) d. setAnimationDuration(dec) 2. The items in Gallery are added using _____ a. socket b. adapter c. grid d. list 3. Gallery class was deprecated in API level ______ a. 15 b. 9 c. 16 d. 10 4. Adapter Class adds the data from __________ in each item of GridView 72 CU IDOL SELF LEARNING MATERIAL (SLM)

a. Main Class b. Activity Class c. Adapter Class d. Modal Class 5. A GridView is a _____ scrolling grid. a. two-dimensional b. three- dimensional c. uni-directional d. All of these Answers 1-a, 2-b, 3-c, 4-d, 5-a 4.15 REFERENCES References book  “Professional Android 4 Application Development” by Reto Meier  “Programming Android Java Programming for the New Generation of Mobile Devices” by Zigurd Mennieks  “Android Cookbook” by Ian F Darwin  “Android Programming: The Big Nerd Ranch Guide” by Bill Phillips and Chris Stewart Textbook references  “Professional Android 4 Application Development” by Reto Meier  “Programming Android Java Programming for the New Generation of Mobile Devices” by Zigurd Mennieks  “Android Cookbook” by Ian F Darwin  “Android Programming: The Big Nerd Ranch Guide” by Bill Phillips and Chris Stewart Website 73  Introduction to Android: http://developer.android.com/guide/index.html.  Android API: http://developer.android.com/reference/packages.html CU IDOL SELF LEARNING MATERIAL (SLM)

 Java 6 API: http://docs.oracle.com/javase/6/docs/api/ Fundamentals:  Android http://developer.android.com/guide/components/fundamentals.html 74 CU IDOL SELF LEARNING MATERIAL (SLM)

UNIT - 5: DATABASE CONNECTIVITY STRUCTURE 5 Learning Objectives 5.11 Introduction 5.12SQLITE PROGRAMMING 5.13SQ LITEOPENHELPER 5.14SQLITE DATABASE 5.15CURSOR 5.16 FIREBASE 5.17 Summary 5.18 Keywords 5.19 Learning Activity 5.20 Unit End Questions 5.21 References 5.0 LEARNING OBJECTIVES After studying this unit, you will be able to:  Interface android with SQLite database.  Program android with SQLite commands.  Explain different database package of SQLite  Describe the function of cursor 5.1 INTRODUCTION  SQLite is a opensource SQL database that stores data to a text file on a device. Android comes in with built in SQLite database implementation.  SQLite supports all the relational database features. In order to access this database, you don't need to establish any kind of connections for it like JDBC,ODBC e.t.c  Database - Package  The main package is android.database.sqlite that contains the classes to manage your own databases 5.2 SQLITE PROGRAMMING  SQLite is a opensource SQL database that stores data to a text file on a device. Android comes in with built in SQLite database implementation. 75 CU IDOL SELF LEARNING MATERIAL (SLM)

 SQLite supports all the relational database features. In order to access this database, you don't need to establish any kind of connections for it like JDBC,ODBC e.t.c.  Database – Package The main package is android.database.sqlite that contains the classes to manage your own databases  Database – Creation In order to create a database you just need to call this method openOrCreateDatabase with your database name and mode as a parameter. It returns an instance of SQLite database which you have to receive in your own object.Its syntax is given below SQLiteDatabase mydatabase = openOrCreateDatabase(\"your database name\",MODE_PRIVATE,null); 5.3 SQ LITEOPENHELPER  For managing all the operations related to the database , an helper class has been given and is called SQLiteOpenHelper.  It automatically manages the creation and update of the database.  Its syntax is given below public class DBHelper extends SQLiteOpenHelper { public DBHelper(){ super(context,DATABASE_NAME,null,1); } public void onCreate(SQLiteDatabase db) {} public void onUpgrade(SQLiteDatabase database, int oldVersion, int newVersion) {} }  Example of android SQLite database File: Contact.java package example.my.com.sqlitetutorial; public class Contact { 76 int _id; String _name; String _phone_number; public Contact(){ } CU IDOL SELF LEARNING MATERIAL (SLM)

public Contact(int id, String name, String _phone_number){ 77 this._id = id; this._name = name; this._phone_number = _phone_number; } public Contact(String name, String _phone_number){ this._name = name; this._phone_number = _phone_number; } public int getID(){ return this._id; } public void setID(int id){ this._id = id; } public String getName(){ return this._name; } public void setName(String name){ this._name = name; } public String getPhoneNumber(){ return this._phone_number; } CU IDOL SELF LEARNING MATERIAL (SLM)

public void setPhoneNumber(String phone_number){ this._phone_number = phone_number; } } 5.4 SQLITEDATABASE Database - Creation  In order to create a database you just need to call this method openOrCreateDatabase with your database name and mode as a parameter.  It returns an instance of SQLite database which you have to receive in your own object.Its syntax is given below SQLiteDatabase mydatabase = openOrCreateDatabase(\"your database name\",MODE_PRIVATE,null); There are other functions available in the database package , that does this job. They are listed below Sr.No Method & Description 1 openDatabase(String path, SQLiteDatabase.CursorFactory factory, int flags, DatabaseErrorHandler errorHandler) This method only opens the existing database with the appropriate flag mode. The common flags mode could be OPEN_READWRITE OPEN_READONLY 2 openDatabase(String path, SQLiteDatabase.CursorFactory factory, int flags) It is similar to the above method as it also opens the existing database but it does not define any handler to handle the errors of databases 3 openOrCreateDatabase(String path, SQLiteDatabase.CursorFactory factory) It not only opens but create the database if it not exists. This method is equivalent to openDatabase method. 4 openOrCreateDatabase(File file, SQLiteDatabase.CursorFactory factory) This method is similar to above method but it takes the File object as a path rather then a string. It is equivalent to file.getPath() 78 CU IDOL SELF LEARNING MATERIAL (SLM)

Database - Insertion  We can create table or insert data into table using execSQL method defined in SQLiteDatabase class. Its syntax is given below mydatabase.execSQL(\"CREATE TABLE IF NOT EXISTS TutorialsPoint(Username VARCHAR,Password VARCHAR);\"); mydatabase.execSQL(\"INSERT INTO TutorialsPoint VALUES('admin','admin');\"); This will insert some values into our table in our database. Another method that also does the same job but take some additional parameter is given below Sr.No Method & Description 1 execSQL(String sql, Object[] bindArgs) This method not only insert data , but also used to update or modify already existing data in database using bind arguments Database – Fetching  We can retrieve anything from database using an object of the Cursor class.  We will call a method of this class called rawQuery and it will return a resultset with the cursor pointing to the table.  We can move the cursor forward and retrieve the data. Cursor resultSet = mydatbase.rawQuery(\"Select * from TutorialsPoint\",null); resultSet.moveToFirst(); String username = resultSet.getString(0); String password = resultSet.getString(1); There are other functions available in the Cursor class that allows us to effectively retrieve the data. That includes Sr.No Method & Description 1 getColumnCount() This method return the total number of columns of the table. 2 getColumnIndex(String columnName) This method returns the index number of a column by specifying the name of the column 3 getColumnName(int columnIndex) 79 CU IDOL SELF LEARNING MATERIAL (SLM)

This method returns the name of the column by specifying the index of the column 4 getColumnNames() This method returns the array of all the column names of the table. 5 getCount() This method returns the total number of rows in the cursor 6 getPosition() This method returns the current position of the cursor in the table 7 isClosed() This method returns true if the cursor is closed and return false otherwise 5.5 CURSOR The basic purpose of a cursor is to point to a single row of the result fetched by the query. We load the row pointed by the cursor object. By using cursor we can save lot of ram and memory. The cursor is defined in the following code: Public Cursor getString(String[] columnNames}{ Cursor cursor = database.query(table_name, columnName, null, null, Null,null,null); Return cursor; } } Here, we pass the table name, column name only then we receive the cursor. In order to get the columns and rows, we use the statement: Int col = cursor.getColumnCount(); 80 Int row = cursor.getCount(); In order to get the column names, we use: String[] columnNames = cursor.getColumnNames(); CU IDOL SELF LEARNING MATERIAL (SLM)

We then display the results through the statement: Result += “No of Columns: “+col + “ ”; Result += “No of Rows: “+row + “ ”; Result += “Name of Columns” “+” ”; Any query in the SQLite database returns a cursor object and the cursor points to a single row. Lets take the following code: Cursor cursor = database.query(TABLE_NAME, columnNames, null, null, null, null, null); Return cursor; } } When we define the cursor it will point to the first row. Using the cursor we define a ‘for row’ with the code: for( cursor.moveTofirst(); !cursor.isAfterLast(); cursor</pre> <pre style=\"text-align: justify;\">moveToNext()) {</pre> <pre style=\"text-align: justify;\">Result += cursor.getString(0) + “ ”</pre> <pre style=\"text-align: justify;\">+ cursor.getString(1) + “ ”</pre> <pre style=\"text-align: justify;\">+ cursor.getString(2) + “ ”;</pre> <pre style=\"text-align: justify;\">} When we call ‘Movetonext’ method it keeps going to the next row. If the Method is ‘afterlast’ it will go to NULL. 5.6 FIREBASE What is the use of firebase in Android? Firebase is a mobile platform that helps you quickly develop high-quality apps, grow your user base, and earn more money. Firebase is made up of complementary features that you can mix-and-match to fit your needs, with Google Analytics for Firebase at the core.  Add Firebase to your Android project: 81 CU IDOL SELF LEARNING MATERIAL (SLM)

1. Prerequisites : Install or update Android Studio to its latest version. Make sure that your project meets these requirements: Targets API level 16 (Jelly Bean) or higher Uses Android 4.1 or higher Uses Jetpack (AndroidX), which includes meeting these version requirements: com.android.tools.build:gradle v3.2.1 or later compileSdkVersion 28 or later Set up a physical device or use an emulator to run your app. Note that Firebase SDKs with a dependency on Google Play services require the device or emulator to have Google Play services installed. Sign into Firebase using your Google account. 2. Add Firebase using the Firebase console Adding Firebase to your app involves tasks both in the Firebase console and in your open Android project (for example, you download Firebase config files from the console, then move them into your Android project). Step 1: Create a Firebase project Before you can add Firebase to your Android app, you need to create a Firebase project to connect to your Android app. Visit Understand Firebase Projects to learn more about Firebase projects. Step 2: Register your app with Firebase To use Firebase in your Android app, you need to register your app with your Firebase project. Registering your app is often called \"adding\" your app to your project. Go to the Firebase console. In the center of the project overview page, click the Android icon (plat_android) or Add app to launch the setup workflow. Enter your app's package name in the Android package name field. Click Register app. Step 3: Add a Firebase configuration file Add the Firebase Android configuration file to your app: Click Download google-services.json to obtain your Firebase Android config file (google- services.json). Move your config file into the module (app-level) directory of your app. 82 CU IDOL SELF LEARNING MATERIAL (SLM)

enable Firebase products in your app, add the google-services plugin to your Gradle files. In your root-level (project-level) Gradle file (build.gradle), add rules to include the Google Services Gradle plugin. Check that you have Google's Maven repository, as well. In your module (app-level) Gradle file (usually app/build.gradle), apply the Google Services Gradle plugin: Step 4: Add Firebase SDKs to your app Using the Firebase Android BoM, declare the dependencies for the Firebase products that you want to use in your app. Declare them in your module (app-level) Gradle file (usually app/build.gradle). Sync your app to ensure that all dependencies have the necessary versions. 5.7 SUMMARY  SQLite is a opensource SQL database that stores data to a text file on a device. Android comes in with built in SQLite database implementation. .  For managing all the operations related to the database,a helper class has been given and is called SQLiteOpenHelper.  The basic purpose of a cursor is to point to a single row of the result fetched by the query. We load the row pointed by the cursor object. By using cursor we can save lot of ram and memory.  Firebase is a mobile platform that helps you quickly develop high-quality apps, grow your user base, and earn more money. Firebase is made up of complementary features that you can mix-and-match to fit your needs, with Google Analytics for Firebase at the core. 5.8 KEYWORDS  SQLite Database: SQLite Database is an open-source database provided in Android which is used to store data inside the user's device in the form of a Text file. We can perform so many operations on this data such as adding new data, updating, reading, and deleting this data  Prerequisites: a thing that is required as a prior condition for something else to happen or exist.  Firebase console:a secured site from which field artillery can lay down interdicting fire.  Cursor: a movable indicator on a computer screen identifying the point that will be affected by input from the user. 83 CU IDOL SELF LEARNING MATERIAL (SLM)

5.9 LEARNING ACTIVITY 1. Give example of android SQLite database ___________________________________________________________________________ ___________________________________________________________________________ 2. List the functions of database packages. ___________________________________________________________________________ ___________________________________________________________________________ 5.10 UNIT END QUESTIONS A. Descriptive Questions Short Questions 1. Explain the process of database creation 2. How is database fetch? 3. What are the prerequisites before adding firebase? 4. List the functions available in cursor. 5. What is SQ LITEOPENHELPER Long Questions 1. Explain the importance of cursor in SQLite.. 2. Explain the process of of creation of SQLITE DATABASE 3. Explain the usage of Cursor with respect to SQLITE. 4. How is firebase added using firebase console B. Multiple Choice Questions 1. Firebase is a ________ platform a. mobile b. desktop c. mobile and dektop d. cross 2. The basic purpose of a cursor is to point to a ________ row 84 CU IDOL SELF LEARNING MATERIAL (SLM)

a. multiple 85 b. single c. lower d. upper 3. Using cursor we can save lot of ______ a. energy b. money c. RAM d. ROM 4. GetPosition () returns the current position of the cursor in the table a. True b. False 5. SQLiteOpenHelper manages the ____ and _____ of the database a. creation, update b. creation, delete c. update , delete d. create and drop Answers 1-a, 2-b, 3-c, 4-a, 5-a 5.11 REFERENCES References book  “Professional Android 4 Application Development” by Reto Meier CU IDOL SELF LEARNING MATERIAL (SLM)

 “Programming Android Java Programming for the New Generation of Mobile Devices” by Zigurd Mennieks  “Android Cookbook” by Ian F Darwin  “Android Programming: The Big Nerd Ranch Guide” by Bill Phillips and Chris Stewart Textbook references  “Professional Android 4 Application Development” by Reto Meier  “Programming Android Java Programming for the New Generation of Mobile Devices” by Zigurd Mennieks  “Android Cookbook” by Ian F Darwin  “Android Programming: The Big Nerd Ranch Guide” by Bill Phillips and Chris Stewart Website  Introduction to Android: http://developer.android.com/guide/index.html.  Android API: http://developer.android.com/reference/packages.html  Java 6 API: http://docs.oracle.com/javase/6/docs/api/  Android Fundamentals: http://developer.android.com/guide/components/fundamentals.html 86 CU IDOL SELF LEARNING MATERIAL (SLM)

UNIT - 6: ONLINE DATA PARSING STRUCTURE 6 Learning Objectives 6.11 Introduction 6.12XML AND JSON 6.13XML PARSING SAX 6.14XML PULLPARSER 6.15JSON PARSING 6.16Summary 6.17Keywords 6.18Learning Activity 6.19Unit End Questions 6.20References 6.0 LEARNING OBJECTIVES After studying this unit, you will be able to:  Describe the similarities between XML and JSON  Differentiate between XML and JSON  Explain how Android provides the facility to parse the xml file using SAX, DOM  Explain why Android recommends to use XMLPullParser to parse the xml file than SAX and DOM 6.1 INTRODUCTION JSON stands for JavaScript Object Notation.It is an independent data exchange format and is the best alternative for XML. This chapter explains how to parse the JSON file and extract necessary information from it. Android provides four different classes to manipulate JSON data. These classes are JSONArray,JSONObject,JSONStringer and JSONTokenizer. JSON - Elements An JSON file consist of many components. Here is the table defining the components of an JSON file and their description – Sr.No Component & description 1 Array([) 87 CU IDOL SELF LEARNING MATERIAL (SLM)

In a JSON file , square bracket ([) represents a JSON array 2 Objects({) In a JSON file, curly bracket ({) represents a JSON object 3 Key A JSON object contains a key that is just a string. Pairs of key/value make up a JSON object 4 Value Each key has a value that could be string , integer or double e.t.c JSON - Parsing For parsing a JSON object, we will create an object of class JSONObject and specify a string containing JSON data to it. Its syntax is – String in; JSONObject reader = new JSONObject(in); 6.2 XML AND JSON What is json? JSON stands for JavaScript object notation. JSON has been derived from javascript, where javascript is a programming language. It was originally created to hold the structured data that could be used in javascript. JSON became so popular that it is used for data for all kinds of applications. It is the most popular way of sending the data for Web APIs. Basic data types supported by json are:  Strings: Characters that are enclosed in single or double quotation marks.  Number: A number could be integer or decimal, positive or negative.  Booleans: The Boolean value could be either true or false without any quotation marks.  Null: Here, null means nothing without any quotation marks. In addition to basic data types, json has arrays and objects. What is XML? 88 CU IDOL SELF LEARNING MATERIAL (SLM)

XML stands for an extensible markup language. It is like HTML, where HTML stands for Hypertext Markup language. HTML is used for creating websites, whereas XML can be used for any kind of structured data. XML has two ways of handling data, i.e., Tags and Attributes. The tags work as HTML. The start tags start with the <_> and end with the </_>. The start and end tags must match. The names must only be letters, numbers, and underscore, and the tag name must start with a letter only. Similarities between the json and XML.  Self-describing: Both json and xml are self-describing as both xml data and json data are human-readable text.  Hierarchical: Both json and xml support hierarchical structure. Here hierarchical means that the values within values.  Data interchange format: JSON and XML can be used as data interchange formats by many different programming languages.  Parse: Both the formats can be easily parsed.  Retrieve: Both formats can be retrieved by using HTTP requests. The methods used for retrieving the data are GET, PUT, POST. Differences between the json and XML JSON XML JSON stands for javascript object notation. XML stands for an extensible markup language. The extension of json file is .json. The extension of xml file is .xml. The internet media type is application/json. The internet media type is application/xml or text/xml. The type of format in JSON is data interchange. The type of format in XML is a markup language. It is extended from javascript. It is extended from SGML. It is open source means that we do not have to It is also open source. pay anything to use JSON. The object created in JSON has some type. XML data does not have any type. The data types supported by JSON are strings, XML data is in a string format. numbers, Booleans, null, array. 89 CU IDOL SELF LEARNING MATERIAL (SLM)

It does not have any capacity to display the data. XML is a markup language, so it has the capacity to display the content. JSON has no tags. XML data is represented in tags, i.e., start tag and end tag. JSON is quicker to read and write. XML file takes time to read and write because the learning curve is higher. JSON can use arrays to represent the data. XML does not contain the concept of arrays. It can be parsed by a standard javascript function. XML data which is used to interchange the data, It has to be parsed before use. must be parsed with respective to their programming language to use that. It can be easily parsed and little bit code is It is difficult to parse. required to parse the data. File size is smaller as compared to XML. File size is larger. JSON is data-oriented. XML is document-oriented. It is less secure than XML. It is more secure than JSON. 6.3 XML PARSING SAX Android provides the facility to parse the xml file using SAX, DOM etc. parsers. The SAX parser cannot be used to create the XML file, It can be used to parse the xml file only. Advantage of SAX Parser over DOM is that tt consumes less memory than DOM. Example of android SAX Xml parsing:  activity_main.xml <RelativeLayout xmlns:androclass=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\" > <TextView 90 CU IDOL SELF LEARNING MATERIAL (SLM)

android:id=\"@+id/textView1\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_alignParentLeft=\"true\" android:layout_alignParentTop=\"true\" android:layout_marginLeft=\"75dp\" android:layout_marginTop=\"46dp\" android:text=\"TextView\" /> </RelativeLayout> 91  xml document  Create an xml file named file.xml inside the assets directory of your project. file.xml <?xml version=\"1.0\"?> <records> <employee> <name>Sachin Kumar</name> <salary>50000</salary> </employee> <employee> <name>Rahul Kumar</name> <salary>60000</salary> </employee> <employee> <name>John Mike</name> <salary>70000</salary> </employee> </records>  Activity class Now write the code to parse the xml using sax parser. MainActivity.java CU IDOL SELF LEARNING MATERIAL (SLM)

package com.javatpoint.saxxmlparsing; 92 import java.io.InputStream; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; import android.app.Activity; import android.os.Bundle; import android.widget.TextView; public class MainActivity extends Activity { TextView tv; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tv=(TextView)findViewById(R.id.textView1); try { SAXParserFactory factory = SAXParserFactory.newInstance(); SAXParser saxParser = factory.newSAXParser(); DefaultHandler handler = new DefaultHandler() { boolean name = false; boolean salary = false; public void startElement(String uri, String localName,String qName, Attributes attributes) throws SAXException { if (qName.equalsIgnoreCase(\"name\")) { name = true; } if (qName.equalsIgnoreCase(\"salary\")) CU IDOL SELF LEARNING MATERIAL (SLM)

{ salary = true; } }//end of startElement method public void endElement(String uri, String localName, String qName) throws SAXException { } public void characters(char ch[], int start, int length) throws SAXException { if (name) { tv.setText(tv.getText()+\"\\n\\n Name : \" + new String(ch, start, length)); name = false; } if (salary) { tv.setText(tv.getText()+\"\\n Salary : \" + new String(ch, start, length)); salary = false; } }//end of characters method };//end of DefaultHandler object InputStream is = getAssets().open(\"file.xml\"); saxParser.parse(is, handler); } catch (Exception e) {e.printStackTrace();} } } Output: 93 CU IDOL SELF LEARNING MATERIAL (SLM)

Figure 6.1 6.4 XML PULLPARSER Android recommends to use XMLPullParser to parse the xml file than SAX and DOM because it is fast. The org.xmlpull.v1.XmlPullParser interface provides the functionality to parse the XML document using XMLPullParser. Events of XmlPullParser The next() method of XMLPullParser moves the cursor pointer to the next event. Generally, we use four constants (works as the event) defined in the XMLPullParser interface. START_TAG :An XML start tag was read. TEXT :Text content was read; the text content can be retrieved using the getText() method. 94 CU IDOL SELF LEARNING MATERIAL (SLM)

END_TAG : An end tag was read. END_DOCUMENT :No more events are available  Example of android XMLPullParser activity_main.xml <RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\" > <ListView android:id=\"@+id/listView1\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" > </ListView> </RelativeLayout> xml document employees.xml <?xml version=\"1.0\" encoding=\"UTF-8\"?> <employees> <employee> <id>1</id> <name>Sachin</name> <salary>50000</salary> </employee> <employee> <id>2</id> <name>Nikhil</name> <salary>60000</salary> </employee> </employees> Employee class: Employee.java package com.example.xmlpullparsing; 95 CU IDOL SELF LEARNING MATERIAL (SLM)

public class Employee { 96 private int id; private String name; private float salary; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public float getSalary() { return salary; } public void setSalary(float salary) { this.salary = salary; } @Override public String toString() { return \" Id= \"+id + \"\\n Name= \" + name + \"\\n Salary= \" + salary; } } XMLPullParserHandler class XMLPullParserHandler.java package com.example.xmlpullparsing; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import org.xmlpull.v1.XmlPullParserFactory; CU IDOL SELF LEARNING MATERIAL (SLM)

public class XmlPullParserHandler { 97 private List<Employee> employees= new ArrayList<Employee>(); private Employee employee; private String text; public List<Employee> getEmployees() { return employees; } public List<Employee> parse(InputStream is) { try { XmlPullParserFactory factory = XmlPullParserFactory.newInstance(); factory.setNamespaceAware(true); XmlPullParser parser = factory.newPullParser(); parser.setInput(is, null); int eventType = parser.getEventType(); while (eventType != XmlPullParser.END_DOCUMENT) { String tagname = parser.getName(); switch (eventType) { case XmlPullParser.START_TAG: if (tagname.equalsIgnoreCase(\"employee\")) { // create a new instance of employee employee = new Employee(); } break; case XmlPullParser.TEXT: text = parser.getText(); break; case XmlPullParser.END_TAG: if (tagname.equalsIgnoreCase(\"employee\")) { // add employee object to list employees.add(employee); }else if (tagname.equalsIgnoreCase(\"id\")) { employee.setId(Integer.parseInt(text)); } else if (tagname.equalsIgnoreCase(\"name\")) { CU IDOL SELF LEARNING MATERIAL (SLM)

employee.setName(text); 98 } else if (tagname.equalsIgnoreCase(\"salary\")) { employee.setSalary(Float.parseFloat(text)); } break; default: break; } eventType = parser.next(); } } catch (XmlPullParserException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} return employees; } } MainActivity class MainActivity.java package com.example.xmlpullparsing; import java.io.IOException; import java.io.InputStream; import java.util.List; import android.os.Bundle; import android.app.Activity; import android.view.Menu; import android.widget.ArrayAdapter; import android.widget.ListView; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); CU IDOL SELF LEARNING MATERIAL (SLM)

ListView listView = (ListView) findViewById(R.id.listView1); List<Employee> employees = null; try { XmlPullParserHandler parser = new XmlPullParserHandler(); InputStream is=getAssets().open(\"employees.xml\"); employees = parser.parse(is); ArrayAdapter<Employee> adapter =new ArrayAdapter<Employee> (this,android.R.layout.simple_list_item_1, employees); listView.setAdapter(adapter); } catch (IOException e) {e.printStackTrace();} } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.activity_main, menu); return true; } } Output: 99 CU IDOL SELF LEARNING MATERIAL (SLM)

Figure 6.2 6.5 JSON PARSING JSON (Javascript Object Notation) is a programming language . It is minimal, textual, and a subset of JavaScript. It is an alternative to XML. Android provides support to parse the JSON object and array. Advantage of JSON over XML 1) JSON is faster and easier than xml for AJAX applications. 2) Unlike XML, it is shorter and quicker to read and write. 3) It uses array. json object A JSON object contains key/value pairs like map. The keys are strings and the values are the JSON types. Keys and values are separated by comma. The { (curly brace) represents the json object. { \"employee\": { \"name\": \"sachin\", 100 CU IDOL SELF LEARNING MATERIAL (SLM)


Like this book? You can publish your book online for free in a few minutes!
Create your own flipbook