Download presentation
Presentation is loading. Please wait.
Published byKenneth Weaver Modified over 6 years ago
1
Android 5: Assignment 1, First Half, Arithmetic Operations and Exceptions
3
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
4
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
5
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
6
5.1 Copying Projects in Android Studio
7
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
8
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
9
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
10
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
11
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
12
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
13
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
14
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
15
5.2 A Note on Assignments
16
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
17
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
18
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
19
5.3 A Preview Survey of the Parts of the Assignment in Screen Shots
20
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
21
Part 1
22
Part 2
23
Unfortunately, Error Messages Can be Uninformative. …OK…
24
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
26
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
27
Subtraction with valid operands
28
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.
29
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.
30
Part 5 Enter the first value Then click + Enter the second value
Ta-Da
34
5.4 Assignment 1, Part 1
35
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
36
Part 1
37
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
38
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
39
<resources> <string name="app_name">Assignment1Part1</string> <string name="inputHint">Enter a string.</string> </resources>
40
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
41
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
42
<. xml version="1. 0" encoding="utf-8"
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android=" xmlns:tools=" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.example.kascott.assignment1part1.MainActivity"> <EditText android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_alignParentLeft="true" android:layout_alignParentStart="true"
43
<EditText android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_marginLeft="39dp" android:layout_marginStart="39dp" <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="+" android:layout_alignParentTop="true" android:layout_alignParentRight="true" android:layout_alignParentEnd="true" android:onClick="sendMessage" /> </RelativeLayout>
44
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
45
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); } }
46
5.5 Assignment 1, Part 2
47
Part 2
48
Unfortunately, Error Messages Can be Uninformative. …OK…
49
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
50
double double1 = Double. parseDouble(editText. getText()
double double1 = Double.parseDouble(editText.getText().toString()); double double2 = Double.parseDouble(editText2.getText().toString());
51
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
52
5.6 Assignment 1, Part 3
54
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
55
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
56
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
57
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
58
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); }
59
5.7 Assignment 1, Part 4
60
Subtraction with valid operands
61
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.
62
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.
63
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
64
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?
65
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(), …
66
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
67
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 = ""; }
68
5.8 Assignment 1, Part 5
69
Enter the first value Then click + Enter the second value Then click = Ta-Da
73
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
74
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
75
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); }
76
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(""); }
77
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); }
78
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
79
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
80
The End
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.