Download XAAndroid5Assignment1FirstHalfArithmeticOpsNew

Document related concepts
no text concepts found
Transcript
Android 5: Assignment 1, First Half,
Arithmetic Operations and
Exceptions
1
2
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
3
• 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
4
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
5.1 Copying Projects in Android Studio
6
• 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
7
• 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
8
• 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
9
• 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
10
• 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
11
• 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
12
• 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
13
• 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
14
5.2 A Note on Assignments
15
• 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
16
• 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
17
• 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
18
5.3 A Preview Survey of the Parts of
the Assignment in Screen Shots
19
• 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
20
Part 1
21
Part 2
22
Unfortunately, Error Messages Can be
Uninformative. …OK…
23
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
24
25
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
26
Subtraction with valid operands
27
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.
28
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.
29
Part 5
•
•
•
•
•
Enter the first value
Then click +
Enter the second value
Then click =
Ta-Da
30
31
32
33
5.4 Assignment 1, Part 1
34
• 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
35
Part 1
36
• 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
37
• 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
38
•
<resources>
<string name="app_name">Assignment1Part1</string>
<string name="inputHint">Enter a string.</string>
</resources>
39
• 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
40
• 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
41
•
<?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"/>
42
•
<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>
43
• 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
44
•
package com.example.kascott.assignment1part1;
import
import
import
import
import
android.content.Intent;
android.support.v7.app.AppCompatActivity;
android.os.Bundle;
android.view.View;
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);
}
}
45
5.5 Assignment 1, Part 2
46
Part 2
47
Unfortunately, Error Messages Can be
Uninformative. …OK…
48
• 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
49
•
double double1 =
Double.parseDouble(editText.getText().toString());
double double2 =
Double.parseDouble(editText2.getText().toString());
50
• 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
51
5.6 Assignment 1, Part 3
52
53
• 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
54
• 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
55
• 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
56
•
•
•
•
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
57
•
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);
}
58
5.7 Assignment 1, Part 4
59
Subtraction with valid operands
60
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.
61
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.
62
• 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
63
• 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?
64
• 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(), …
65
• 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
66
•
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 = "";
}
67
5.8 Assignment 1, Part 5
68
•
•
•
•
•
Enter the first value
Then click +
Enter the second value
Then click =
Ta-Da
69
70
71
72
• 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
73
• 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
74
•
package com.example.kascott.assignment1part5;
import
import
import
import
import
android.content.Intent;
android.support.v7.app.AppCompatActivity;
android.os.Bundle;
android.view.View;
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);
}
75
•
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("");
*/
}
76
•
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);
}
77
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
78
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
79
The End
80