Teaching materials and advanced sample applications for Android platform

Size: px
Start display at page:

Download "Teaching materials and advanced sample applications for Android platform"

Transcription

1 MASARYK UNIVERSITY FACULTY OF INFORMATICS Teaching materials and advanced sample applications for Android platform MASTER THESIS Bc. Vanda Cabanová Brno, 2014

2 Statement of an author of a school work Student s Name and UČO: I acknowledge that the Masaryk University (MU) is entitled in accordance with the law (Article 35 3 and 4 of the Copyright Act No. 121/2000 Sb.) to use for educational and other internal purposes on a non-commercial basis my thesis or my other school work, which I authored to fulfill my study obligations towards MU (my work). The use of my work for internal purposes includes the use of the original work as well as of its derivatives and might consists also of assigning of my work for additional processing to another student or a member of the MU academic community, or of making it available as a basis for a creation of a derivative thesis or other school work at MU. Any such use of my work will acknowledge my authorship, the original name and source of my work and will be conducted exclusively in order to further develop educational and other interests of MU related to further development and utilization of my work within its academic community. I also acknowledge my duty to inform MU at the latest upon the submission of my work about my intent to further develop or use my work at MU or elsewhere or about any other relevant issues related to my work. Brno, Student s signature

3 Declaration Hereby I declare, that this paper is my original authorial work, which I have worked out by my own. All sources, references and literature used or excerpted during elaboration of this work are properly cited and listed in complete reference to the due source.... Bc. Vanda Cabanová Advisor: doc. RNDr. Tomáš Pitner, Ph.D. i

4 Acknowledgement First of all, I would like to thank my advisor Tomáš Pitner for supervising me and enabling me to work on this topic and for giving me the opportunity to create a new course at the faculty which I honor gratefully. I would also like to thank Aurel Medvegy and RNDr. David Novák, Ph. D. for their consultations on the AppEngine server. I also want to thank my colleague Jonáš Ševčík for helping me throughout the course. Last but not least, I want to thank Tomáš Vlček, all my friends and mom for helping me and being patient with me during my work on the thesis. ii

5 Abstract The aim of this thesis is to design a course material and an application demonstrating advanced programming for Android platform. The code of the application is clear and should help even a less experienced reader to understand the matter and easily use the code in their own application. The application also points out alternatives of implementing individual tasks, their pros and cons and cases of appropriate or inappropriate use of particular alternatives. The implementation part includes the code of the Android client application as well as AppEngine backend, which the application will communicate with through its API. iii

6 Keywords Android, AppEngine, Java, REST API iv

7 Contents 1 Introduction Android application Course design First exercise Activity Navigation Drawer Fragment Action Bar Menu Tabs Styles and themes Second exercise ListView Adapter Optimization Multiple data types in one list ViewPager Third exercise Contextual Action Bar Handling configuration changes Fragment communication Parcelable interface Fourth exercise Selectors Custom drawables patch images Animations Fifth exercise Networking Threads Server API Sixth exercise Database Content Provider vi

8 CONTENTS 2.8 Seventh exercise GCM Broadcast Receiver Services Eighth exercise Alarm Manager Notifications Ninth exercise Maps Bound service Introduction to AppEngine AppEngine database AppEngine Endpoints REST API GCM Conclusion Bibliography Abbreviations Attachments vii

9 1 Introduction The number of mobile devices is exploding. Whereas a decade ago it seemed that desktop computing would be the norm going forward, today everything is becoming increasingly mobile. A 2014 study by comscore, a leading internet technology company that provides analytics for a digital world, has released a study showing that at the beginning of 2014, time spent in mobile applications surpassed the time spent using desktop computers. Figure 1 Time spent with Internet by Device in US in minutes [1] The number of new mobile applications is predicted to be increasing in the near future and hence more mobile developers will be needed on the market. With the recent growth of internet resources there are many tutorials and online courses where developers can learn about mobile development. The online tutorials are unfortunately rarely complete and sometimes they are hard to understand as the developer creating one usually solves his own problem and then writes a tutorial on how to solve that particular problem. So it helps others only partially and it still takes a lot of time to get to know a new platform well. 1

10 1 Introduction This is where universities should step in and offer more courses focused on mobile devices, either focusing on the architecture and security, or proper mobile applications development. We have designed a single semester course that teaches students the basics of Android programming, using the implementation of a server backend mentioned in the last part of the thesis. The students are guided through the entire development of mobile application, over the course of 12 weeks. Compared with the more traditional cycle of weekly homework, having an extended project leads to greater student engagement, and a sense of accomplishment at the end of the semester. To make the application interesting and relevant, we chose to develop a social networking chat application. From a technical point of view, this also serves as a great example of a mobile application, as students learn about many of the modern programming paradigms, such as UI design, client-server interaction, notifications and cloud data storage. The course concerns implementation of the Android chat application divided into exercises that correspond to nine or ten weeks of a university semester. Each exercise has its own sample application published on the Google Play Store where students can review detailed animations and functionality and the theory needed to complete the exercise. The theory refers to the source code of the sample applications as well as discusses some frequently asked questions or possible tweaks of the code. The course breakdown is covered in the second chapter of the thesis with a subchapter for each of the exercises. The third chapter describes implementation of the AppEngine server backend, its database structure and REST API. 2

11 2 Android application 2.1 Course design The course has a practical approach so the challenge was to create a type of an application that could cover as many topics as possible. There could be an easier way of making the exercises independent of each other and each exercise would have its own set of exercises, but developing one whole application throughout the semester is much more interesting and much more motivating for students, which is the wanted purpose. Another important issue was to think of what most of the commercial Android applications have in common. Nowadays, Android applications are usually thin clients communicating with a remote server so that even users with different mobile operating systems can communicate with each other. Based on this assumption, I came to a conclusion to make a chat-based application since social networks are nowadays so popular and students might easily get engaged with making their own chat application. Also, at the end of the semester they could see a big progress in their programming skills and they could see the result of their work they could message their classmates through their own application, even if their classmates had their own version of the application. Having a common server backend is a great opportunity to make their own app and yet be able to connect with each other in the course. The course is divided into several exercises, each containing a part of the application that will be added to the previous version of the application. At the beginning, the whole skeleton of the app is built, the basics of building of an Android application is introduced as well as a deep insight into styling of the UI and using of themed based approach to application interface design must not be omitted. In the next exercises another building components are added, both from the UI side and from the backend side. The result will be an application through which students can send a message, can see their friends location using GPS and Google maps. This would make the basic functionality that can be extended to any direction. The purpose of this application is not to make it user-friendly at first place, but to make it interesting for the students that will be to develop it, so it may be grown into a much more complex application, though still keeping Android design patterns in mind. 3

12 2.1 Course design The first lecture will be introductory and will lead students through basic components of an application, demonstrating the power of themes and styles. The second exercise will explain Action Bar and widely used tabs along with a ViewPager component to let users slide to multiple main screens, each containing a different set of functions. Then we will add networking along with Google Cloud Messaging for sending messages directly to appointed devices, database, Facebook authentication and Google maps functionality. At the end of the course students will be able to build a release version of the application and publish it on Google Play Store. Except for the theory part, students are given the demo application available on Google Play Store as well as screenshots of the application so that they can understand better what is required from them. The final step is to choose what platform versions to support. The most important thing to take into consideration is that for supporting anything lower than Ice Cream Sandwich (API 15) we have to use Android Support Library which brings a lot of additional work. By doing so, we would omit almost 10% of market. Hypothetically, these 10% are those users whose devices are not going to get any new update and are not even willing to buy a new device. On top of that, their devices must be at least two years old so they are quite small and low on memory. After taking this into account I assume that making the application available also for this kind of users would be worthy only if the purpose of the application would be to cover as much of the market as possible. On the other hand, if the application should use a lot of graphics and animations, should be very demanding memory- and processor-wise, it would be too expensive to make the application available also to such old devices with such old operating systems. Although all of this above is true, however, during the semester I could notice that many of the students in the class still had those old devices so they would have to use Android emulators to test their applications. So for the purpose of this course supporting of devices all the way down to Gingerbread is necessary. As for maximum API we chose Kitkat (API 19), since only an unstable developer version of Lollipop (API 21) bringing along many big changes into Android development was released. 4

13 2.2 First exercise 2.2 First exercise In the first exercise, we are going to create the application project in Android Studio and set our custom theme including two themes for the application. We are going to have a Navigation Drawer as the main means of navigation. So far, there are going to be two menu items in the Navigation Drawer, one for the messaging part and one for the map part coming in the following lectures. In the messaging part, there are going to be another two sections, one containing conversations and one containing friends of the user. We are going to use ActionBarActivity class as the host activity for Navigation Drawer and content Fragment. ActionBar will contain an ActionBar Item that, after clicking on it, will restart the application to refresh with a different theme - for example yellow and lime themes will be switching Activity An activity is a single, focused thing that the user can do.[2] Basically, one Activity represents one screen that the user can view or represents a set of functions that belong together in some sense. An Activity is one of the four main components (activity, broadcast receiver, content provider, service) and has its own lifecycle composed of states in which it can be. There is only one running Activity within the whole system at the same time. At first, when the application is started, the main activity is started along with it and the oncreate method is called. That is where the object of the activity and all initial settings are proceeded. On start and onresume are called every time Activity regains focus after some other Activity or after user returns to the application and the application has not been yet killed by the system or the user (for example manually by pressing Stop button in the general app settings). OnResume and onstart are also called immediately after oncreate so it is good practice to make sure no equal methods are called in these three methods that meaning, if you call to create the same object in all three methods, it will be called three times after the first run and it will waste resources for no reason. In such a case it would be probably better to create the object only in onresume for instance, if there is no more important reason to do so in oncreate. 5

14 2.2 First exercise If a new Activity is being created by the application, it is important to decide, whether to keep the current Activity or destroy it by calling Activity.finish(). Keeping the Activity open means there is a chance to get back to it by clicking back, but once it is killed, by clicking the back button you would go outside the application. Figure 2 - Activity Lifecycle [3] Thus there are three main loops in the lifecycle The entire lifecycle beginning with oncreate and ending with ondestroy when all resources are released The visible lifecycle when user can see the activity on the screen, though it may not be on the entire foreground. This is the best lifecycle to start monitoring activities that could interact with user. For example, if the purpose of the app is to show where the user is standing, location checking might be started in onstart() and stopped in onstop() 6

15 2.2 First exercise The foreground lifecycle during which the activity is in foreground, and thus user can interact with it. It begins with onresume() and ends with onpause(), when another activity takes focus. If the activity is paused, there is no need to update the content as user cannot see it. What exactly do lifecycle callback method look like? protected void oncreate(bundle savedinstancestate) if (DEBUG_LIFECYCLE) Slog.v(TAG, "oncreate " + this + ": " + savedinstancestate); if (mlastnonconfigurationinstances!= null) mallloadermanagers = mlastnonconfigurationinstances.loaders; if (mactivityinfo.parentactivityname!= null) if (mactionbar == null) menabledefaultactionbarup = true; else mactionbar.setdefaultdisplayhomeasupenabled(true); if (savedinstancestate!= null) Parcelable p = savedinstancestate.getparcelable(fragments_tag); mfragments.restoreallstate(p, mlastnonconfigurationinstances!= null? mlastnonconfigurationinstances.fragments : null); mfragments.dispatchcreate(); getapplication().dispatchactivitycreated(this, savedinstancestate); mcalled = true; /* package */ void dispatchactivitycreated(activity activity, Bundle savedinstancestate) Object[] callbacks = collectactivitylifecyclecallbacks(); if (callbacks!= null) for (int i=0; i<callbacks.length; i++) ((ActivityLifecycleCallbacks)callbacks[i]).onActivityCreated(activity, savedinstancestate); Figure 3 Android source code [4] If we take oncreate(bundle savedinstancestate) method, we can see that it does all necessary code for creating an Activity and then it dispatches the oncreate() method to all its Fragments. After that, dispatchactivitycreated(this,savedinstancestate) method is called that does not do anything else than calls onactivitycreated() callback in Activity which we can override with code needed to be done right after the Activity is created. This works similarly for the rest of lifecycle methods. Project structure An Activity is a UI component, so we put our new object MyActivity.class into the.ui subpackage. Another subpackages will contain adapters for binding data to views, or classes that will deal with networking, or databases. We divide them into subpackages because we 7

