Appendix: Utilities
Table of Contents:
- Copy and rename a project
- Delete a project
- Extract Resources
- Add support libraries
- Create images in Asset Studio
- Compare custom objects
- Save state of custom objects
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
- On your computer's file system (not in Android Studio), make a copy of the ExistingProject directory.
- 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:
- Start Android Studio
- Click Open an existing Android Studio project.
- Navigate to the NewProject directory, select it, and click OK.
- Select Build > Clean Project to remove the auto-generated files.
- Click the 1:Project side-tab and choose Android from the drop-down menu to see your files in the Project view.
- Expand app > java.
- Right-click com.example.android.existingproject and choose Refactor > Rename. This opens the Rename dialog.
- Change existingproject to newproject.
- Check Search in comments and strings and Search for text occurrences and click Refactor.
- The Find Refactoring Preview pane appears, showing the code to be refactored.
- Click Do Refactor.
- Expand res > values and double-click the strings.xml file.
- 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:
- Expand Gradle Scripts and double-click build.gradle (Module: app).
- Under defaultConfig, check to make sure that the value of the applicationID key has been changed to "com.example.android.newproject". If it has not changed, change it manuall now.
- 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.
- Expand app > manifests and double-click AndroidManifest.xml.
- Find the statement below, and if necessary, change the label if to the string resource for the new app name:
android:label="@string/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:
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.Make sure your cursor is in the highlighted text.
Press Alt + Enter and select Create string value resource.
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:
- Place your cursor in the view whose attributes you want to turn into a style.
- Right click and select Refactor > Extract > Style.
- 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.
- 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:
- In Android Studio, in your project, make sure you are in the Project pane (1) and in the Android view (2).
- In the hierarchy of files, find the Gradle Scripts folder (3).
- Expand Gradle Scripts, if necessary, and open the build.gradle (Module: app) file (4).
- Towards the end of the build.gradle (Module: app) file, find the dependencies section.
- Add these two library dependencies as the last two lines (inside the curly braces):
compile 'com.android.support:recyclerview-v7:23.1.1' compile 'com.android.support:design:23.1.1'
- There is probably an existing line similar to this one:
compile 'com.android.support:appcompat-v7:23.1.1'
- 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.)
- There is probably an existing line similar to this one:
- If prompted, sync your app now.
- 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 'com.android.support:appcompat-v7:23.1.1'
compile 'com.android.support:recyclerview-v7:23.1.1'
compile 'com.android.support:design:23.1.1'
}
Create images in Asset Studio
Use Image Asset Studio to create and add a launcher icon.
- Open your app in Android Studio.
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:
- 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. - In the Asset Type row, select Text.
- Type "Hello World!" into the text box.
- Experiment with adjusting the font.
- Scroll down and change font and background colors.
- Click Next.
- 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.
- Click Finish.
- 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.
- To use the new icon, open the Android manifest. Change the android icon line from referencing ic_launcher to ic_launcher_text.
android:icon="@mipmap/ic_launcher_text"
- Run your app.
- After the app has launched, go to the home screen and open the list of apps.
- Scroll and you should see your icon listed along with the other installed apps.
To add a clipart icon:
Follow the previous steps except:
- Change the Name to
ic_launcher_clipart
. - Choose Clip Art as the Asset Type.
- In the Clip Art row, click the button showing the current icon, the default Android.
- Choose an icon from the popup window of clip art.
To add a custom icon:
Follow the previous steps except:
- Change the Name to
ic_launcher_image
. - Choose Image as the Asset Type.
- 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 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:
@Override
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:
- 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.
- 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.
- Choose both
describeContents()
andwriteToParcel(Parcel dest, int flags)
. Click OK. - 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. - You can now save the state of these objects using the savedInstanceState bundles methods: putParcelable, putParcelableArray, and putParcelableArrayList and the respective getters.