review udacity android app development

13
Review Material for Lesson 1 Congratulations on finishing lesson 1! You’ve come a long way already: you've created your first app, and have learned many of the essential Android concepts. We studied the tools used to create apps, including Android Studio, the Android SDK, testing devices (both real and emulated), and the Gradle build system. We also looked at some of the core classes that make up Android apps, including activities, fragments, layouts, views, list views, and adapters. New Concepts Android Studio SDK - Target and Minimum Emulators vs. Real Devices Gradle Application Activity Fragment Views and ViewGroups Views and XML layouts ListView Adapter Android Studio Android Studio is the IDE that we’re using for the course. When you start a new app, you will create aProject in Android Studio. Every project will contain one or more modules for each logical part of your application. To ensure that your module name is unique, the module naming convention is to use the reverse of your internet domain name. Android Studio organizes your project in a specific way, described here. The following is a review of some of the important buttons in Android Studio.

Upload: akash-shinde

Post on 14-Nov-2015

13 views

Category:

Documents


2 download

DESCRIPTION

android development

TRANSCRIPT

Review Material for Lesson 1Congratulations on finishing lesson 1! Youve come a long way already: you've created your first app, and have learned many of the essential Android concepts. We studied the tools used to create apps, including Android Studio, the Android SDK, testing devices (both real and emulated), and the Gradle build system. We also looked at some of the core classes that make up Android apps, including activities, fragments, layouts, views, list views, and adapters.New Concepts Android Studio SDK - Target and Minimum Emulators vs. Real Devices Gradle Application Activity Fragment Views and ViewGroups Views and XML layouts ListView AdapterAndroid StudioAndroid Studio is the IDE that were using for the course. When you start a new app, you will create aProjectin Android Studio. Every project will contain one or moremodulesfor each logical part of your application. To ensure that your module name is unique, the module naming convention is to use the reverse of your internet domain name.Android Studio organizes your project in a specific way, describedhere.The following is a review of some of the important buttons in Android Studio.

1. This determines how the project structure will be shown. In the course we use theProjectview but theAndroidview is also a handy way to organize your files.2. This is therunbutton. It will save and compile the current state of your project as an apk and then launch it on either an Android phone connected to your computer or an emulator.3. This is thedebugbutton. It runs your code as above, but attaches the Android debugger, which allows you to do things like stop at breakpoints and step through the code.4. This is theAVD managerbutton. It opens the Android Virtual Device manager, which allows you to create, delete, run and edit Android emulators.5. This is theSDK Managerbutton. The SDK Manager allows you to download new SDKs for different Android APIs.6. This is theAndroid Device Monitorbutton. The Android Device Monitor shows you a lot of information about your emulated and attached devices. For example, you can do basic performance analysis and see whats on the file system.SDK - Target and MinimumWhen you create a new project, you need to define a minimum SDK, or Software Development Kit. The SDK is a set of tools that you download that allows you to compile and create Android Projects. SDKs match API levels, when a new API level is released, a new SDK is released to make projects for that level. A current SDK is automatically downloaded when you install Android Studio.The minimum SDK is the minimum Android API level that the application is meant to support. In our case we are supporting API level 10, which includes all devices running Gingerbread and beyond. This will support 99% of devices on the market.The target SDK, which is automatically defined for you, signifies the SDK that you use to compile and test with. It should be the most current SDK.Emulators vs. Real DevicesWhen you download Android Studio 1.0 it comes with an emulated phone. You can start this emulated phone on your computer by simply running your app and choosing the Launch emulator" option and picking your emulator:

Note, sometimes emulated phones hang with a black screen or loading screen like this one:

If this happens to you, check out your error messages in Android Studio. A common message is:/Android/sdk/tools/emulator -avd _Nexus_5_API_21_x86 -netspeed full -netdelay noneemulator: The memory needed by this VM exceeds the driver limit.HAX is not working and emulator runs in emulation modeThis means that your machine is not fast enough to run the default emulator. Not to worry; followKatherines instructionsto make a new emulator and reduce the RAM that the emulator uses. Here is the configuration screen where you can do this:

Emulators are great, but they can be a bit slow. If at all possible, we suggest you use a real device. Youll need to follow the steps in thisvideoto unlock developer mode, but ultimately the performance will be much faster and experience much smoother.If youre set on using the emulator, consider installing Genymotion. The steps to do so can be foundhere.GradleGradle is the build system that packages up and compiles Android Apps. Android Studio automatically generates Gradle files for your application, including thebuild.gradlefor your app and module and thesettings.gradlefor your app. You do not need to create these files. You can run Gradle from a terminal (described inthisandthisvideo), but you can also use therunbutton which will automatically run the Gradle scripts in your project. For more information on the build process that Android Studio and Gradle are automatically handling for you, checkout thedeveloper guide.TIP: if your project is having Gradle issues, sometimes clicking theSync Project with Gradle Filesbutton helps. Running clean and rebuilding your project can also help resolve errors.

ApplicationYou probably know what an Android application, like Gmail or Keep, looks like as a user, but what does an application look like from a developers perspective? An application is a loose collection of classes for the user to interact with. The UI components are organized into Activities, which we learned about in this lesson. The behind-the-scenes work is handled by other Android classes including: Content Providers (Lesson 4) - Manage app data. Services (Lesson 6) - Run background tasks with no UI, such as downloading information or playing music. Broadcast Receivers (Lesson 6) - Listen for and respond to system announcements, such as the screen being turned on or losing network connectivity.ActivityActivities are the components of Android apps that the user interacts with and a core class in Android. When you create an app with Android Studio, it will create an initial activity class that will start when the app is launched. The default name of this activity isMainActivity. An activity is a single, focused thing that the user can do and roughly maps to one screen of the app.FragmentActivities can contain one or more Fragments. Fragments are modular sections of an activity, usually meant to display UI. Two activities can have the same fragment and fragments can be added or removed from an Activity. An Activity with blank Fragment is what we created for Sunshine. ThePlaceholderFragmentis automatically generated as an inner class of the activity, but fragments dontneedto be inner classes.Views and ViewGroupsA view is the basic building block for user interface components. A fragment might combine multiple views to define its layout. Buttons, text and other widgets are subclasses of views and can be combined in ViewGroups to create larger layouts. Common ViewGroups include: LinearLayout- For horizontal or vertical collections of elements. RelativeLayout- For laying out elements relative to one another. FrameLayout- For a single view.Since views nest within other views, this creates a tree like structure of views for every layout.Views and XML LayoutsTo describe our user interface, we describe layouts using XML. The layout defines a collection of views, view groups and the relationships between them. Our layouts are stored in the app/src/main/res/layout directory. To turn an xml layout into java view objects, we need toinflatethe layout. After the layout is inflated, we need to associate it with an Activity or Fragment. This process of inflating and associating is a little different depending on whether its a layout for an Activity or Fragment.For an ActivityWe inflate the layout and associate it with the Activity by calling thesetContentViewmethod inonCreatein our Activity:setContentView(R.layout.activity_main);For a FragmentIn our Fragment classes we inflate the layout in theonCreateViewmethod, which includes aLayoutInflateras a parameter:View rootView = inflater.inflate(R.layout.fragment_main, container, false);The root view, or view element which contains all the other views, is returned by theinflatemethod of theLayoutInflater. We then should return this rootView for theonCreateView.ListViewListView is a subclass of View optimized for displaying lists by displaying many copies of a single layout. We are going to use a ListView to display our weather information in Sunshine. Each row of weather information is defined by a layout calledlist_item_forecast.xml. The list view contains multiple copies of list_item_forecast.xml, one for each row of weather data.AnAdapteris used to populate a ListView.AdapterAdapters translate a data source into views for a ListView to display. In our case we used an ArrayAdapter to take an array as our data source and populate our ListView with the data from the array. Heres the correspondingvideoabout how this process works.Review Material for Lesson 2Congratulations! Youve got two lessons under your belt and Sunshine is now connected to the cloud. Below is a list of the key concepts covered, along with a description of each concept.New Concepts HttpURLConnection Logcat MainThread vs. Background Thread AsyncTask Adding Menu Buttons values/strings.xml Permissions JSON ParsingHttpURLConnectHttpURLConnect is a Java class used to send and receive data over the web. We use it to grab the JSON data from theOpenWeatherMap API. The code to do so is introduced in thisvideoandgistLogcatLogcat is the program you can use to view your Android devices logging output. In the course there are three ways to do this:1. Android Studio has a DDMS window which includes logcat output. Make sure the Android Window is selected.2. You can open up a terminal and typeadb logcat. Thedeveloper guidehas more information on options you can use to filter the output.3. You can explicitly open a separate window for Android DDMS and access logcat.Logs come in five flavours,Verbose,Debug,Info,WarnandError. You can filter the logs by selecting the Log Level (shown in green), which will show you only logs of that level and above. For example, only seeing warning and above would show you Warning and Error logs.In your code you can write statements which will post log messages to logcat. To do so, you use the Log class followed by v, d, i, w or e method, depending on which log level you want the message to be at. Log.w(","); for example, would output a Warning level log message. Each method takes two strings, the first is the tag, which is used to identify where the log is coming from. The second parameter is the specific log message.The convention used in the course for thetagis to create a String constantLOG_TAGwhich equals the name of the class the constant is in. You can get the class name programmatically. Heres an example for the MainActivity:private final String LOG_TAG = MainActivity.class.getSimpleName();MainThread vs. Background ThreadIn Android there is a concept of theMain Threador UI Thread. If youre not sure what a thread is in computer science, check out thiswikipedia article. The main thread is responsible for keeping the UI running smoothly and responding to user input. It can only execute one task at a time. If you start a process on the Main Thread which is very long, such as a complex calculation or loading process, this process will try to complete. While it is completing, though, your UI and responsiveness to user input will hang.Therefore, whenever you need to start a longer process you should consider using another Background" thread, which doesnt block" the Main Thread. An easy (but by no means perfect) way to do this is to create a subclass of AsyncTask.AsyncTaskAsyncTask is an easy to use Android class that allows you to do a task on a background thread and thus not disrupt the Main Thread. To use AsyncTask you should subclass it as weve done with FetchWeatherTask. There are four important methods to override: onPreExecute- This method is run on the UI before the task starts and is responsible for any setup that needs to be done. doInBackground- This is the code for the actual task you want done off the main thread. It will be run on a background thread and not disrupt the UI. onProgressUpdate- This is a method that is run on the UI thread and is meant for showing the progress of a task, such as animating a loading bar. onPostExecute- This is a method that is run on the UIafterthe task is finished.Note that when you start an AsyncTask, it is tied to the activity you start it in. When the activity is destroyed (which happens whenever the phone is rotated), the AsyncTask you started will refer to the destroyed activity and not the newly created activity. This is one of the reasons why using AsyncTask for a longer running task is dangerous.Adding menu buttonsSo that we could add a temporary Refresh button, we learned how to add menu buttons. Here are the basic steps.1. Add an xml file inres/menu/that defines the buttons you are adding, their ordering and any other characteristics.2. If the menu buttons are associated with a fragment, make sure to callsetHasOptionsMenu(true)in the fragment'sonCreatemethod.3. Inflate the menu in theonCreateOptionsMenuwith a lineinflater.inflate(R.menu.forecastfragment, menu);4. InonOptionsItemSelectedyou can check which item was selected and react appropriately. In the case of Refresh, this means creating and executing aFetchWeatherTask.values/strings.xmlAndroid has a specific file for all of the strings in your app, stored invalues/strings.xml. Why? Well besides further helping separate content from layout, the strings file also makes it easy to localize applications. You simply create avalues-language/strings.xmlfiles for each locale you want to localize to. For example, if you want to create a Japanese version of your app, you would create avalues-ja/strings.xml. Note, if you put the flagtranslatable="false"in your string it means the string need not be translated. This is useful when a string is a proper noun.PermissionsBy default, applications in Android aresandboxed. This means they have their own username, run on their own instance of the virtual machine, and manage their own personal and private files and memory. Therefore, to have applications interact with other applications or the phone, you must request permission to do so.Permissions are declared in theAndroidManifest.xmland are needed for your app to do things like access the internet, send an SMS or look at the phones contacts. When a user downloads your application, they will see all of the permissions you request. In the interest of not seeming suspicious, its a good idea to only request the permissions you need.JSON ParsingOften when you request data from an API this data is returned in a format like JSON. This is the case for Open Weather Map API. Once you have this JSON string, you need to parse it.If youre unfamiliar with JSON, take a look atthis tutorial.If youre not sure of the exact structure of the JSON, use a formatter.Heres a good oneyou can use in the browser.In Android, you can use theJSONObjectclass, documentedhere. To use this class you take your JSON string and create a new object:JSONObject myJson = new JSONObject(myString);And then you can use variousgetmethods to extract data, such asgetJSONArrayandgetLong.