16 2.2 First exercise want to keep order in our project because once it grows big we will want to be very quick to find things in the project. MyActivity.class Activity is extended by two other important and frequently used components, ActionBarActivity, FragmentActivity. Since they extend Activity, they contain methods that make it more convenient to work with ActionBar or Fragments. To be more precise, ActionBarActivity extends FragmentActivity which extends Activity. FragmentActivity A FragmentActivity, on top of maintaining the callback lifecycle, has a FragmentManager object that manages adding, removing and calling Fragment callback methods along Activity callback methods. In the code snippet of FragmentActivity implementation you can see there is a static variable marking what version code this object is from (Honeycomb, API 11) and that it contains a Handler object that manages Fragment state when its Activity is stopped or resumed. IT calls appropriate methods in Fragment so that Fragments, as well as their parent Activites, manage their state well for a good user experience. public class FragmentActivity extends Activity private static final String TAG = "FragmentActivity"; static final String FRAGMENTS_TAG = "android:support:fragments"; // This is the SDK API version of Honeycomb (3.0). private static final int HONEYCOMB = 11; static final int MSG_REALLY_STOPPED = 1; static final int MSG_RESUME_PENDING = 2; final Handler mhandler = new public void handlemessage(message msg) switch (msg.what) case MSG_REALLY_STOPPED: if (mstopped) doreallystop(false); break; case MSG_RESUME_PENDING: onresumefragments(); mfragments.execpendingactions(); break; default: super.handlemessage(msg); 8

17 2.2 First exercise ; final FragmentManagerImpl mfragments = new FragmentManagerImpl(); final FragmentContainer mcontainer = new public View findviewbyid(int id) return FragmentActivity.this.findViewById(id); ; Code snippet of a Fragment Activity from a Google repository If a hardware back button is pressed, the Activity first calls all its Fragments onbackpressed() callback methods. These, if they process the back click, return true. If false is returned to the Activity, then it processes the back click on its own. public void onbackpressed() if (!mfragments.popbackstackimmediate()) finish(); ActionBarActivity It is an extension of the FragmentActivity that adds managing of ActionBar, one of the main components of the Activity being set on top of the Activity view. Added functionality includes navigation between multiple Activities, ActionBar option items that are placed on ActionBar, clicking on option items and managing adding and removing options based on where we navigate through. Set a UI for an Activity Layouts for UI components in Android are usually created in XML files, although they may be created programmatically, too. To load a layout for MyActivity we call setcontentview(r.layout.activity_my) in oncreate method. It should usually be the first thing to call after super.oncreate method (in our case, we will add implementation for changing a theme before setting the layout). The R.layout.activity_my says the file called activity_my.xml is located in layout directory in resources. The absolute path within the module is java/res/layout/activity_my.xml How to load a specific view from the layout? The Activity, as well as any View object, has a findviewbyid(int) method which goes through all its children recursively until it finds a View with the specified ID in a form of R.id.name. 9

18 2.2 First exercise This time we use id instead of layout in the path, because we are referring to a view located in the XML tree structure marked with an ID unique for the three structure Navigation Drawer Navigation Drawer is essentially a Fragment that has a toggle button placed in ActionBar which can drag the Drawer from outside the screen or have it hidden back when user clicks on a menu item in it, or clicks the toggle button. It also has gestures integrated if you swipe right at the very end of the left part of the screen, it will come out, and if you swipe the opposite direction, it will be closed again. You can have at most two Navigation Drawers - one on each side of the screen. The left one is usually used for navigation within the application. The right one is usually used for additional features such as notification history or any other history of changes in the app. To add Navigation Drawer, DrawerLayout element must be the root element in the activity layout. This means the navigation drawer is attached to one activity so the best solution is to keep all screens belonging to menu items of the Drawer in fragments switching one to another. <android.support.v4.widget.drawerlayout xmlns:android=" xmlns:tools=" android:id="@+id/drawer_layout" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".myactivity"> Root element in activity_my.xml layout DrawerLayout acts as a top-level container for window content that allows for interactive drawer views to be pulled out from the edge of the window. [4] There are usually just two child views in DrawerLayout. The first one is usually a content view a FrameLayout, where the usual main screen content is displayed and where screens built of Fragment are opened from the Navigation Drawer. The best practice is to set id of as many tutorials and examples refer to it. The second child view is a fragment element the drawer. You have to set its width element to a particular value. The usual value known from practice is 280dp, covering almost three quarters of the screen width when it is open. Another important value is the layout gravity to place it to either left or right side of the screen. Values named start and end will be proposed as the position of the drawer would be switched for RTL devices (RTL is a Right to Left support for countries whose written language is positioned from right to left and thus also all the layouts are positioned in the opposite direction. This means that start value refers 10

19 2.2 First exercise to left position in general, but will be positioned on the right side if RTL is present. This behavior is added from API 17 and higher). To easily add all Navigation Drawer functionality, Android Studio provides a range of different activities to generate when generating a new project or module. For generating Navigation Drawer behavior it is necessary to pick Navigation Drawer Activity. It will be automatically added to the xml layout of the Activity as well as the class object will be generated appropriately. NavigationDrawerFragment.java class contains an object referring to the drawer toggle, called mdrawertoggle. It is instantiated from ActionBarDrawerToggle class. Although default image is provided (three horizontal lines usually called a hamburger menu ), it is easy to change in the constructor. mdrawertoggle = new ActionBarDrawerToggle( getactivity(), /* host Activity */ mdrawerlayout, /* DrawerLayout object */ R.drawable.ic_drawer, /* nav drawer image to replace 'Up' caret */ R.string.navigation_drawer_open, /* "open drawer" description for accessibility */ R.string.navigation_drawer_close /* "close drawer" description for accessibility */ ) The last two items of the constructor are Strings indicating accessibility texts for drawer opening and drawer closing. They are called out loud when user accessibility options are switched on. This kind of behavior helps the visually impaired to navigate through apps by clicking on views. Once a View gets focus, it reads its description out loud. ActionBarDrawerToggle has three callback methods. Two of them listen to drawer opening and closing events, the third one is called when the drawer slides from the open state to closed or vice versa. This is where menu items for ActionBar are handled. When the drawer is opened, there might be certain global settings that would only be visible when no particular fragment is focused. But they have to be gone when the drawer closes. To update the ActionBar option items, getactivity().supportinvalidateoptionsmenu(); or getactivity().invalidateoptionsmenu() are called. Whether to use one or the other is decided based on whether the application uses a compatibility library called AppCompat. There is a listener implemented for MyActivity that listens to menu item clicks. If a menu item is clicked, the drawer is closed and an appropriate fragment is loaded. The listener is called NavigationDrawerFragment.NavigationDrawerCallbacks. 11

20 2.2 First exercise The listener calls its onnavigationdraweritemselected(int position), where the argument carries position of the menu item that was clicked. Beware, the menu is usually displayed in a ListView. ListViews can have a headerview and clicking the headerview calls the listener with the position of 0 value. If the headerview is not present, 0 value is the position of the first item in ListView. The last but not least thing to do is to setup the fragment in MyActivity by calling setup(int drawerid,drawerlayout drawer) method in oncreate() callback. DrawerId is the view id belonging to the drawer fragment and the second argument refers to the root element view of the activity called DrawerLayout. Does Navigation Drawer layout have to fill the whole screen height? If set the layout_height element to a specific value, its height can be easily adjusted to any wanted size. Additionally, the layout_gravity can be set to top, bottom, or center, according to where exactly on the screen it should be placed. Settings for this kind of behavior: <android.support.v4.widget.drawerlayout xmlns:android=" android:id="@+id/drawer_layout" android:layout_width="match_parent" android:layout_height="match_parent"> <fragment android:id="@+id/navigation_drawer" android:layout_width="@dimen/navigation_drawer_width" android:layout_height="100dp" android:layout_gravity="start bottom" android:name= "cz.muni.fi.pv256.zina.ui.navigationdrawerfragment" /> /> How to disable toggle button? In MyActivity: mnavigationdrawerfragment.setdrawertoggleenabled(false); 12

21 2.2 First exercise Fragment A Fragment represents a behavior or a portion of user interface in an Activity.[5] Fragments can replace activities to keep one screen-one activity rule or multiple fragments can be combined in one activity to create a multi-pane UI often used on tablets. One fragment can also be reused in multiple activities if the same behavior is required. A fragment cannot live without an Activity and the fragment s lifecycle is driven by that of the fragment s parent activity. Fragments are managed by a FragmentManager already mentioned above. It has all the necessary methods for storing, retrieving and attaching fragments. There are two ways of creating and adding a Fragment. Static attachment is made by declaring a fragment element in the xml layout file. The layout manager finds it, looks at the name attribute where the absolute path of the Java class for that Fragment is stored and creates the object according to the implemented behavior in the class. Navigation Drawer in our application is attached statically and the name attribute looks like this: android:name="cz.muni.fi.pv256.zina1.ui.navigationdrawerfragment" Another way of creating a fragment is to create it dynamically. In our application, fragments called from menu are added this way. For example, MessagesFragment creation looks like this: String fragmenttitle = ""; Fragment fragment = null; FragmentManager fragmentmanager = getsupportfragmentmanager(); switch (position) case 0: fragmenttitle = getresources().getstring(r.string.title_section1); fragment = fragmentmanager.findfragmentbytag( fragmenttitle); if (fragment == null) Log.i("Zina", "MyActivity creating new MessagesFragment"); fragment = new MessagesFragment(); fragmentmanager.begintransaction().settransitionstyle(fragmenttransaction.transit_fragment_open).replace(r.id.container, fragment, fragmenttitle).commit(); break; 13

22 2.2 First exercise Fragment title is retrieved from String resources. FragmentManager instance is stored in the ActionBarActivity because it extends FragmentActivity, as mentioned earlier. By calling findfragmentbytag(string) we try to find that particular fragment. If it was ever created in the past, it might be stored in the FragmentManager object. If it is not, a null object reference is returned and MessagesFragment object is instantiated. To add the fragment, fragmentmanager starts transaction by calling BeginTransaction() which returns a FragmentTransaction object. Then we can add the fragment by calling either add() or replace(). Add will simply store the fragment to the stack, whereas replace will remove the previous fragment and load the current fragment instead. Either way, the first argument is the id of the view that is marked as a content holder, or container the first child element in the DrawerLayout in our application. The second argument is the fragment object itself and the third argument is its label that will help finding the fragment in the next call. The last thing to do is to call commit() so that everything declared in the transaction is proceeded Action Bar ActionBar is a primary toolbar within the activity that may display the activity title, application-level navigation affordances, and other interactive items.[6] It was introduced with Android Honeycomb release (Android 3.0, API level 11). It is placed on top of the activity s window. With coming of Android Lollipop version, ActionBar will be represented by any Toolbar widget within the application layout. ActionBar is used to manifest the application s identity. It holds its title or a title referring to the content currently displayed on the screen. If the content displayed on the screen is searchable, ActionBar can contain a filter view that expands and collapses depending on the focus. It also can contain a progress bar in case the content of the screen si being refreshed or loaded. The most common use for Action Bar is to put Action Bar items to it. They usually are to manipulate the displayed content. In our app, the main option is to switch the theme of the application. In other screens there will be items to add a friend when the list of friends is displayed, or create a new message when users in the list are picked. ActionBar s visual style can be adjusted by changing theme and style attributes that will be mentioned later in this chapter. To change ActionBar title, getactionbar() from any Activity must be called to get the reference and then calling ActionBar.setTitle(String) will change the title as specified in the argument. 14

23 2.2 First exercise Can I disable ActionBar? ActionBar can be hidden by using one of Theme.NoActionBar themes. It can also be hidden programmatically by calling hide() on the object reference. By calling show() on the same object reference the ActionBar is shown again. This behavior could be used for nested fragments where ActionBar takes up much space that could be used for the detail content and no ActionBar features are necessary to use there Menu Menu items are added to ActionBar upon creation of the activity or fragment. To add required menu items to the activity s ActionBar, one must add them by inflating them from an xml file and adding to the Menu object returned in the callback method oncreateoptionsmenu as an argument. This is the place where menu items can be manually managed as access to the Menu object is available public boolean oncreateoptionsmenu(menu menu) getmenuinflater().inflate(r.menu.global, menu); int theme = getintent().getintextra(extra_theme, 1); if (theme == 0) menu.removeitem(r.id.action_lime); if (theme == 1) menu.removeitem(r.id.action_yellow); return true; Menu items are defined in an xml file located in the menu resources folder called menu. As with inflating layouts, the first argument is the file name of the xml menu file, so the path is defined as the relative path in resources in a form of R.menu.name. The other argument is the menu object to which the menu items should be added. Menu items can be added or removed also manually. We will do this for theme switchers. Originally, we will have two menu items and we will remove that menu item which is not relevant to the current theme. Manual management of menu items is though not recommended. Menu items can be displayed on ActionBar or can be hidden behind one ActionBar item with three dots on it, indicating there are all menu options that are not supposed 15

