Appendix: Utilities

Table of Contents:

This appendix is a collection of tasks you may need to do during development of the apps in the practicals. They are not specific to one practical.

Copy and rename a project

For some lessons, you will need to make a copy of a project before making new changes. You may also want to copy a project to use some of its code in a new project. In either case you can copy the existing project (ExistingProject), and then rename and refactor the new project's (NewProject) components to use the new project's name. (In the instructions below, substitute your actual project names for ExistingProject and NewProject.

1. Copy the project

  1. On your computer's file system (not in Android Studio), make a copy of the ExistingProject directory.
  2. Rename the copied directory to NewProject .

2. Rename and refactor the project components

The old name of the project, ExistingProject, still appears throughout the packages and files in the new copy of your project. Change the file and the package references in your app to the new name, as follows:

  1. Start Android Studio
  2. Click Open an existing Android Studio project.
  3. Navigate to the NewProject directory, select it, and click OK.
  4. Select Build > Clean Project to remove the auto-generated files.
  5. Click the 1:Project side-tab and choose Android from the drop-down menu to see your files in the Project view.
  6. Expand app > java.
  7. Right-click and choose Refactor > Rename. This opens the Rename dialog.
  8. Change existingproject to newproject.
  9. Check Search in comments and strings and Search for text occurrences and click Refactor.
  10. The Find Refactoring Preview pane appears, showing the code to be refactored.
  11. Click Do Refactor.
  12. Expand res > values and double-click the strings.xml file.
  13. Change the name="app_name" string to New Project.

3. Update the build.gradle and AndroidManifest.xml files

Each app you create must have a unique application ID, as defined in the app's build.gradle file. Even though the above steps should have changed the build.gradle file, you should check it to make sure, and also sync the project with the gradle file:

  1. Expand Gradle Scripts and double-click build.gradle (Module: app).
  2. Under defaultConfig, check to make sure that the value of the applicationID key has been changed to "". If it has not changed, change it manuall now.
  3. Click Sync Now in the top right corner of the Android Studio window.
    Tip: You can also choose Tools > Android > Sync Project with Gradle File to sync your gradle files.

In addition, some apps include the app name in readable form (such as "New Project" rather than newproject) as a label in the AndroidManifest.xml file.

  1. Expand app > manifests and double-click AndroidManifest.xml.
  2. Find the statement below, and if necessary, change the label if to the string resource for the new app name:

Delete a project

All the files for an Android project are contained in the project's folder on the computer's file system. To delete a project, delete its folder.

Android Studio also keeps a list of recent projects that you have opened. You can delete a project from the list of recent projects in Android Studio. (Deleting a project from the recent projects list does not affect the actual project files.)

To remove a project from the recent projects list, do one of the following:

  • On the Android Studios startup screen screen, click the name of the project and press the delete key.
  • Select File > Open Recent > Manage Projects, click the name of the project and press the delete key.

Extract Strings and Dimensions

Extracting Strings

In order for your app to be translatable into multiple languages you must keep all of your string resources in the res/values/strings.xml file.

Creating string resources

There are several ways to create string resources:

  • Add them manually in the strings.xml file using the following syntax:
    <string name="string_name">String Value</string>
  • Wherever the string will be used, such as the text attribute of a TextView:

    1. Type in the desired name for a string resource in the following format: @string/string_name. It will be highlighted in red since the resource does not yet exist.

    2. Make sure your cursor is in the highlighted text.

    3. Press Alt + Enter and select Create string value resource.

    4. Enter your desired string and press OK and he string gets added to your strings.xml file.

  • You can select any existing, hard-coded string in either XML or Java, press Alt + Enter, and select Extract string resource.

Accessing string resources:

  • In XML, references string resource using the following syntax: @string/string_name
  • In Java, reference string resources using the following syntax: getString(R.string.string_name)

2. Extract Dimensions

Dimensions should in general not be hard-coded but kept in the dimens.xml file. This allows for you to specify different dimensions using resource qualifiers.

Extract dimensions in the same way as strings (Alt-Enter), and they will be stored in the dimens.xml.

3. Extract Styles

If you have several elements that share attributes, you can create a style in the style.xml file. To learn more about styles, see the Styles and Themes lesson.

To extract existing attributes into a style, do the following:

  1. Place your cursor in the view whose attributes you want to turn into a style.
  2. Right click and select Refactor > Extract > Style.
  3. Name the style and select attributes. If Launch 'Use Style Where Possible' refactoring after the style is extracted is checked, Android Studio will search the rest of the file for the selected attributes and apply the style to views where the attributes match.
  4. Click OK.

Add Android support libraries to the build file

Android Support Libraries provide backward-compatible versions of Android framework APIs, additional UI components and a set of useful utilities.

For example, to use the RecyclerView class, which is located in the Android Support package, you must include two dependencies in your project's build.gradle file. The process is the same for other support library components.

Follow these steps and refer to the screenshot below:

  1. In Android Studio, in your project, make sure you are in the Project pane (1) and in the Android view (2).
  2. In the hierarchy of files, find the Gradle Scripts folder (3).
  3. Expand Gradle Scripts, if necessary, and open the build.gradle (Module: app) file (4). build.gradle file in Android Studio
  4. Towards the end of the build.gradle (Module: app) file, find the dependencies section.
  5. Add these two library dependencies as the last two lines (inside the curly braces):
    compile ''
    compile ''
    • There is probably an existing line similar to this one:
      compile ''
    • Add your lines below that line.
    • Match the version number of your lines to the version number of that existing line.
    • Make sure the version numbers of all the libraries are the same and match up with the compiledSdkVersion at the top of the file. (If these don't match, you will get a build time error.)
  6. If prompted, sync your app now.
  7. Build and run your app.

The following is an example of the dependencies section of the build.gradle file with support libraries added.

dependencies {
   compile fileTree(dir: 'libs', include: ['*.jar'])
   testCompile 'junit:junit:4.12'
   compile ''
   compile ''
   compile ''

Create images in Asset Studio

Use Image Asset Studio to create and add a launcher icon.

  1. Open your app in Android Studio.
  2. Right-click the res folder of your project and select New > Image Asset from menu.

    This opens the Image Asset Studio window, where you can create a text icon, choose from available clipart, or add your own custom icon.

    Note that the panel on the top-left is scrollable; scroll to see additional customizations.

To add a custom text icon:

  1. Change the Name of the icon to ic_launcher_text, if you don't want to overwrite the default Android ic_launcher icon that comes with your project.
  2. In the Asset Type row, select Text.
  3. Type "Hello World!" into the text box.
  4. Experiment with adjusting the font.
  5. Scroll down and change font and background colors.
  6. Click Next.
  7. The Confirm Icon Path window shows how an icon with your specified text will be created for each resolution, as well as the default storage location and path in your app.
  8. Click Finish.
  9. Got the the res/mipmap folder. If now contains your new icon, with a default version at the top level, and size-adjusted versions for different resolutions.
  10. To use the new icon, open the Android manifest. Change the android icon line from referencing ic_launcher to ic_launcher_text.
  11. Run your app.
  12. After the app has launched, go to the home screen and open the list of apps.
  13. Scroll and you should see your icon listed along with the other installed apps.

To add a clipart icon:

Follow the previous steps except:

  1. Change the Name to ic_launcher_clipart.
  2. Choose Clip Art as the Asset Type.
  3. In the Clip Art row, click the button showing the current icon, the default Android.
  4. Choose an icon from the popup window of clip art.

To add a custom icon:

Follow the previous steps except:

  1. Change the Name to ic_launcher_image.
  2. Choose Image as the Asset Type.
  3. In the Path row, choose an image. This can be an image that you've added to your project or an image on your computer.

Compare custom objects

Whenever your data model calls for objects to be sorted, it becomes necessary to define how these objects can be compared to each other.

The Comparable interface allows you to specify how to compare two objects and determine whether one is biggers, smaller, or the same as the other.

The Comparable interface requires that you implement a single method: compareTo(<T> another) where is the parameterized type you implemented Comparable with, and the type of object you are comparing to (i.e if you want to compare your Foobar instance to other Foobar instances, you would implement Comparable<Foobar> and your compareTo method would take Foobar as a parameter).

The compare method should do the following:

  • Return a negative integer if the object is less than the parameter.
  • Return a positive integer if the object is greater than the parameter.
  • Return zero if the objects are equal.

For example, to compare a list of books by publication date:

public int compareTo(Book book) {
    if (this.publication == book.publication) { return 0; }
    else { return this.publication > book.publication ? 1 : -1;}

Save state of custom objects

In Android, you will frequently create custom objects to represent your particular data model. In order to preserve the state of these objects, you must be able to pass them into the savedInstanceState bundle. In order to do so, your custom class must implement the Parcelable interface. This allows for primitive types (int, string, byte, etc) to be saved in the savedInstanceState callback.

Do the following:

  1. After setting up the data in your custom class (only the primitive data types will be saved), add the Parcelable implementation to your class declaration.
  2. The declaration will be underlined in red, since you have to implement the interface methods. With your cursor on the underlined text, press Alt + Enter and select Implement methods.
  3. Choose both describeContents() and writeToParcel(Parcel dest, int flags). Click OK.
  4. The class name will still be underlined, indicating that the interface is not fully implemented yet. Select the class name, and again press Alt + Enter and choose Add Parcelable implementation. Android studio will automatically add the required code. Note the variables for which you want to preserve the state (primitive types) are written to the Parcel in the writeToParcel method.
  5. You can now save the state of these objects using the savedInstanceState bundles methods: putParcelable, putParcelableArray, and putParcelableArrayList and the respective getters.

results matching ""

    No results matching ""