Android 5: Assignment 1, First Half, Arithmetic Operations and Exceptions
Introduction This set of overheads is devoted entirely to explaining the first half, the first 50 points, of the first graded assignment on Android There is no downloadable code for these assignments It’s not that you have to do each one of them from scratch Part of what you will get accustomed to doing is modifying existing code in order to create new code
The first thing that will be introduced is the procedure for copying a project in Android Studio After that, the various requirements and details associated with each of the five parts of the assignment will be given
Outline 5.1 Copying Projects in Android Studio 5.2 A Note on Assignments 5.3 A Preview Survey of the Parts of the Assignment in Screen Shots 5.4 Assignment 1, Part 1 5.5 Assignment 1, Part 2 5.6 Assignment 1, Part 3 5.7 Assignment 1, Part 4 5.8 Assignment 1, Part 5
5.1 Copying Projects in Android Studio
You may have noticed that the File menu for Android Studio does not have options like these: Save Project As Export Project To me this seems like a bit of a curious oversight, but there’s no arguing with reality
The general description for the process of copying existing projects is based on the idea that you accepted all the defaults when you installed Android Studio (We will eventually see what things are like in the lab…) If you did a default installation, your projects will be stored in this path: C:\Users\your_userid\AndroidStudioProjects
What you will find in the projects folder is one folder for each project you’ve saved If you want to copy a project, the first step is to copy the folder containing it and rename the copy So, for example, you might already have a project folder named Assignment1Part1 Make a copy of this folder and rename the copy Assignment1Part2
Now Start or go into Android Studio Take the Open Existing Project option Follow the path to the copy that you just made It will typically “open” in Android Studio with none of the development environment windows opening
Do either Alt + 1 on the keyboard or use the mouse on the Project tab in the left margin in order to open the explorer, or project view The app folder for the project you are opening should be highlighted in the explorer Expand the app folder Then expand the java folder underneath it
In that folder you’ll find an entry for the file containing your app code, as well as two more entries for test code Right click on the entry for your app In the pop-up menu that appears, take the Refactor option From the pop-up menu that appears for that, take the Rename… option
You will be given three choices: Rename Package, Rename Directory, and Cancel Take the option to Rename Package Rename the package to agree with the new name that you gave to the copied project file When you hit enter, at the bottom of the screen you will need to confirm your choice You do this by taking the “Do Refactor” option
This should complete the process of making the code consistent You can test your copy by building and running it You may want to make one final change: Go to strings.xml and update the app_name to agree with the name you gave to your copied project
5.2 A Note on Assignments
The different parts of this assignment and some other assignments will build on each other Sometimes part n+1 is just an extension or modification of part n Sometimes part n+1 represents a more significant change to part n
In short, in some cases, if you got part n+1 to work, it implies that part n was accomplished The point is that for grading purposes you need to show a separate solution for each part, even if solving one part implies that the previous parts were solved Simply save your solutions as separate projects as you go, making copies in order to do the next part
The following sections of the overheads to large extent tell you how to do each of the parts What each of the parts of the assignments do is relatively simple There are the usual details which have to be taken care of, but what is important is the process of getting used to “growing” code step-by-step
5.3 A Preview Survey of the Parts of the Assignment in Screen Shots
What follows immediately is a preview of what the assignment is about by showing screenshots of each of the parts The overall plan of action is to create a simple interface and simple functionality that might ultimately be implemented in a calculator app
Part 1
Part 2
Unfortunately, Error Messages Can be Uninformative. …OK…
Part 3 The screen shots are given on the following slide This example illustrates a mismatch between the display of a layout on an attached device and the emulator The layout is correctly displayed on the attached device The app adds numeric input values and concatenates inputs if either is a string
Part 4 For the sake of realism, the following screen shots were taken from the device rather than the emulator The emulator screen isn’t as wide as the device screen, so the views in the relative layout don’t all fit horizontally and some would be covered up Everything fits nicely on the device
Subtraction with valid operands
Catch the exception on bad input and provide an informative error message. The application doesn’t stop. The user can back up and try again.
Something unexpected, and maybe not ideal: Some documentation says that division by 0 will throw the ArithmeticException. Even if you try to catch that, it will be ignored, and the result of the invalid operation is shown in this way.
Part 5 Enter the first value Then click + Enter the second value Ta-Da
5.4 Assignment 1, Part 1
There is no downloadable example code for these assignments The starting point is the Hello World example from the tutorials From that point on, the starting point is the previous part of the assignment
Part 1
Part 1 will essentially be shown in its entirety If you’re at a loss, it should be possible to get started largely by copying and pasting from PowerPoint to Android Studio After Part 1, the presentation of the following parts will be less complete
Working from the bottom up, so to speak, the app has string resources, a layout resource, and a Java activity The following screen shows the string resources
<resources> <string name="app_name">Assignment1Part1</string> <string name="inputHint">Enter a string.</string> </resources>
The two screens following the next one show the layout This is my approach on layouts: Copy an existing layout when possible Use the graphical development tools if desirable Modify what you get from doing these two things to achieve the desired results
In other words, I have not learned either the complete set of layout items (views, widgets) or the XML for them I pick what I need as I go and fix things as needed This is not a very comprehensive approach, but it works for me and I suggest it to you
<. xml version="1. 0" encoding="utf-8" <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context="com.example.kascott.assignment1part1.MainActivity"> <EditText android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/editText" android:layout_alignParentTop="true" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" android:hint="@string/inputHint"/>
<EditText android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/editText2" android:layout_alignParentTop="true" android:layout_toRightOf="@+id/editText" android:layout_marginLeft="39dp" android:layout_marginStart="39dp" android:hint="@string/inputHint"/> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="+" android:id="@+id/button" android:layout_alignParentTop="true" android:layout_alignParentRight="true" android:layout_alignParentEnd="true" android:onClick="sendMessage" /> </RelativeLayout>
The MainActivity code is shown on the following overhead The majority of this is simply the machinery for creating another activity The operation that the app performs, string concatenation, is accomplished with the “+” operator There activity that displays the results is the same as Hello World, so it’s components are not shown
package com. example. kascott. assignment1part1; import android package com.example.kascott.assignment1part1; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.EditText; public class MainActivity extends AppCompatActivity { public final static String EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public void sendMessage(View view) { Intent intent = new Intent(this, DisplayConcatenatedInputStrings.class); EditText editText = (EditText) findViewById(R.id.editText); EditText editText2 = (EditText) findViewById(R.id.editText2); String message = editText.getText().toString() + editText2.getText().toString(); intent.putExtra(EXTRA_MESSAGE, message); startActivity(intent); } }
5.5 Assignment 1, Part 2
Part 2
Unfortunately, Error Messages Can be Uninformative. …OK…
Part 2 is supposed to implement addition rather than string concatenation The strings and layouts for this part are nothing special What you have to keep in mind for the app is that editText fields deal in strings You have to convert to doubles See the code on the following overhead
double double1 = Double. parseDouble(editText. getText() double double1 = Double.parseDouble(editText.getText().toString()); double double2 = Double.parseDouble(editText2.getText().toString());
As shown in the screen shots, there are problems if you don’t enter numeric values Do not try to address those problems in part 2 They will be addressed in the coming parts
5.6 Assignment 1, Part 3
Remember that this example illustrates a mismatch between the display of a layout on an attached device and the emulator Whether working in the emulator or on an attached device, you want the app to display correctly
The app adds numeric input values and concatenates inputs if either is a string It would be possible to check input with if statements However, the approach taken here is an introduction or review of exception handling—depending on whether you’ve seen it before
The basic idea is that when code generates errors, the system detects them, and the system will throw an exception that can be caught and acted on in the code itself The plan behind the sendMessage() method in the main activity code is given on the following overhead
Try to parse a double out of a string If it works, do addition If it doesn’t work, an exception will be thrown Catch the exception and do string concatenation instead At the end, put out the result of either of the two outcomes The code is shown on the following overhead
public void sendMessage(View view) { String message; Intent intent = new Intent(this, DisplayConcatenatedInputStrings.class); EditText editText = (EditText) findViewById(R.id.editText); EditText editText2 = (EditText) findViewById(R.id.editText2); try { double double1 = Double.parseDouble(editText.getText().toString()); double double2 = Double.parseDouble(editText2.getText().toString()); double result = double1 + double2; message = result + ""; } catch(NumberFormatException e) { message = editText.getText().toString() + editText2.getText().toString(); } intent.putExtra(EXTRA_MESSAGE, message); startActivity(intent); }
5.7 Assignment 1, Part 4
Subtraction with valid operands
Catch the exception on bad input and provide an informative error message. The application doesn’t stop. The user can back up and try again.
Something unexpected, and maybe not ideal: Some documentation says that division by 0 will throw the ArithmeticException. Even if you try to catch that, it will be ignored, and the result of the invalid operation is shown in this way.
The idea now is that “+” can make sense for both numbers and strings, but as soon as you include the other operations, strings don’t make sense Also, when you do division, dividing by 0 doesn’t make sense
Overall, a big change in the app is that it has 4 buttons instead of 1 You have a design choice to make Do all of the buttons go to the same sendMessage() method, and it contains if statements to sort out which button was pressed? Or is there a separate sendMessage() method for each button?
It turns out that a sendMessage() method can have a unique name—as long as you remember to keep the names straight in the code, the layout files, etc. To me it seemed far simpler to have a separate sendMessage() method for each button, sendMessage1(), sendMessage2(), …
sendMessage4(), for division, is shown on the following overhead It illustrates, in principle, how you can check for more than one kind of exception at a time As noted with the screen shots, in fact, catching the division by 0 does not work as advertised However, the logic for the other exception is fine
public void sendMessage4(View view) { Intent intent = new Intent(this, DisplayConcatenatedInputStrings.class); EditText editText = (EditText) findViewById(R.id.editText); EditText editText2 = (EditText) findViewById(R.id.editText2); try { double double1 = Double.parseDouble(editText.getText().toString()); double double2 = Double.parseDouble(editText2.getText().toString()); double result = double1 / double2; message = result + ""; } catch(NumberFormatException e) { message = "NumberFormatException thrown. Please enter valid numbers."; } catch(ArithmeticException e) { message = "You just tried to divide by zero. Please enter a different divisor."; } intent.putExtra(EXTRA_MESSAGE, message); startActivity(intent); message = ""; }
5.8 Assignment 1, Part 5
Enter the first value Then click + Enter the second value Then click = Ta-Da
It should be apparent that this version of the app more closely models the functionality of a desktop calculator app At a conceptual level, it may be a step beyond the foregoing apps, but at an implementation level, it is pretty simple It just has the one layout, and for the time being, there it is not necessary to do anything fancy with thrown exceptions
It is so mysteriously simple, the complete code for the app is shown on the following overheads in case you are in doubt about how to get it to work
package com. example. kascott. assignment1part5; import android package com.example.kascott.assignment1part5; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.EditText; public class MainActivity extends AppCompatActivity { public final static String EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE"; String message = ""; double input1 = 0.0; double input2 = 0.0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); }
public void sendMessage1(View view) { EditText editText = (EditText) findViewById(R.id.editText); try { input1 = Double.parseDouble(editText.getText().toString()); } catch(NumberFormatException e) { /* What to do in error cases? */ } editText.setText(""); }
public void sendMessage2(View view) { EditText editText = (EditText) findViewById(R.id.editText); try { input2 = Double.parseDouble(editText.getText().toString()); } catch(NumberFormatException e) { /* What to do in error cases? */ } double result = input1 + input2; String resultText = result + ""; editText.setText(resultText); }
Summary and Assignment The assignment is simple: Do the five parts reviewed above Remember that you will turn these in at the same time you turn in the second half of the assignment, which is explained in coming sets of overheads
A Look Ahead This sequence of assignment steps is a starting point for thinking about a calculator app Later in the course, making a more complete, realistic, and attractive calculator app will be an assignment At that time, you may want to come back to these parts of assignment 1 and review some of the ideas introduced here
The End