24 2.2 First exercise to be on or cannot fit in ActionBar layout. To hide an actionbar item we set app:showasaction to never, or, if only want it to be displayed when there is room for it (there can be room for it in landscape mode, but no room when in portrait mode), we set it to ifroom. OrderInCategory attribute is considered, when ordering items from left to right in the layout. If there are any menu items added, the method must return true, otherwise the items will not be displayed. If returned true, ActionBar will be invalidated, otherwise not. If Fragments also have any menu options, sethasoptions(true) must be called in oncreate() method of the Fragment. It is because if not set, oncreateoptionsmenu callback method is not called and menu items cannot be inflated. By inflating menu items, previous menu items are kept as long as their belonging activities or fragments exist in the view. In MyActivity, we inflate R.menu.global menu items. To implement onclick behavior we must override another callback method onoptionsitemselected. Clicked menu item will be returned in the argument of that method. By comparing its menu id we find out which menu item it is and we proceed actions declared specifically for it. The actual implementation of the theme switching will be explained later on as it is not technically specific to the ActionBar Menu behavior. This method must also return true to indicate the menu item click was processed. If false would be returned, onoptionsitemselected() method of the predecessor will be called. For instance, if Action Bar contains menu items from both the activity and its fragment, first the callback method of the fragment is called and if the menu id does not belong to any of the fragment menu items, false is returned and that menu item is processed in the activity s callback method. On the other hand, if it was processed in the fragment, returning true would prevent calling the callback method of the activity Tabs Tabs make it easy to explore and switch between different views or functional aspects of the application or browse categorized data sets [7]. In our application, we use tabs in the MessagesFragment for switching between a list of conversations with our friends and a list of friends that we can start a conversation with. 16

25 2.2 First exercise If a tab is clicked, its view is inflated into the content space. For a better user experience, also swiping between views is often required. For that, we will use ViewPager implementation. How to add tabs to ActionBar? When MessagesFragment is being created, it is necessary to add the tabs to the ActionBar. The best place to do so is in onactivitycreated() method to be sure ActionBar object is properly set. First of all, actionbar navigation mode must be set to the tab mode. Even though tabs are placed to a second line of ActionBar in portrait mode, they dive into the first line in the landscape mode if there is room. To manage this behavior, the tab mode must be set. ActionBar actionbar = ((MyActivity) getactivity()).getsupportactionbar(); actionbar.setnavigationmode(actionbar.navigation_mode_tabs); First and second tab are created by calling newtab() on actionbar. This will return a Tab object to which the tab text can be set via settext( ) method. This tab is then added to the actionbar via addtab() method. To be sure there are no other tabs, we call removealltabs() before adding new ones. actionbar.removealltabs(); ActionBar.Tab tab = actionbar.newtab().settext("recent").settablistener(tablistener); actionbar.addtab(tab); ActionBar.Tab tab1 = actionbar.newtab().settext("friends").settablistener(tablistener); actionbar.addtab(tab1); Now we have to add ViewPager that will hold views for all tabs. To enable switching pages and to be able to mark an appropriate tab as clicked when pages within ViewPager are swiped, we must create a listener in this chapter. Creating ViewPager will be described in the next chapter. ActionBar.TabListener has three callback methods, only one of which is important to implement ontabselected(). This method has a Tab that was clicked as one of its arguments. If a tab is clicked, we must set the ViewPager to the appropriate position. We get this position from the Tab object by calling tab.getposition(). pager.setcurrentitem(tab.getposition()); After the listener is implemented, we must set it to each tab we add to the Action Bar. Why is there a closedrawer() command in ontabselected()? 17

26 2.2 First exercise Although ActionBar tabs are not a good fit when using Navigation Drawer, because Navigation Drawer takes all of the space under the Action Bar and as Action Bar tabs are part of the ActionBar, so Navigation Drawer does not overlay them. That means, when Navigation Drawer is open, the tabs are visible to the user and user can click on them and although pages under the drawer are changing, it is not a good user experience for the user. To fix that UX issue, we close the drawer manually. We create two methods in MyActivity because we can reach MyActivity object from within a fragment (and we can reach drawer object form within the activity). We create isdraweropen() to determine if it is open when tab is clicked and closedrawer() to close the drawer. We also have to change drawer s isdraweropen() method from private to public to reach it from the activity and create close() method in there. The close method will simply call it s already implemented closedrawer(mfragmentcontainerview) method on the drawerlayout view. Can we fix this issue more nicely? Yes, we can use a 3rd party library created by Alexander Stuetz. It is very widely used for tabs implementation. Tabs are not bound to ActionBar anymore and so Navigation Drawer can finally overlay them. The library is called PagerSlidingTabStrip as its other main function is to be able to swipe between multiple tabs when there is not enough room to display them all one next to another in one line. Gradle path to the library is com.astuetz:pagerslidingtabstrip: Layout The layout element name must be declared fully to refer to the Java class file path com.astuetz.pagerslidingtabstrip. There are several attributes that can be customized. Since now we cannot use android core namespaces, we must tell the build tool to look for them in the library. For that we use a new namespace, xmlns:app= It is a static namespace, defined by Google, used by all libraries used in the project. In our project, we want to change the background color and the indicator of a clicked tab. Background is set in app:pststabbackground, indicator is set in app:pstsindicatorcolor. Since the newer platform versions include a selected state for draw able selectors, we use it to refer to the secondary color we choose for the currently used theme. We refer to it via?android:attr format. The full value is?android:attr/actionmodebackground. This will 18

27 2.2 First exercise simply set the indicator color to any color that is currently present in the theme attribute under that name. However, we still want to support old platform versions, so we split this layout into two folders (layout, layout-v11). The layout defined in the layout folder devoted for the old platform will simply not use that color, it will use a static color instead. Binding with ViewPager Binding with View Pager is even simpler than that of ActionBar tabs. After loading the view in onviewcreated method we set ViewPager to it by calling tabs.setviewpager(pager). Also pagechangelistener can be set directly to PagerSlidingTabStrip object. When a page is swiped, we will just save the newly displayed page so as to return to it in the next activity startup Styles and themes Styles and themes are often overridden when ActionBar, Spinner or other more complex layout attributes are to be customized. An application can usually have only one theme set at the same time, but a custom theme can be set for just one view. A theme is a set of styled attributes that can be referenced through?theme_attr form. The themed attributes are used as default attributes for views that do not have a particular attribute set explicitly by the developer. A style is a collection of properties that specify the look and format for a View [8]. A default theme is set in Android manifest file in the application element (android:theme attribute). We are going to use two different themes for the application Lime and Yellow. They are going to be set based on what the user picks before the MyActivity s contentview is set in oncreate() method. The appropriate theme will be picked based on what will be stored in the activity s intent s extra value. Activities are created by putting an Intent object into startactivity() method. An extra value is a key-value map, where we can adjust activity s behavior or look by sending values into it before creation. Here we set 0 for lime theme and 1 for the yellow theme. After calling startactivity(), current activity is killed by calling finish() to prevent the presence of two activities of the same kind. In the activity s oncreate method we get the Intent s extra value by calling getintent().getintextra(extra_theme, 1). EXTRA_THEME is a defined constant to keep calling the same label for both storing and loading the value to and from Intent. 19

28 2.2 First exercise The value 1 means that if no such value is stored in Intent (when Activity is first started), yellow theme will be default. The theme is overridden by calling settheme(r.style.theme_res_name). Now, all unspecified values will be loaded form the newly set theme. Namespaces There are various types of namespaces used in styles. It is due to a big fragmentation of the Android platform caused by indefatigable development and creation of new UI components that can be styled. For such cases support libraries are developed and to differ the namespace for an attribute from the core code and from the support library code, a different name must be used. Since our application supports devices all the way down to API 10, Gingerbread, and since Action Bar was introduced only in API 11, Honeycomb, lean back support had to be created for styling Action Bar on Gingerbread devices and a support library had to be added in build.gradle file compile "com.android.support:appcompat-v7:19.0.+" When using styles from the support library, it is supposed to be enough to cover all platform versions and it is supposed to run correctly. Unfortunately, some of the styles are not overridden properly for newer platform versions and so here comes in hand to split styles into two different values folders one marked as default ( values ) and one marked as specific to platforms newer than API 11 ( values-v11 ). This meaning, when a device runs our application, upon loading resources, it looks at its own platform version and tries to find the most suitable folder for it. Anything newer than API 11, Honeycomb will load the attributes from the values-v11 folder, anything lower than that will take them from the default folder. As for namespaces, they are usually called android:background with android: prefix, but for older platforms, where certain attributes are not present yet, we call the support library version of the attributes of the same name, only the android prefix is missing. How to make two themes out of one Generally, we derive from AppCompat.Light theme so we make it a parent of our main style called AppTheme. Then we create another two styles called AppTheme.Lime and AppTheme.Yellow. The dot in the name means that we want to override some other style with a name placed before the dot, so we take all styling from the AppTheme style created before. Another way of overriding a style is to put a parent attribute into style element. 20

29 2.2 First exercise How to style ActionBar (Yellow theme) In AppTheme.Yellow style we set actionbarstyle Since YellowActionBar is a defined style, we prepend the name annotation. YellowActionBar extends MyActionBar where common attributes are set. It then extends Widget.AppCompat.Light.ActionBar defined in the core SDK, extending from other styles and if we bubble up the predecessors, we can discover what all attributes for ActionBar we can change. <style name="widget.appcompat.base.actionbar" parent=""> <item name="displayoptions">uselogo showhome showtitle</item> <item name="divider">?attr/dividervertical</item> <item name="height">?attr/actionbarsize</item> <item name="homelayout">@layout/abc_action_bar_home</item> <item <item <item name="background">@drawable/abc_ab_transparent_dark_holo</item> <item name="backgroundstacked">@drawable/abc_ab_stacked_transparent_dark_holo</item> <item name="backgroundsplit">@drawable/abc_ab_bottom_transparent_dark_holo</item> <item name="actionbuttonstyle">@style/widget.appcompat.actionbutton</item> <item <item name="progressbarstyle">@style/widget.appcompat.progressbar.horizontal</item> <item name="indeterminateprogressstyle">@style/widget.appcompat.progressbar</item> </style> Background change background Title text color text color is defined in titletextstyle, so we change it to our own ActionBarTitle style which overrides the same parent style, then we simply set android:textcolor Items text color set actionmenutextcolor Items dropdown set popupmenustyle with a custom style PopupMenu and set popupbackground drawable selector How to style ActionBar Tabs Divider - actionbartabbarstyle is customized and to remove a divider we set android:divider original parent style is TabBar Background - background is set in actionbartabstyle overriding core TabView style Text color - text color along with text size and other text styles are set in actionbartabtextstyle with its parent being Widget.App Compat.Light.ActionBar.TabText 21

30 2.2 First exercise How to style ListView Selector - selector is the drawable resource that changes background based on whether the view is focused, selected, pressed, or normal; we customize listviewstyle and set listselector Why pagerslidingtabstrip tabs keep their position when switching theme and not when actionbar tabs are used? It is because tabs position of ActionBar tabs is kept only in the ActionBar object by calling setselectednavigationitem(). For PagerSlidingTabStrip we use SharedPreferences. SharedPreferences is a file storing key-value pairs of various types. Here we usually keep player scores in games or user related data needed for the next session. It might be compared to cookies in webpages. How to make custom attributes To make the navigation drawer menu fancy, instead of highlighting menu item s background we highlight its text. For that, we create a color selector based on whether the item is selected or not. We want to set it to a color that refers to the current theme, but there is not attribute for it. So we have to create it ourselves. We create attrs.xml file in values folder. Here, in resources element, we create a child element called declare-styleable. We set a name for it (textselector) and make another child element called attr, that will present an attribute, exactly like for example android:background is. We set a name for it and add a format attribute that will constrain values that can be used. Reference means we will set the value via an annotation to the drawable folder (@drawable). Back in styles file we set this attribute in both of the custom themes to lime and yellow text selector respectively. Both of these selectors must be declared in the drawable folder. That means that as many themes we have declared, so many selectors would have to be created for that. 22

31 2.3 Second exercise 2.3 Second exercise In the second exercise, we are going to work with ListViews and Adapters. We are going to add a header view to Navigation drawer s list view and we will have to adjust menu item positions as position of the headerview also counts in. There are several ListView types that extend their predecessors to enhance development speed. Also, listviews are primarily used for data of the same type, but their adapters are built so as to cope with different data types as well. This feature is mainly used when there is a possibility of selecting items and doing group operations on them. We have to tell the adapter that it has more than one datatype in its view for it to count with this information when it renders scrolling of the list ListView ListView is a very commonly used building block. It is a view group that displays a list of scrollable items. The list items are automatically inserted to the list using an Adapter that pulls content from a source such as an array or database query and converts each item result into a view that is placed into the list. [9] How about a Horizontal ListView? Android core SDK does not support a horizontal AdapterView other than a ViewPager, but there is a very easy-to-use library called TwoWayView that acts exactly like a ListView, but orientation can be changed between horizontal and vertical. It can also be changed dynamically Adapter Adapters are bridging classes that bind data to user-interface Views. The adapter is responsible for creating the child views used to represent each item and providing access to the underlying data. [10] User-interface controls that support Adapter binding must extend the AdapterView abstract class. It is possible to create your own AdapterView-derived controls and create new Adapter classes to bind them. BaseAdapter BaseAdapter is a base class for Adapter implementation. Besides being used for ListView, it can be also used for Spinner a specialiazed SpinnerAdapter extends this class, too. 23

32 2.3 Second exercise It is best practice to use exactly this class for adapter implementation in our application, although using of already existing specialized classes such as ArrayAdapter might be useful and could enhance the speed of development if a ListView with just one piece of information per List item were to be presented. We are going to focus on the main methods that must be overridden for proper functioning. The main and most important method is getview. After that, we must also implement our own behavior for getcount, getitem and getitemid so as to keep proper positioning and order of items. We usually pass the collection of data via adapter s constructor and store them in the adapter s global attribute. getview method returns a View object representing a list item in ListView. It is first brought to the method in its argument. If it is null, the layout is inflated by LayoutInflater object that searches for the layout xml file and loads the layout to that view object, often called convertview. After inflating it, we find the object that is supposed to be displayed at a given position and bind data into their corresponding fields within the layout. This method is called so many times as many List items can fit onto the screen. If scrolling is performed, the method is called again to load new views and reuse memory used for items that can be no longer visible. Data item from a collection being displayed is retrieved by calling getitem(int position) method. Here we can implement a special behavior for a case where there is no data provided for a specific position or the collection is null so that the application does not crash. Method getitemid(int position) usually returns the position itself. On the other hand, server driven applications often have an id for each item in the server database. Then it is best practice to return this id in this method. ArrayAdapter ArrayAdapter s construction was established on the idea that adapters are used for collections of data. ArrayAdapter already has a field and management mechanism for storing, adding and retrieving data represented as an array. The data can be of any type as Java reflection is used here. It also has filtering implementation ready to use. 24

33 2.3 Second exercise Its getview method is already implemented so it can be used right away. The only thing to be careful about is that the datatype s tostring() method is implemented as this is where resources for list items come from. public View getview(int position, View convertview, ViewGroup parent) return createviewfromresource(position, convertview, parent, mresource); private View createviewfromresource(int position, View convertview, ViewGroup parent, int resource) View view; TextView text; if (convertview == null) view = minflater.inflate(resource, parent, false); else view = convertview; try if (mfieldid == 0) // If no custom field is assigned, assume the whole resource is a TextView text = (TextView) view; else // Otherwise, find the TextView field within the layout text = (TextView) view.findviewbyid(mfieldid); catch (ClassCastException e) Log.e("ArrayAdapter", "You must supply a resource ID for a TextView"); throw new IllegalStateException( "ArrayAdapter requires the resource ID to be a TextView", e); T item = getitem(position); if (item instanceof CharSequence) text.settext((charsequence)item); else text.settext(item.tostring()); return view; CursorAdapter CursorAdapter is very similar to an ArrayAdapter, but the data is provided and stored in a Cursor, whose implementation is very similar to that of Iterator s. We will use CursorAdapter for ListViews that load data from the database. Its internal getview method does exactly the same as that of BaseAdapter s. If convertview is null, it calls newview method that must be overriden. If convertview already has an instance stored, bindview is called to bind data to its corresponding views. BindView thus must be also overridden. public View getview(int position, View convertview, ViewGroup parent) if (!mdatavalid) throw new IllegalStateException("this should only be called when the cursor is valid"); 25

34 2.3 Second exercise if (!mcursor.movetoposition(position)) throw new IllegalStateException("couldn't move cursor to position " + position); View v; if (convertview == null) v = newview(mcontext, mcursor, parent); else v = convertview; bindview(v, mcontext, mcursor); return v; Usage When our adapter is setup, we bind it to ListView. Whenever new data are passed to the adapter, we call notifydatasetchanged() on Adapter which will cause reloading of all ListView items. peoplelist.setadapter(peopleadapter); peopleadapter.add(person); peopleadapter.notifydatasetchanged(); Optimization As already has been said, ListView controls which list items are currently created and fetches data for list items from its adapter. When scrolling, list items are created and destroyed according to the current position within the list view. If we were scrolling up and down, the same items would be created and destroyed again and again. To prevent this behavior and to smooth out loading, a ViewHolder pattern was introduced. We create a static class ViewHolder in each of our Adapter classes. We create fields for each of the bound items. When getting view for a particular position, we set an instance of ViewHolder as a tag to its convertview. A tag is an object that we can assign to any other object. So if convertview is not null, we load this instance from its tag and set appropriate values for given position or we inflate the layout and set a new instance of ViewHolder to it. public static class ViewHolder RoundedImageView roundedimageview; TextView nameview; TextView public View getview(int position, View convertview, ViewGroup parent) ViewHolder viewholder = null; if (convertview == null) LayoutInflater minflater = (LayoutInflater) context.getsystemservice(activity.layout_inflater_service); convertview = minflater.inflate(resourceid, null); 26

35 2.3 Second exercise viewholder = new ViewHolder(); viewholder.roundedimageview = (RoundedImageView) convertview.findviewbyid(r.id.friendlist_photo); viewholder.nameview = (TextView) convertview.findviewbyid(r.id.friendlist_name); convertview.settag(viewholder); else viewholder = (ViewHolder) convertview.gettag(); User user = users.get(position); viewholder.nameview.settext(user.name); return convertview; Multiple data types in one list Adapters usually bind data from a collection of data of the same type. However, sometimes we want to differentiate List View items. The most common example is when we want to enable selection and group operations. Most commonly selection is done by highlighting background of items and while scrolling, selection might get mixed up with previous and following items. To prevent this we override some methods: getviewtypecount() returns number of different views in a listview, for selection usually returns 2 getitemviewtype() returns a type represented by a number for the actual view that is supposed to be rendered at given position, usually returned values are 0 for a regular position, 1 for selected position ViewPager As was mentioned before, ViewPager takes care of switching between pages representing views, each belonging to one tab or any data item in any collection. ViewPager layout The layout element is called android.support.v4.view.viewpager. The absolute path must be declared because ViewPager comes from the support library. Binding with tabs To bind ActionBar tabs we must do the binding both ways. When a tab is clicked and its ontabselected listener method called, we set the corresponding page as current by calling pager.setcurrentitem(tab.getposition). 27

36 2.3 Second exercise If the pager is swiped, we want the tabs to move the clicked state to the appropriate tab as well, so we set a listener to that event. pager.setonpagechangelistener( new public void onpageselected(int position) // When swiping between pages, select the // corresponding tab. getactionbar().setselectednavigationitem(position); ); When a new page is swiped to, onpageselected() method is called with the position of this view as an argument. Here we must select the navigation item at the same position in the ActionBar tabs by calling ActionBar.setSelectedNavigationItem(int position). Binding data to pages ViewPager holds on to a set of data, each data item representing one page view. To generate a corresponding size and bind the data items to the corresponding place we use PagerAdapter. Adapter takes care of creating and destroying views to save space and keep only those views that are necessary to be ready to be displayed. Usually it is the current view, the previous view and the next view. After each swipe, one new view is created and one redundant view is destroyed. We want to have each page represented by Fragment and for that we use FragmentPagerAdapter. We pass a FragmentManager instance in constructor. Usually we use the fragmentmanager stored in Activity. In this case, ViewPager is placed not in Activity but in MessagesFragment. Thus, we have to use its own fragment manager, because if we pass the fragment manager from the parent activity, the flow of the child fragments would be managed by the flow of the activity, not the flow of the parent fragment (MessagesFragment). We retrieve this fragment by calling getchildfragmentmanager(). Three methods must be overridden. The last method to override is getpagetitle(int position) that provides a title for each page. GetCount() returns the total number of pages. We keep it hardcoded to 2, because the number of pages is static. Usually there is a collection of data stored as a global attribute of the pager and in that case its size would be returned. 28

37 2.4 Third exercise GetItem(int position) returns the specific fragment instance. In our case, if position in the argument equals 0, we return RecentMessagesFragment, otherwise we return FriendsFragment. Fragments are stored in the fragment manager passed to the constructor, so it is not bad practice to return a newly instantiated fragment object. GetItem() method is only called if there is no fragment stored for a particular position. 2.4 Third exercise In the third exercise, we are going to look further at ActionBar group operation feature and how to handle device orientation changing. This chapter is again going to be somewhat shorter due to a more complex implementation of this feature. It is going to be implemented at two places, firstly, when picking people from a list of all users to add them to user s friends, secondly when creating a new message that can be sent not only to one person, but to a group of people sharing one conversation. Last but not least, we are going to cover communication between fragments and Parcelable interface. When new friends are added in AddFriendsFragment, they are immediately sent to FriendsFragment and displayed. To do so, we must wrap the list of users so that it can be represented as a String and then unwrapped to its original structure in FriendsFragment Contextual Action Bar The contextual action bar (CAB) is a temporary action bar that overlays your app's current action bar while data is selected. It appears after the user long-presses on a selectable data item. [11] To have access to CAB manipulation we create a field of ActionMode type in our Fragment class, AddFriendsFragment and FriendsFragment. Also several types of events such as switching on CAB, switching it off or creating menu items for it, must be listened to, so we create an ActionMode.Callback field that will be instantiated as an anonymous class. Why is CAB called Contextual? ActionBar in this mode contains options for group operations working only in the context of this one particular collection of objects. For example, CAB is inflated when highlighting a word in a text. In that case, cut, copy and paste options are shown. 29

38 2.4 Third exercise CAB is started when user long-presses an item within a list view. startactionmode() runs oncreateactionmode() listener method with ActionMode and Menu arguments. ActionMode instance is the instance being prepared, Menu instance is the one that will populate action buttons in ActionBar. To inflate menu items into the Menu instance we must use MenuInflater which is possible to get from ActionMode public boolean oncreateactionmode(actionmode actionmode, Menu menu) // Inflate a menu resource providing context menu items MenuInflater inflater = actionmode.getmenuinflater(); inflater.inflate(r.menu.context_menu, menu); return true; The method must return true if any menu items are to be inflated into the menu object. Otherwise they would not be displayed, as it would happen in a regular Menu case. The second listener callback, onprepareactionmode, is called when CAB is invalidated or any changes are done to CAB. Usually returns false, as far as nothing is changed in there. When user clicks on menu items, onactionitemclicked is called. Its behavior is related to that of onoptionsmenuitemclicked method in ActionBar menu callbacks. MenuItem and ActionMode are passed via arguments, by comparing id of the menu item we determine, which item was pressed and we do appropriate actions according to it. If the press action should be processed in this method, we return true, otherwise we return false and the onoptionsmenuitemclicked of the regular ActionBar is called. Every time we click the item in the CAB, the CAB should be closed by calling actionmode.finish(). It s because most likely the user is done with editing a group of items, such as when the user picks a group of contacts to be public boolean onactionitemclicked(actionmode actionmode, MenuItem menuitem) switch (menuitem.getitemid()) case R.id.action_new_message: actionmode.finish(); ArrayList<User> recipients = (ArrayList<User>) friendadapter.getcheckedusers(); Intent intent = new Intent(getActivity(), ConversationActivity.class); intent.putparcelablearraylistextra("recipients", recipients); startactivity(intent); return true; case R.id.action_remove_friends: actionmode.finish(); return true; default: return false; 30

39 2.4 Third exercise When finish() is called on ActionMode, it makes ondestroyactionmode callback method to be proceeded. This is where we unassigned our ActionMode field and make it null so that it says that the action mode is not switched on at the time. So every time an item in a list view is clicked, we check whether ActionMode is on or off and we continue public boolean onitemlongclick(adapterview<?> parent, View v, int position, long id) if (mactionmode!= null) return false; mactionmode = ((MyActivity)getActivity()).startSupportActionMode(mActionModeCallback); return true; Handling configuration changes Android handles runtime changes to the language, location, and hardware by terminating and restarting the active Activity. This forces the resource resolution for the Activity to be reevaluated and the most appropriate resource values for the new configuration to be selected. [12] This is default behavior and sometimes we do not want it to happen. As for orientation, sometimes different screens are displayed for landscape and portrait mode and so it is a good use to restart the activity and recreate the layout. But most of the times we want the layout to stay the same, it just is supposed to stretch itself to different screen dimensions. In such case, we want to turn off the default behavior. To do so, we must tell the application that we are going to handle the screen orientation by ourselves. This is done in the main AndroidManifest.xml file in the tag for the particular activity. <activity android:name=".ui.myactivity" android:label="@string/app_name" android:configchanges="orientation" > In the activity lifecycle methods, there is one called onconfigurationchanged(). When orientation is changed, this method is called if configchanges is set to orientation. Here we usually do nothing special as we want to keep the activity the same, we just do not want it to restart. 31

40 2.4 Third exercise Other configuration states that can be overridden this way are keyboard appearance (keyboardhidden), language (location) and many others Fragment communication Sometimes we need two fragments to communicate together and send various values to each other. For that, we are going to set a target fragment to AddFriendsFragment. When users are picked to be added as new friends, we retrieve this target fragment and call its onactivityresult() method. This method will receive the list of friends in an Intent object and add it to the end of the list in its adapter. After that, notifydatasetchanged() method is called in order to rebuild ListView items to display newly added public boolean onoptionsitemselected(menuitem item) if (item.getitemid() == R.id.action_add_friend) AddFriendsFragment fragment = new AddFriendsFragment(); fragment.settargetfragment(this, 666); getactivity().getsupportfragmentmanager().begintransaction().add(r.id.container, fragment).addtobackstack("addfriends").commit(); return public boolean onactionitemclicked(actionmode actionmode, MenuItem menuitem) if (menuitem.getitemid() == R.id.action_add_friend)... intent.putparcelablearraylistextra("friends", (ArrayList<? extends android.os.parcelable>) addedusers); gettargetfragment().onactivityresult(666, 200, intent); Parcelable interface In the previous example, we set the list of new friends to the Intent object via putparcelable ArrayListExtra method. This method takes the ArrayList and converts it to the Parcelable object. To do so, the items in the list must implement Parcelable interface. This way we can make sure all properties of the list item are able to be converted to a String form. To use the interface, we must implement wrapping and unwrapping of its properties. Since we want to operate with a list of users, we must implement a CREATOR class to hanlle it. 32

41 2.4 Third exercise For wrapping we override writetoparcel method. We assign all the values to the Parcel object coming from public void writetoparcel(parcel dest, int flags) dest.writelong(id); dest.writestring(name); dest.writestring( ); dest.writestring(photo); dest.writevalue(currentlocation); dest.writelong(lastupdatedlocation.gettime()); dest.writebyte((byte) (isonline? 1 : 0)); dest.writelong(lasttimeonline.gettime()); dest.writestring(accesscode); dest.writestringarray(devices.toarray(new String[])); dest.writestringarray(friends.toarray(new String[])); Then at some point we want to unwrap those properties. We must make sure the order of unwrapping corresponds to the order of wrapping. To unwrap properties, a private constructor is used. private User(Parcel in) id = in.readlong(); name = in.readstring(); = in.readstring(); photo = in.readstring(); currentlocation = (LatLng) in.readvalue(latlng.class.getclassloader()); lastupdatedlocation = new Date(in.readLong()); isonline = in.readbyte() == 1; lasttimeonline = new Date(in.readLong()); accesscode = in.readstring(); devices = in.readarraylist(string.class.getclassloader()); friends = in.readarraylist(string.class.getclassloader()); The CREATOR class must be present for the interface to use it when necessary when a Bundle object is being created so that it know what object type it works with. public static final Creator<User> CREATOR = new public User createfromparcel(parcel source) return new User(source); public User[] newarray(int size) return new User[size]; 33

42 2.5 Fourth exercise 2.5 Fourth exercise In this chapter, we are going to learn more about UI elements and how to make them responsive and dynamic. Firstly, selectors enable us to specify a different drawable to each state of the View to which it has been assigned. Most native Android Views use State List Drawables, including the image used on Buttons, and the background used for standard List View items. Secondly, there are situations where you have to create your own shape. For that Android provides its own solution by declaring it in XML files. 9-patch images make it easy to support different screen sizes and their structure allows them to stretch across the specified space and still keep their shape nice and smooth Selectors Selectors, or State List Drawables are xml based specifications to smoothly adjust background of a View to a drawable marking a specific state. In our application, we are going to use them for button presses and list view clicks. They are placed in the default drawable folder. <?xml version="1.0" encoding="utf-8"?> <selector xmlns:android=" <item android:state_pressed="true" android:color="@color/turquoise"/> <item android:state_focused="true" android:color="@color/turquoise"/> <item android:state_activated="true" android:color="@color/turquoise"/> <item android:color="@color/black"/> </selector> Selectors can have combined states to better specify the exact state of the button. For example, we want to have a different behavior for a button that is clicked or not clicked, but is also either in selected or deselected state. <?xml version="1.0" encoding="utf-8"?> <selector xmlns:android=" <item android:state_pressed="true" android:state_selected= false android:color="@color/grey"/> <item android:state_pressed="true" android:state_selected= true android:color="@color/turquoise"/> <item android:color="@color/black"/> </selector> 34

43 2.5 Fourth exercise When View is going to pick a background, it goes down through the list one by one and picks the first state that matches the state of the view. That meaning, if View is in pressed and selected state, in the first example it matches the very first color state. However, it would pick the second item in the second example, because although it matches the pressed state value, it does not match the selected value set to false, compared to the second pressed state set to true. <Button style="@style/mybutton" android:id="@+id/register_ " android:layout_width="match_parent" android:layout_height="match_parent" android:text="@string/register_with_ " android:background="@drawable/login_idle_selector_bg" android:onclick="onclick" /> Selector represents a background and thus is set to a view in the android:background attribute. For listview selectors, there are two options either the selector is set for the background, or there is a color for the background and the selector is placed on top of it. The selector drawable is then set in android:selector,android:drawselectorontop should be enabled in that case Custom drawables In our application, we have a profile picture with a circular shape as circular shapes are very modern nowadays. Every View is of rectangular shape, as it is the easiest shape to compute and draw. To change the shape, we must pass the background attribute a custom drawable object declared in an xml layout. The root element will be shape, in which android:shape= oval will be set. From API 21, Lollipop, also circle shape is present. To make oval circular, we must set its height and width the same value. Size and fill type are set as child elements of the shape element. To fill the shape with a color we pick a solid element, to make a border around it we pick a stroke element. The color is passed as element attribute to either of them. Size is declared in size child element with attributes width and height. <shape xmlns:android=" android:shape="oval"> 35

44 2.5 Fourth exercise <solid <size android:width="48dp" android:height="48dp"/> </shape> Another common case is to make multi-layered backgrounds. Since only one color or drawable can be set for one View, we have to create the drawable with multiple layers. When the drawable is being created, the layers defined earlier are also drawn first at the bottom. <layer-list xmlns:android=" > <item <item android:left="24dp" android:right="24dp" /> <item android:bottom="48dp" /> </layer-list> The first layer will be of colored yellow, which will be visible on the left and right side with a width of 24dp. That size is defined by the second layer that will overlay it and has left and right padding set to 24dp. The third layer will overlay both of them and will show only the bottom part of both of them as it only has padding from the bottom side with the size of 48dp. Layers can as well be created out of drawables, or combination of colors and drawables can be used as well patch images The NinePatch class permits drawing a bitmap in nine or more sections. Essentially, it allows creation of custom graphics that will scale the way that you define, when content added within the image exceeds the normal bounds of the graphic. [15] 36

45 2.5 Fourth exercise To make an image 9-patch, we have to add a border 1 pixel wide on each side. Left and top borders are meant to mark pixels that will say what part of the image should be repeated if the image is to be stretched. Bottom and right borders show what part of the image will respond to padding values. The 9-patch drawable can be drawn in any image editor, but.9.png must be appended to the file name so as to parse it as 9-patch. Padding box will determine where text on buttons or in textviews will be laid out Animations Animations are good means to fancy up interaction with users and put user experience to a higher level. Animations can be set in an xml or dynamically in code. The easiest way is to get a ViewPropertyAnimator instance and make it take care of handling animations. ViewPropertyAnimator is though available only from API 12. ViewPropertyAnimator is a View s attribute and is retrieved when animate() is called on View. Then actions are set to this attribute and after startanimation() is called, it starts animating while cancelling all previous animations. Animations that can be done via ViewPropertyAnimator are X and Y property positioning, X and Y transition, 3D rotation in X and Y direction (no 2D rotation available), scaling and changing alpha property. We are going to make our listview items jump or rotate when clicked. We must set the duration to a rather lower number (in milliseconds) so that the jump looks quite natural. v.animate().yby(-50).setduration(100).setlistener(new public void onanimationstart(animator public void onanimationend(animator animation) 37

46 2.5 Fourth exercise v.animate().yby(50).setduration(100).setlistener(null); public void onanimationcancel(animator public void onanimationrepeat(animator animation) We can animate an object either to a position or by a specific number of pixels. For the jump animation it is better to animate by pixels so that we know by how many pixels the view should come down. When the first half of the animation ends, onanimationend of a listener that was set to the animator is called and the opposite animation is started and we remove the listener so that it does not react to the end of the animation again because every view has just one ViewPropertyAnimator and by calling animate(), the object is not recreated, nor it has listeners removed. public ViewPropertyAnimator animate() if (manimator == null) manimator = new ViewPropertyAnimator(this); return manimator; When an object is translated by animation, it s X and Y position value is not changed at all. After translating an object, when View.getX() is called, it will return the exact same value as before. To find out if an object was translated, View.getTranslationX() must be called. Rotation is as easy and as similar. v.animate().rotationyby(720).setduration(500); What to do on devices with lower API than 12? A nineoldandroids ObjectAnimator class can be used. The library can be retrieved from gradle by calling compile 'com.nineoldandroids:library:2.4.0'. Then instead of view.animate() we call ObjectAnimator.ofFloat(view, "rotationx", 0, 720).setDuration(1000).start(); 38

47 2.6 Fifth exercise 2.6 Fifth exercise Network communication is a huge part of Android development. Due to small capacity, either from the memory size aspect or battery life, every larger application is usually connected to and communicates with a server so background operations and HTTP communication are very important to be maintained well because too many uncontrolled HTTP requests cause quick battery drain as the device never sleeps. The second most important thing is to use appropriate amount of threads so that the application does not slow down when user interacts with it along with downloading files, for instance. In this exercise, we are going to add requests to register user via and password, get users and add friends. We are going to use various 3rd party libraries to handle image downloads and caching and different classes to manage requests. For registration, we must add a new Activity Networking DefaultHttpClient and JSON via StringEntity We are going to register user via sending , password and a profile picture wrapped in a JSON object and embedded into a StringEntity. DefaultHttpClient is a standard java http client from apache library. We create an instance of HttpPost object that takes a URL as an argument. Then we create a StringEntity object that will take the JSON object and encoding type as arguments. We will add a header to the HttpPost object stating that we are sending content type of JSON format. We set the StringEntity to HttpPost and call execute on the DefaultHttpClient instance passing it the HttpPost request. Execute call will return a response of type HttpResponse. We execute the request synchronously. HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost( " StringEntity stringentity = new StringEntity(jsonObject.toString(), "UTF-8"); httppost.addheader("content-type", "application/json"); httppost.setentity(stringentity); HttpResponse response = httpclient.execute(httppost); JSON object manipulation For JSON object manipulation, we can use two libraries Gson (org.google.gson) package by Google or Json (org.json). 39

48 2.6 Fifth exercise JSON is an abbreviation for JavaScript Object Notation according to RFC4627. It is a lightweight, text-based. Language-independent data interchange format. JSON defines a small set of formatting rules for the portable representation of structured data. The data comes in key-value pairs and together with,,[,] symbols represents JSON Objects and JSON Arrays that can be parsed out of one line of String formatted stream of characters. Besides objects and arrays, it can represent three other primitive types numbers, booleans and a null value. String usage is obvious and trivial as JSON is usually transferred in its String format. Gson library Gson library is very useful when we want to deserialize a JSON array of JSON objects to a list of objects with a corresponding type. To convert it, we must first declare a list type that should be used for conversion. Type listtype = new TypeToken<List<User>>().getType(); if (jsonobject.has("friends")) ArrayList<User> friends = new Gson().fromJson(jsonObject.get("friends").toString(), listtype); friendadapter.setfriends(friends); OkHttpClient OkHttpClient is an excellent class created by the Square company. The class takes care of all usual network errors and is able to recover after common failures. We are going to use a Call class coming from the same library to call asynchronous requests. To make a post request we use another class from the same library called Request. We create Http client by instantiating OkHttpClient. Then we add the request by calling newcall() method on the OkHttpClient and pass it the request instance. This will return a Call object and by calling enqueue(), the request will be added to the request queue and executed at some point. In the enqueue() method, we create a Callback listener that will return a Response in onresponse method or will fail and return the original request in onfailure method. Request request = new Request.Builder().url(" + ZinaUtil.getUserId()).build(); final OkHttpClient client = new OkHttpClient(); Call call = client.newcall(request); call.enqueue(new public void onfailure(request request, IOException e)... Message message = new Message(); Bundle bundle = new Bundle(); 40

49 2.6 Fifth exercise bundle.putint("status", 404); message.setdata(bundle); handler.sendmessage(message); public void onresponse(response response) throws IOException Message message = new Message(); Bundle bundle = new Bundle(); bundle.putint("status", response.code()); message.setdata(bundle); handler.sendmessage(message); We use a Handler object to refresh the list of users so that currently added friends are removed from the list. A Handler object is a good means to receive messages from other processes. To implement it, we create a new Handler object and override its handlemessage() method. The message will contain any necessary data for it to take actions. private final Handler handler = new public void handlemessage(message msg) peoplelist.setadapter(peopleadapter); peopleadapter.notifydatasetchanged(); ; Retrofit Retrofit is a library released by a company very active in distributing their libraries into open source world - Square. It is a type-safe REST client for Android and Java. It creates an interface out of REST API. The RestAdapter generates its implementation. Each of the HTTP methods are annotated to describe themselves an annotation for the kind of HTTP request method type (POST, PUT, GET, DELETE..), an object type to which the response is supposed to convert List<User> getusers(@path("userid") long Response getfriends(@path("userid") long userid); Then in code, we just generate an object that contains all API calls as methods and we simply call them. All responses as well as requests are handled through JSON serialization. RestAdapter restadapter = new RestAdapter.Builder().setEndpoint(ApiService.URL).setLogLevel(RestAdapter.LogLevel.FULL).build(); 41

50 2.6 Fifth exercise ApiService service = restadapter.create(apiservice.class); retrofit.client.response friendsresponse = service.getfriends(zinautil.getuserid()); Threads Each Android application has at least one thread running when it is started the main thread, often called the UI thread. The runtime keeps its own threads in the system thread group. To execute network operations, we must do it in a separate thread so that we do not have the main thread do too much work which could result in bad user experience. There are two ways to execute code in threads. One is by subclassing Thread class where its run() method must be overridden with a specific implementation. The other way is to construct a new instance of a Thread and pass a Runnable object to the constructor. To start the execution, start() method must be called. Another way is to create an AsyncTask class and do the network operations in its doinbackground() method. It runs in the background and once it is finished, it will return its result in onpostexecute() method that will run again in the UI thread so we can again operate with UI objects. new AsyncTask<Void, Void, protected void onpostexecute(jsonobject jsonobject) protected JSONObject doinbackground(void... params) Return friends;.execute(); Server API The Server API is usually given by the server programmers in a form of a documentation where every server method is presented, its usage is described, its HTTP method is specified and server responses for several cases are detailed. Our API is described online at and is available to anyone that is invited to the project collaboration. 42

51 2.7 Sixth exercise 2.7 Sixth exercise In the sixth exercise, we are going to add a database so that we do not have to create so many request for each step in the application. We are going to store friends into the database and retrieve them from there every time new friends are added. Also messages will be stored in the database Database The Android system uses databases to store useful information that needs to be persisted even when the user kills the application or even shuts down the device and powers it back on. The data includes contacts, system settings, bookmarks, and so on. [13] It is useful to store data locally on the device so as to access it more quickly and have data available even when the device is offline. So the database then acts like a cache. SQLiteDatabase SQLite database is very simple to use. There is no database configuration needed and the database does not have a server. The database is stored in a single file and thanks to 43

EMBEDDED SYSTEMS PROGRAMMING UI and Android

EMBEDDED SYSTEMS PROGRAMMING UI and Android EMBEDDED SYSTEMS PROGRAMMING 2016-17 UI and Android STANDARD GESTURES (1/2) UI classes inheriting from View allow to set listeners that respond to basic gestures. Listeners are defined by suitable interfaces.

More information

ACTIVITY, FRAGMENT, NAVIGATION. Roberto Beraldi

ACTIVITY, FRAGMENT, NAVIGATION. Roberto Beraldi ACTIVITY, FRAGMENT, NAVIGATION Roberto Beraldi Introduction An application is composed of at least one Activity GUI It is a software component that stays behind a GUI (screen) Activity It runs inside the

More information

Understanding Application

Understanding Application Introduction to Android Application Development, Android Essentials, Fifth Edition Chapter 4 Understanding Application Components Chapter 4 Overview Master important terminology Learn what the application

More information

UI Fragment.

UI Fragment. UI Fragment 1 Contents Fragments Overviews Lifecycle of Fragments Creating Fragments Fragment Manager and Transactions Adding Fragment to Activity Fragment-to-Fragment Communication Fragment SubClasses

More information

Action Bar. Action bar: Top navigation bar at each screen The action bar is split into four different functional areas that apply to most apps.

Action Bar. Action bar: Top navigation bar at each screen The action bar is split into four different functional areas that apply to most apps. 1 Action Bar Action bar: Top navigation bar at each screen The action bar is split into four different functional areas that apply to most apps. 1) App Icon 3) Action Buttons 2)View Control 4) Action Overflows

More information

CS371m - Mobile Computing. More UI Action Bar, Navigation, and Fragments

CS371m - Mobile Computing. More UI Action Bar, Navigation, and Fragments CS371m - Mobile Computing More UI Action Bar, Navigation, and Fragments ACTION BAR 2 Options Menu and Action Bar prior to Android 3.0 / API level 11 Android devices required a dedicated menu button Pressing

More information

CS371m - Mobile Computing. More UI Navigation, Fragments, and App / Action Bars

CS371m - Mobile Computing. More UI Navigation, Fragments, and App / Action Bars CS371m - Mobile Computing More UI Navigation, Fragments, and App / Action Bars EFFECTIVE ANDROID NAVIGATION 2 Clicker Question Have you heard of the terms Back and Up in the context of Android Navigation?

More information

Fragments were added to the Android API in Honeycomb, API 11. The primary classes related to fragments are: android.app.fragment

Fragments were added to the Android API in Honeycomb, API 11. The primary classes related to fragments are: android.app.fragment FRAGMENTS Fragments An activity is a container for views When you have a larger screen device than a phone like a tablet it can look too simple to use phone interface here. Fragments Mini-activities, each

More information

Tablets have larger displays than phones do They can support multiple UI panes / user behaviors at the same time

Tablets have larger displays than phones do They can support multiple UI panes / user behaviors at the same time Tablets have larger displays than phones do They can support multiple UI panes / user behaviors at the same time The 1 activity 1 thing the user can do heuristic may not make sense for larger devices Application

More information

Understand applications and their components. activity service broadcast receiver content provider intent AndroidManifest.xml

Understand applications and their components. activity service broadcast receiver content provider intent AndroidManifest.xml Understand applications and their components activity service broadcast receiver content provider intent AndroidManifest.xml Android Application Written in Java (it s possible to write native code) Good

More information

Android Navigation Drawer for Sliding Menu / Sidebar

Android Navigation Drawer for Sliding Menu / Sidebar Android Navigation Drawer for Sliding Menu / Sidebar by Kapil - Tuesday, December 15, 2015 http://www.androidtutorialpoint.com/material-design/android-navigation-drawer-for-sliding-menusidebar/ YouTube

More information

Activities and Fragments

Activities and Fragments Activities and Fragments 21 November 2017 Lecture 5 21 Nov 2017 SE 435: Development in the Android Environment 1 Topics for Today Activities UI Design and handlers Fragments Source: developer.android.com

More information

Android Basics. Android UI Architecture. Android UI 1

Android Basics. Android UI Architecture. Android UI 1 Android Basics Android UI Architecture Android UI 1 Android Design Constraints Limited resources like memory, processing, battery à Android stops your app when not in use Primarily touch interaction à

More information

CS 4518 Mobile and Ubiquitous Computing Lecture 4: Data-Driven Views, Android Components & Android Activity Lifecycle Emmanuel Agu

CS 4518 Mobile and Ubiquitous Computing Lecture 4: Data-Driven Views, Android Components & Android Activity Lifecycle Emmanuel Agu CS 4518 Mobile and Ubiquitous Computing Lecture 4: Data-Driven Views, Android Components & Android Activity Lifecycle Emmanuel Agu Announcements Group formation: Projects 2, 3 and final project will be

More information

Mobile Computing Fragments

Mobile Computing Fragments Fragments APM@FEUP 1 Fragments (1) Activities are used to define a full screen interface and its functionality That s right for small screen devices (smartphones) In bigger devices we can have more interface

More information

Android Essentials with Java

Android Essentials with Java Android Essentials with Java Before You Program o Exercise in algorithm generation Getting Started o Using IntelliJ CE Using Variables and Values o Store data in typed variables Static Methods o Write

More information

MATERIAL DESIGN. Android Elective Course 4th Semester. June 2016 Teacher: Anders Kristian Børjesson. Ovidiu Floca

MATERIAL DESIGN. Android Elective Course 4th Semester. June 2016 Teacher: Anders Kristian Børjesson. Ovidiu Floca MATERIAL DESIGN Android Elective Course 4th Semester June 2016 Teacher: Anders Kristian Børjesson Ovidiu Floca 1 CONTENTS 2 Introduction... 2 3 Problem Definition... 2 4 Method... 2 5 Planning... 3 6 Watching

More information

Multiple devices. Use wrap_content and match_parent Use RelativeLayout/ConstraintLayout Use configuration qualifiers

Multiple devices. Use wrap_content and match_parent Use RelativeLayout/ConstraintLayout Use configuration qualifiers Multiple devices Multiple devices Use wrap_content and match_parent Use RelativeLayout/ConstraintLayout Use configuration qualifiers Create a new directory in your project's res/ and name it using the

More information

CE881: Mobile & Social Application Programming

CE881: Mobile & Social Application Programming CE881: Mobile & Social Application Programming, s, s and s Jialin Liu Senior Research Officer Univerisity of Essex 6 Feb 2017 Recall of lecture 3 and lab 3 :) Please download Kahoot or open a bowser and

More information

ANDROID APPS DEVELOPMENT FOR MOBILE AND TABLET DEVICE (LEVEL I)

ANDROID APPS DEVELOPMENT FOR MOBILE AND TABLET DEVICE (LEVEL I) ANDROID APPS DEVELOPMENT FOR MOBILE AND TABLET DEVICE (LEVEL I) Lecture 3: Android Life Cycle and Permission Android Lifecycle An activity begins its lifecycle when entering the oncreate() state If not

More information

05. RecyclerView and Styles

05. RecyclerView and Styles 05. RecyclerView and Styles 08.03.2018 1 Agenda Intents Creating Lists with RecyclerView Creating Cards with CardView Application Bar Menu Styles and Themes 2 Intents 3 What is Intent? An Intent is an

More information

ANDROID APPS DEVELOPMENT FOR MOBILE AND TABLET DEVICE (LEVEL I)

ANDROID APPS DEVELOPMENT FOR MOBILE AND TABLET DEVICE (LEVEL I) ANDROID APPS DEVELOPMENT FOR MOBILE AND TABLET DEVICE (LEVEL I) Lecture 3: Android Life Cycle and Permission Entire Lifetime An activity begins its lifecycle when entering the oncreate() state If not interrupted

More information

Designing and Implementing Android UIs for Phones and Tablets

Designing and Implementing Android UIs for Phones and Tablets Designing and Implementing Android UIs for Phones and Tablets Matias Duarte Rich Fulcher Roman Nurik Adam Powell Christian Robertson #io2011 #Android 2 Ask questions Give feedback http://goo.gl/mod/zdyr

More information

Android development. Outline. Android Studio. Setting up Android Studio. 1. Set up Android Studio. Tiberiu Vilcu. 2.

Android development. Outline. Android Studio. Setting up Android Studio. 1. Set up Android Studio. Tiberiu Vilcu. 2. Outline 1. Set up Android Studio Android development Tiberiu Vilcu Prepared for EECS 411 Sugih Jamin 15 September 2017 2. Create sample app 3. Add UI to see how the design interface works 4. Add some code

More information

Minds-on: Android. Session 2

Minds-on: Android. Session 2 Minds-on: Android Session 2 Paulo Baltarejo Sousa Instituto Superior de Engenharia do Porto 2016 Outline Activities UI Events Intents Practice Assignment 1 / 33 2 / 33 Activities Activity An activity provides

More information

CS 4518 Mobile and Ubiquitous Computing Lecture 5: Rotating Device, Saving Data, Intents and Fragments Emmanuel Agu

CS 4518 Mobile and Ubiquitous Computing Lecture 5: Rotating Device, Saving Data, Intents and Fragments Emmanuel Agu CS 4518 Mobile and Ubiquitous Computing Lecture 5: Rotating Device, Saving Data, Intents and Fragments Emmanuel Agu Administrivia Moved back deadlines for projects 2, 3 and final project See updated schedule

More information

ACTIVITY, FRAGMENT, NAVIGATION. Roberto Beraldi

ACTIVITY, FRAGMENT, NAVIGATION. Roberto Beraldi ACTIVITY, FRAGMENT, NAVIGATION Roberto Beraldi View System A system for organizing GUI Screen = tree of views. View = rectangular shape on the screen that knows how to draw itself wrt to the containing

More information

Fragments and the Maps API

Fragments and the Maps API Fragments and the Maps API Alexander Nelson October 6, 2017 University of Arkansas - Department of Computer Science and Computer Engineering Fragments Fragments Fragment A behavior or a portion of a user

More information

Produced by. Mobile Application Development. David Drohan Department of Computing & Mathematics Waterford Institute of Technology

Produced by. Mobile Application Development. David Drohan Department of Computing & Mathematics Waterford Institute of Technology Mobile Application Development Produced by David Drohan (ddrohan@wit.ie) Department of Computing & Mathematics Waterford Institute of Technology http://www.wit.ie User Interface Design" & Development -

More information

CS 528 Mobile and Ubiquitous Computing Lecture 3b: Android Activity Lifecycle and Intents Emmanuel Agu

CS 528 Mobile and Ubiquitous Computing Lecture 3b: Android Activity Lifecycle and Intents Emmanuel Agu CS 528 Mobile and Ubiquitous Computing Lecture 3b: Android Activity Lifecycle and Intents Emmanuel Agu Android Activity LifeCycle Starting Activities Android applications don't start with a call to main(string[])

More information

Google Maps Troubleshooting

Google Maps Troubleshooting Google Maps Troubleshooting Before you go through the troubleshooting guide below, make sure that you ve consulted the class FAQ, Google s Map Activity Tutorial, as well as these helpful resources from

More information

CMSC436: Fall 2013 Week 3 Lab

CMSC436: Fall 2013 Week 3 Lab CMSC436: Fall 2013 Week 3 Lab Objectives: Familiarize yourself with the Activity class, the Activity lifecycle, and the Android reconfiguration process. Create and monitor a simple application to observe

More information

Mobile Programming Lecture 5. Composite Views, Activities, Intents and Filters

Mobile Programming Lecture 5. Composite Views, Activities, Intents and Filters Mobile Programming Lecture 5 Composite Views, Activities, Intents and Filters Lecture 4 Review How do you get the value of a string in the strings.xml file? What are the steps to populate a Spinner or

More information

Getting Started. Dr. Miguel A. Labrador Department of Computer Science & Engineering

Getting Started. Dr. Miguel A. Labrador Department of Computer Science & Engineering Getting Started Dr. Miguel A. Labrador Department of Computer Science & Engineering labrador@csee.usf.edu http://www.csee.usf.edu/~labrador 1 Goals Setting up your development environment Android Framework

More information

COLLEGE OF ENGINEERING, NASHIK-4

COLLEGE OF ENGINEERING, NASHIK-4 Pune Vidyarthi Griha s COLLEGE OF ENGINEERING, NASHIK-4 DEPARTMENT OF COMPUTER ENGINEERING 1) What is Android? Important Android Questions It is an open-sourced operating system that is used primarily

More information

Upon completion of the second part of the lab the students will have:

Upon completion of the second part of the lab the students will have: ETSN05, Fall 2017, Version 2.0 Software Development of Large Systems Lab 2 1. INTRODUCTION The goal of lab 2 is to introduce students to the basics of Android development and help them to create a starting

More information

CS378 - Mobile Computing. Anatomy of an Android App and the App Lifecycle

CS378 - Mobile Computing. Anatomy of an Android App and the App Lifecycle CS378 - Mobile Computing Anatomy of an Android App and the App Lifecycle Application Components five primary components different purposes and different lifecycles Activity single screen with a user interface,

More information

Syllabus- Java + Android. Java Fundamentals

Syllabus- Java + Android. Java Fundamentals Introducing the Java Technology Syllabus- Java + Android Java Fundamentals Key features of the technology and the advantages of using Java Using an Integrated Development Environment (IDE) Introducing

More information

ANDROID DEVELOPMENT. Course Details

ANDROID DEVELOPMENT. Course Details ANDROID DEVELOPMENT Course Details centers@acadgild.com www.acadgild.com 90360 10796 01 Brief About the Course Android s share of the global smartphone is 81%. The Google Certified Android development

More information

Android Fundamentals - Part 1

Android Fundamentals - Part 1 Android Fundamentals - Part 1 Alexander Nelson September 1, 2017 University of Arkansas - Department of Computer Science and Computer Engineering Reminders Projects Project 1 due Wednesday, September 13th

More information

CS371m - Mobile Computing. Persistence - Web Based Storage CHECK OUT g/sync-adapters/index.

CS371m - Mobile Computing. Persistence - Web Based Storage CHECK OUT   g/sync-adapters/index. CS371m - Mobile Computing Persistence - Web Based Storage CHECK OUT https://developer.android.com/trainin g/sync-adapters/index.html The Cloud. 2 Backend No clear definition of backend front end - user

More information

CHAPTER 4. Fragments ActionBar Menus

CHAPTER 4. Fragments ActionBar Menus CHAPTER 4 Fragments ActionBar Menus Explore how to build applications that use an ActionBar and Fragments Understand the Fragment lifecycle Learn to configure the ActionBar Implement Fragments with Responsive

More information

CS378 -Mobile Computing. Anatomy of and Android App and the App Lifecycle

CS378 -Mobile Computing. Anatomy of and Android App and the App Lifecycle CS378 -Mobile Computing Anatomy of and Android App and the App Lifecycle Hello Android Tutorial http://developer.android.com/resources/tutorials/hello-world.html Important Files src/helloandroid.java Activity

More information

CS378 -Mobile Computing. More UI -Part 2

CS378 -Mobile Computing. More UI -Part 2 CS378 -Mobile Computing More UI -Part 2 Special Menus Two special application menus options menu context menu Options menu replaced by action bar (API 11) menu action bar 2 OptionsMenu User presses Menu

More information

Open Lecture Mobile Programming. Intro to Material Design

Open Lecture Mobile Programming. Intro to Material Design Open Lecture Mobile Programming Intro to Material Design Agenda Introduction to Material Design Applying a Material Theme Toolbar/Action Bar Navigation Drawer RecyclerView CardView Support Design Widgets/Tools

More information

In this Class Mark shows you how to put applications into packages and how to run them through the command line.

In this Class Mark shows you how to put applications into packages and how to run them through the command line. Overview Unless you ve been sleeping for the last couple of years, you know that Mobile is H-O-T! And the most popular mobile platform in the world? That s Android. Do you have a great idea for an App

More information

Diving into Android. By Jeroen Tietema. Jeroen Tietema,

Diving into Android. By Jeroen Tietema. Jeroen Tietema, Diving into Android By Jeroen Tietema Jeroen Tietema, 2015 1 Requirements 4 Android SDK 1 4 Android Studio (or your IDE / editor of choice) 4 Emulator (Genymotion) or a real device. 1 See https://developer.android.com

More information

Android Application Model I

Android Application Model I Android Application Model I CSE 5236: Mobile Application Development Instructor: Adam C. Champion, Ph.D. Course Coordinator: Dr. Rajiv Ramnath Reading: Big Nerd Ranch Guide, Chapters 3, 5 (Activities);

More information

Android Basics Nanodegree Syllabus

Android Basics Nanodegree Syllabus Android Basics Nanodegree Syllabus Before You Start This is an entry-level program. No prior programming experience required. Project 1: Build a Single Screen App Design and implement a single screen app

More information

EMBEDDED SYSTEMS PROGRAMMING Application Basics

EMBEDDED SYSTEMS PROGRAMMING Application Basics EMBEDDED SYSTEMS PROGRAMMING 2015-16 Application Basics APPLICATIONS Application components (e.g., UI elements) are objects instantiated from the platform s frameworks Applications are event driven ( there

More information

(Refer Slide Time: 1:12)

(Refer Slide Time: 1:12) Mobile Computing Professor Pushpendra Singh Indraprastha Institute of Information Technology Delhi Lecture 06 Android Studio Setup Hello, today s lecture is your first lecture to watch android development.

More information

Contextual Android Education

Contextual Android Education Contextual Android Education James Reed David S. Janzen Abstract Advances in mobile phone hardware and development platforms have drastically increased the demand, interest, and potential of mobile applications.

More information

CS 4330/5390: Mobile Application Development Exam 1

CS 4330/5390: Mobile Application Development Exam 1 1 Spring 2017 (Thursday, March 9) Name: CS 4330/5390: Mobile Application Development Exam 1 This test has 8 questions and pages numbered 1 through 7. Reminders This test is closed-notes and closed-book.

More information

GUI Design for Android Applications

GUI Design for Android Applications GUI Design for Android Applications SE3A04 Tutorial Jason Jaskolka Department of Computing and Software Faculty of Engineering McMaster University Hamilton, Ontario, Canada jaskolj@mcmaster.ca November

More information

UNDERSTANDING ACTIVITIES

UNDERSTANDING ACTIVITIES Activities Activity is a window that contains the user interface of your application. An Android activity is both a unit of user interaction - typically filling the whole screen of an Android mobile device

More information

Mobile Computing Professor Pushpedra Singh Indraprasth Institute of Information Technology Delhi Andriod Development Lecture 09

Mobile Computing Professor Pushpedra Singh Indraprasth Institute of Information Technology Delhi Andriod Development Lecture 09 Mobile Computing Professor Pushpedra Singh Indraprasth Institute of Information Technology Delhi Andriod Development Lecture 09 Hello, today we will create another application called a math quiz. This

More information

ANDROID SYLLABUS. Advanced Android

ANDROID SYLLABUS. Advanced Android Advanced Android 1) Introduction To Mobile Apps I. Why we Need Mobile Apps II. Different Kinds of Mobile Apps III. Briefly about Android 2) Introduction Android I. History Behind Android Development II.

More information

XML Tutorial. NOTE: This course is for basic concepts of XML in line with our existing Android Studio project.

XML Tutorial. NOTE: This course is for basic concepts of XML in line with our existing Android Studio project. XML Tutorial XML stands for extensible Markup Language. XML is a markup language much like HTML used to describe data. XML tags are not predefined in XML. We should define our own Tags. Xml is well readable

More information

Produced by. Mobile Application Development. David Drohan Department of Computing & Mathematics Waterford Institute of Technology

Produced by. Mobile Application Development. David Drohan Department of Computing & Mathematics Waterford Institute of Technology Mobile Application Development Produced by David Drohan (ddrohan@wit.ie) Department of Computing & Mathematics Waterford Institute of Technology http://www.wit.ie Android Google Services" Part 1 Google+

More information

Lifecycle-Aware Components Live Data ViewModel Room Library

Lifecycle-Aware Components Live Data ViewModel Room Library Lifecycle-Aware Components Live Data ViewModel Room Library Multiple entry points launched individually Components started in many different orders Android kills components on reconfiguration / low memory

More information

Android. The Toolbar

Android. The Toolbar Android The Toolbar Credits Lectures are heavily based of materials and examples from: Android Programming The Big Nerd Ranch Guides Bill Phillips and Brian Hardy April 7, 2013 ToDoList We re going to

More information

Android Ecosystem and. Revised v4presenter. What s New

Android Ecosystem and. Revised v4presenter. What s New Android Ecosystem and Revised v4presenter What s New Why Mobile? 5B 4B 3B 2B 1B Landlines PCs TVs Bank users Mobiles 225M AOL 180M 135M 90M 45M 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 Quarters

More information

Application Fundamentals

Application Fundamentals Application Fundamentals CS 2046 Mobile Application Development Fall 2010 Announcements CMS is up If you did not get an email regarding this, see me after class or send me an email. Still working on room

More information

Programming Android UI. J. Serrat Software Design December 2017

Programming Android UI. J. Serrat Software Design December 2017 Programming Android UI J. Serrat Software Design December 2017 Preliminaries : Goals Introduce basic programming Android concepts Examine code for some simple examples Limited to those relevant for the

More information

LECTURE NOTES OF APPLICATION ACTIVITIES

LECTURE NOTES OF APPLICATION ACTIVITIES Department of Information Networks The University of Babylon LECTURE NOTES OF APPLICATION ACTIVITIES By College of Information Technology, University of Babylon, Iraq Samaher@inet.uobabylon.edu.iq The

More information

Create new Android project in Android Studio Add Button and TextView to layout Learn how to use buttons to call methods. Modify strings.

Create new Android project in Android Studio Add Button and TextView to layout Learn how to use buttons to call methods. Modify strings. Hello World Lab Objectives: Create new Android project in Android Studio Add Button and TextView to layout Learn how to use buttons to call methods. Modify strings.xml What to Turn in: The lab evaluation

More information

Android App Development for Beginners

Android App Development for Beginners Description Android App Development for Beginners DEVELOP ANDROID APPLICATIONS Learning basics skills and all you need to know to make successful Android Apps. This course is designed for students who

More information

Programming in Android. Nick Bopp

Programming in Android. Nick Bopp Programming in Android Nick Bopp nbopp@usc.edu Types of Classes Activity This is the main Android class that you will be using. These are actively displayed on the screen and allow for user interaction.

More information

Lab 1: Getting Started With Android Programming

Lab 1: Getting Started With Android Programming Islamic University of Gaza Faculty of Engineering Computer Engineering Dept. Eng. Jehad Aldahdooh Mobile Computing Android Lab Lab 1: Getting Started With Android Programming To create a new Android Project

More information

Introduction To JAVA Programming Language

Introduction To JAVA Programming Language Introduction To JAVA Programming Language JAVA is a programming language which is used in Android App Development. It is class based and object oriented programming whose syntax is influenced by C++. The

More information

getcount getitem getitemid getview com.taxi Class MainActivity drawerlayout drawerleft drawerright...

getcount getitem getitemid getview com.taxi Class MainActivity drawerlayout drawerleft drawerright... Contents com.taxi.ui Class CallDialog... 3 CallDialog... 4 show... 4 build... 5 com.taxi.custom Class CustomActivity... 5 TOUCH... 6 CustomActivity... 6 onoptionsitemselected... 6 onclick... 6 com.taxi.model

More information

Android Activities. Akhilesh Tyagi

Android Activities. Akhilesh Tyagi Android Activities Akhilesh Tyagi Apps, memory, and storage storage: Your device has apps and files installed andstoredonitsinternaldisk,sdcard,etc. Settings Storage memory: Some subset of apps might be

More information

Introduction to Android development

Introduction to Android development Introduction to Android development Manifesto Digital We re an award winning London based digital agency that loves ideas design and technology We aim to make people s lives better, easier, fairer, more

More information

Lifecycle Callbacks and Intents

Lifecycle Callbacks and Intents SE 435: Development in the Android Environment Recitations 2 3 Semester 1 5779 4 Dec - 11 Dec 2018 Lifecycle Callbacks and Intents In this recitation we ll prepare a mockup tool which demonstrates the

More information

ORACLE UNIVERSITY AUTHORISED EDUCATION PARTNER (WDP)

ORACLE UNIVERSITY AUTHORISED EDUCATION PARTNER (WDP) Android Syllabus Pre-requisite: C, C++, Java Programming SQL & PL SQL Chapter 1: Introduction to Android Introduction to android operating system History of android operating system Features of Android

More information

Mobile Application Development Android

Mobile Application Development Android Mobile Application Development Android Lecture 2 MTAT.03.262 Satish Srirama satish.srirama@ut.ee Android Lecture 1 -recap What is Android How to develop Android applications Run & debug the applications

More information

COSC 3P97 Mobile Computing

COSC 3P97 Mobile Computing COSC 3P97 Mobile Computing Mobile Computing 1.1 COSC 3P97 Prerequisites COSC 2P13, 3P32 Staff instructor: Me! teaching assistant: Steve Tkachuk Lectures (MCD205) Web COSC: http://www.cosc.brocku.ca/ COSC

More information

Android Application Development

Android Application Development Android Application Development Octav Chipara What is Android A free, open source mobile platform A Linux-based, multiprocess, multithreaded OS Android is not a device or a product It s not even limited

More information

Android. Lesson 1. Introduction. Android Developer Fundamentals. Android Developer Fundamentals. to Android 1

Android. Lesson 1. Introduction. Android Developer Fundamentals. Android Developer Fundamentals. to Android 1 Android Lesson 1 1 1 1.0 to Android 2 Contents Android is an ecosystem Android platform architecture Android Versions Challenges of Android app development App fundamentals 3 Android Ecosystem 4 What is

More information

Android Basics Nanodegree Syllabus

Android Basics Nanodegree Syllabus Android Basics Nanodegree Syllabus Before You Start This is an entry-level, single term Nanodegree program with no prior programming experience required. Support Options We are here to support you every

More information

Course Learning Outcomes (CLO): Student Outcomes (SO):

Course Learning Outcomes (CLO): Student Outcomes (SO): Course Coverage Course Learning Outcomes (CLO): 1. Understand the technical limitations and challenges posed by current mobile devices and wireless communications; be able to evaluate and select appropriate

More information

States of Activities. Active Pause Stop Inactive

States of Activities. Active Pause Stop Inactive noname Conceptual Parts States of Activities Active Pause Stop Inactive Active state The state that the activity is on the most foreground and having a focus. This is in Active state. Active state The

More information

MC Android Programming

MC Android Programming MC1921 - Android Programming Duration: 5 days Course Price: $3,395 Course Description Android is an open source platform for mobile computing. Applications are developed using familiar Java and Eclipse

More information

Android. Mobile operating system developed by Google A complete stack. Based on the Linux kernel Open source under the Apache 2 license

Android. Mobile operating system developed by Google A complete stack. Based on the Linux kernel Open source under the Apache 2 license Android Android Mobile operating system developed by Google A complete stack OS, framework A rich set of applications Email, calendar, browser, maps, text messaging, contacts, camera, dialer, music player,

More information

Android Application Model I. CSE 5236: Mobile Application Development Instructor: Adam C. Champion, Ph.D. Course Coordinator: Dr.

Android Application Model I. CSE 5236: Mobile Application Development Instructor: Adam C. Champion, Ph.D. Course Coordinator: Dr. Android Application Model I CSE 5236: Mobile Application Development Instructor: Adam C. Champion, Ph.D. Course Coordinator: Dr. Rajiv Ramnath 1 Framework Support (e.g. Android) 2 Framework Capabilities

More information

Developing Android Applications Introduction to Software Engineering Fall Updated 1st November 2015

Developing Android Applications Introduction to Software Engineering Fall Updated 1st November 2015 Developing Android Applications Introduction to Software Engineering Fall 2015 Updated 1st November 2015 Android Lab 3 & Midterm Additional Concepts No Class Assignment 2 Class Plan Android : Additional

More information

CS 370 Android Basics D R. M I C H A E L J. R E A L E F A L L

CS 370 Android Basics D R. M I C H A E L J. R E A L E F A L L CS 370 Android Basics D R. M I C H A E L J. R E A L E F A L L 2 0 1 5 Activity Basics Manifest File AndroidManifest.xml Central configuration of Android application Defines: Name of application Icon for

More information

Vienos veiklos būsena. Theory

Vienos veiklos būsena. Theory Vienos veiklos būsena Theory While application is running, we create new Activities and close old ones, hide the application and open it again and so on, and Activity can process all these events. It is

More information

Android App Development. Mr. Michaud ICE Programs Georgia Institute of Technology

Android App Development. Mr. Michaud ICE Programs Georgia Institute of Technology Android App Development Mr. Michaud ICE Programs Georgia Institute of Technology Android Operating System Created by Android, Inc. Bought by Google in 2005. First Android Device released in 2008 Based

More information

Lecture 2 Android SDK

Lecture 2 Android SDK Lecture 2 Android SDK This work is licensed under the Creative Commons Attribution 4.0 International License. To view a copy of this license, visit http://creativecommons.org/licenses/by/4.0/ or send a

More information

IEMS 5722 Mobile Network Programming and Distributed Server Architecture

IEMS 5722 Mobile Network Programming and Distributed Server Architecture Department of Information Engineering, CUHK MScIE 2 nd Semester, 2016/17 IEMS 5722 Mobile Network Programming and Distributed Server Architecture Lecture 1 Course Introduction Lecturer: Albert C. M. Au

More information

User Interface: Layout. Asst. Prof. Dr. Kanda Runapongsa Saikaew Computer Engineering Khon Kaen University

User Interface: Layout. Asst. Prof. Dr. Kanda Runapongsa Saikaew Computer Engineering Khon Kaen University User Interface: Layout Asst. Prof. Dr. Kanda Runapongsa Saikaew Computer Engineering Khon Kaen University http://twitter.com/krunapon Agenda User Interface Declaring Layout Common Layouts User Interface

More information

Android Development Community. Let s do Material Design

Android Development Community. Let s do Material Design Let s do Material Design Agenda Introduction to Material Design Toolbar Navigation Drawer SwipeRefreshLayout RecyclerView Floating Action Button CardView Toolbar - Lives in package android.support.v7.widget

More information

Java Training Center - Android Application Development

Java Training Center - Android Application Development Java Training Center - Android Application Development Android Syllabus and Course Content (3 months, 2 hour Daily) Introduction to Android Android and it's feature Android releases and Versions Introduction

More information

Introduction to Android

Introduction to Android Introduction to Android Ambient intelligence Teodoro Montanaro Politecnico di Torino, 2016/2017 Disclaimer This is only a fast introduction: It is not complete (only scrapes the surface) Only superficial

More information

MS_40541 Build Native Cross-Platform Mobile Apps with a Shared C# Business Logic for ios, Android, and UWP in C#.NET with Xamarin and Visual Studio

MS_40541 Build Native Cross-Platform Mobile Apps with a Shared C# Business Logic for ios, Android, and UWP in C#.NET with Xamarin and Visual Studio Build Native Cross-Platform Mobile Apps with a Shared C# Business Logic for ios, Android, and UWP in C#.NET with Xamarin and Visual Studio www.ked.com.mx Av. Revolución No. 374 Col. San Pedro de los Pinos,

More information

Mobile User Interfaces

Mobile User Interfaces Mobile User Interfaces CS 2046 Mobile Application Development Fall 2010 Announcements Next class = Lab session: Upson B7 Office Hours (starting 10/25): Me: MW 1:15-2:15 PM, Upson 360 Jae (TA): F 11:00

More information

Produced by. Mobile Application Development. David Drohan Department of Computing & Mathematics Waterford Institute of Technology

Produced by. Mobile Application Development. David Drohan Department of Computing & Mathematics Waterford Institute of Technology Mobile Application Development Produced by David Drohan (ddrohan@wit.ie) Department of Computing & Mathematics Waterford Institute of Technology http://www.wit.ie Android Google Services" Part 1 Google+

More information

You ve been told lies about Fragments.

You ve been told lies about Fragments. You ve been told lies about Fragments. Mateusz Herych Android Tech Lead @ IG Google Developer Expert on Android GDG Kraków co-organizer Father of twins @mherych / github.com/partition You ve been told

More information

Overview of Activities

Overview of Activities d.schmidt@vanderbilt.edu www.dre.vanderbilt.edu/~schmidt Institute for Software Integrated Systems Vanderbilt University Nashville, Tennessee, USA CS 282 Principles of Operating Systems II Systems Programming

More information