Can someone please help me implent the java coding section. I only get the building view part of the xml layout. I need help with the Mortgage Data section , Exception Handling section, Voice output section, and clear on shake section. Please and thankyou.
20 MCalcPro Cash Price Amortization Interest (%) ANALYZE for MCalcPro The ples 400000 D3 20 The amc the devi Ast 1 2 ANALYZE Monthly Payment = 2,639.82 4 5 8 0 By making this payments monthly for 20 years, the mortgage will be paid in full. Butf you terminate the mortgage on its nth anniversary, the balance still owing depends on n as shown below: Figure 13.1 Upon launching the app n Balance 400,000 388,051 375,490 Figure D3.2 Upon tapping the ANA 2 pon tapping the ANALYZE button 03.1-REQUIREMENT D3.1- REQUIREMENT app is similar to the one built in the previous chapter except 13.1.a - The MCalcPro App This Mortgage-Calculator-Pro app i for two key differences: A professional look-and-feel on the outside, and Full API delegation on the inside. sich and crash-proof, and the latter means we don't im- The former means the app is fear plement anything ourselves! The ing ourselves! The result is a symphony in which we are the maestro monthly to Daidinti on its owing D3.1b - UI and Behaviour visible UI consists of fire vertically aligned widgets: three textboxes (for the cash price amortization, and interest), a button captioned "ANALYZE", and label for displaying the output (see Figures D3.1 and D3.2). The widgets extend across the entire width of the device (regardless of size) in portrait and landscape modes. As to behaviour, the app must: 1. Equip each textbox with a hint in lieu of a label) to prompt the user. The hint gets over- written by the input and it reappears whenever the input is cleared. 2. Display a soft keyboard that is appropriate for the input. The keyboard's next button must move the focus to the next input field, if any. 3. Validate the input when the button is tapped: the cash price (aka the principle) must be a positive real number; the amortization must be an int in r20.307: and the interest rate percent must be a non-negative real number ca 50 4. Issue an error message in a brief, floating bubble if any exception is thrown. Display the analysis for valid input below the button with vertical scrolling as needed. analysis consists of the monthly payment (rounded to the nearest cent) and a table ows the balance owing (rounded to the nearest dollar) if the mortgage is stopped 0,1,2,3,4,5,10,15,20 years. All amounts must have thousands separators. hly payment must be spoken (voice output) in addition to being displayed. and any output must be cleared if the device is shaken strongly; specifically, whenever the device acceleration exceeds 20 m/s. 7. The monthly payment mu 8. All entries and any out oice receives foc ptional decimal por sboards cut down tc them. Specific DOING 98 Chapter 3 A Symphony of APIs Based on this requirement, the soft keyboard that pops when the cash price must allow the user to only enter a real number (ie. digits with an option while the amortization keyboard must allow only integers. Such soft keyboard invalid inputs (such as entering letters) but does not completely eliminate the the user can still manage to make invalid inputs in two ways Make Non-Numeric Entries For example, the user can simply leave one of the input fields blank. In thi try cannot be parsed into a real number and must be handled or else the bok. In this case the d or else the app will crash 5 for the interest. These Make Out-Of-Range Entries For example, the user can enter 12 for the amortization or 75 for the intere not create parsing problems but must still be handled as per the requirement. Requirement specifies that invalid input must be handled (i.e. it must not be allow the computation part of the app) and the handling must culminate in an error mess message must indicate why the input is invalid, must appear for a short time and then appear, and must float "above" the UI. Fig. D3.3 is shows an example of the error mese that must appear briefly when the entered interest is not within the specified range. 1 2 3 4 5 6 a o 9 Interest out of range! * 0 # DO Figure 3.3 This brief, ficating error message appears if the entered interest is invalid at your app must examine the entries in the order of their appcar reports the first invalid one. For example, if the user e button, then the error message would be "Cash Price not nu appearance in the UI and or example, if the user left all entries blank and tappe Cash Price not numeric!". ad tapped the DOING ve 03- Spor w If the input is valid, the a the left appeared when the full height of the analys the app displays the analysis as shown in D34. The screenshot hen the button was tapped. But since the device could na sis, the user had to scroll down, which led to the right MCP 400000 100000 est. Those ed to ANALYZE Monthly Payment 2,639.82 ANALYZE 388,051 2 By making this payments monthly for 20 years, the mortgage will be paid in full. But if you terminate the mortgage on its nth anniversary, the balance still owing depends onn as shown below. 375,490 362287 3 348 408 333,819 n Balance 248,886 400,000 15 139,886 388,051 375,490 Figure 13.4 The analysis appears as in the left screenshot. Scrolling down leads to the right screenshot The analysis starts with a line that shows the monthly mortgage payment properly formatted (this is the line that must be read aloud). Below this line is a fixed explanatory paragraph and then a table of two columns and ten rows (including a header row). The formatting of these clements should be as close as possible to the above screenshots. In particular, the figures in the second column should be rounded to the nearest dollar with a thousand separator. The table shows how much is still owing to the bank if the mortgage is terminated before its amortization. For example, if this mortgage is terminated on its 5 anniversary, you would need to pay the bank $333,819. The table shows the outstanding balance (still owing) on the 1", 2, 3, 4, 5, 10, 15, and 20th anniversaries. The Oh anniversary termination on start Is there as a self-check and its outstanding balance must be the full cash price 100 Chapter 3 A Symphony of APIs DOING D3.2 - DESIGN As advertised carlier, this project is about orchestrating the required functionality together a bunch of APIs. As such, there is no model for us to build our acti on ready-made components whose APIs are described in the following sections. activity will ich o n D3.2.a - The MPro API The textbook's library (12c.jar) contains a class named MPro whose API fulfills om allows us to create an instance having a user-supplied principle, amortization, and i and it has methods that compute all the figures needed to compose the required an Moreover, the class has mechanisms in place that validate the user input and return i that we can display if any entry is invalid. Hence, this class has everything we need to vali the input and to generate the output. Add the textbook's library to your project's denen cies as shown in Chapter 0. API fulfills our needs. It and interest required analysis d return messages D3.2.b - The Toast API A ready-made class named Toast has an API that provides methods for displaying a floatia message (a toast) to the user for a brief period of time. Hence, this class has everythine we need to display error messages when the input is invalid. D3.2.c - The IME API This ready-made Input-Method-Editor API allows us to customise the soft keyboard that pops when a textbox widget receives focus. We can control what keys the keyboard contains and what happens when the keyboard's action key is tapped (e.g. move to the next entry) D3.2.d - The TTS API This ready-made Text-To-Speech API allows us to synthesize voice from any string in many languages. We simply create a default instance and then mutate it for our locale. After wards, we simply invoke the speak method and pass to it the text to be spoken. D3.2.e - The Accelerometer API This ready-made API allows us to monitor the acceleration sensor on the device. Whenever the device is accelerated, an event is fired and a method in our activity is invoked with the three components of the acceleration vector passed to it. We simply clear the fields if length of that vector exceeds the threshold specified in the requirement. D3.3-IMPLEMENTATION Create a project MCalcPro with activity MCalcPro Activity and layout mcalcpro_layout. MCalcPro D3.3.a - Building the View Add three textboxes pBox, aBox, and iBox and set the hint attribute of each to the prompts as shown. Set the Input Type attribute of the P and i boxes to numberDecimal and that of the a box to number. This attribute is part of the IME (input-method-editor) API and it dictates the type of soft keyboard that pops and the allowed characters. Next, add a button with a caption and connect its onClick attribute to a method in the activity (see Fig. D3.5). Cash Price Amortization interest Below the button, add a ScrollView and anchor it under the button and make it extend to both sides and to the bottom edge of the screen. Use the techniques you learned in Chapter 0 This way, it would extend sideways and down to the edge of the device in both portrait and landscape modes. Scroll view is a container widget that can hold other widgets inside it. Its role is to enable scrolling: if the contents in the widgets inside it do not fit in the visible device window, it enables the end user to swipe up and Figure D3.5 The UI elements. down and thus be able to see the content that is hidden "below" the edge of the device. It is a good idea though not specified in the requirement) to set the scrollingIndicators attribute to right so that the user can see where about the scrolling window lies. Finally, add a label named output to the scroll view; i.e.it Component Tree should be inside the scroll view with match_parent for the ConstraintLayout layout width. The component tree should thus look as pBox (Edit Text) shown in Fig. D3.6. Set the font Family attribute of output waBox (Edit Text) Box (Edit Text) to monospace because this allows us to easily align the tabu- ok button - "ANALYZE lar part of the analysis. IscrollView A output (TextView) The requirement does not specify any particular size or Figure D3.6 The Ul component tree. colour for the output so set these as you see fit. DOING 102 Chapter 3 A Symphony of APIs D3.3.b - Mortgage Data This ready made class performs the needed analysis. Its API shows this con | MPro Constructor . public MPro ( ) Construct an instance having zero principle, AMORT_MIN amortization, and zero interest. The first observation we make here is that the description refers to "AMORT MIN known as fields in API lingo and represent public constants. Indeed, we see a field the API in addition to constructors and methods) and it looks like this: MPro Fields MEN. These a field schon public static final int AMORT MIN The minimum amortization period allowed (value=20). public static final int AMORT_MAX The maximum amortization period allowed (value=30). public static final double INTEREST_MAX The maximum interest rate percent allowed (value-50). public static final double EPSILON A small number that sets the resolution in this class. Any real number less than it in absolute value is deemed to be zero (value 0.001). As you can see all these fields are final (hence they are constants) and are all static so you refer to them in code using the class, rather than the instance, name before the dot for example, a client of MPro can include this line in its code: double x = MPro. INTEREST MAX; This effectively transfers a value across classes (from MPro to the client class). Syntax you can easily tell a field from a method by the absence of parentheses after the name Note that the API not only describes the contents of fields but also specifies tr Nevertheless, client code should refrain from referring to these values. Por es statement: double x - 50; is 100% equivalent to the one above (since INTEREST_MAX is 58) yet it should nc you think of a reason why not? For example, hould not be used Cod 103 DOING 033-IMPLEMENTATION In general, you should strive to avoid includin numbers (other than and +1) in your code because doing so makes your programs difficult to understand by others and even by you after a few weeks) and difficult to maintain (e.p. modify). Such so-called map m ers can be avoided by prefixing any declaration with the word final. For example, if the variable z holds a period measured in years and you want to convert it to months, you may be tempted to write: z-z. 12; // don't use magic numbers! But based on the above guideline and best practices, you should instead write final int MONTHS_PER_YEAR - 12; z - Z. MONTHS_PER_YEAR; It may take a few more seconds to write two lines instead of one but experience has shown that this can save months of work down the road. It makes it easier for someone reading the code to understand why z was multiplied by 12 (e. was it to convert teet to inches). In the case of MPro, the developer followed the above guidelines to handle the constants that determine the interest and amortization range, so we, as clients, should continue the practice. For example, to ensure that the interest is within range, we should ensure that: interest 20) (EditText) findViewById(R.id.pBox)).setText(""); CCEditText) findViewById(R.id.aBox)).setText(""); (EditText) findViewById(R.id. iBox)).setText(""); (TextView) findViewById(R.id.output)).setText(""); If the device is accelerated beyond 20 m/s, the boolean expression (a > 20 will true, and this will trigger the execution of the block following the if statement, turn will trigger the clearing of the four fields. On the other hand if (a > 20) eva false, the block following the if statement will be skipped, and the method will change to the displayed screen. method will end with 20 MCalcPro Cash Price Amortization Interest (%) ANALYZE for MCalcPro The ples 400000 D3 20 The amc the devi Ast 1 2 ANALYZE Monthly Payment = 2,639.82 4 5 8 0 By making this payments monthly for 20 years, the mortgage will be paid in full. Butf you terminate the mortgage on its nth anniversary, the balance still owing depends on n as shown below: Figure 13.1 Upon launching the app n Balance 400,000 388,051 375,490 Figure D3.2 Upon tapping the ANA 2 pon tapping the ANALYZE button 03.1-REQUIREMENT D3.1- REQUIREMENT app is similar to the one built in the previous chapter except 13.1.a - The MCalcPro App This Mortgage-Calculator-Pro app i for two key differences: A professional look-and-feel on the outside, and Full API delegation on the inside. sich and crash-proof, and the latter means we don't im- The former means the app is fear plement anything ourselves! The ing ourselves! The result is a symphony in which we are the maestro monthly to Daidinti on its owing D3.1b - UI and Behaviour visible UI consists of fire vertically aligned widgets: three textboxes (for the cash price amortization, and interest), a button captioned "ANALYZE", and label for displaying the output (see Figures D3.1 and D3.2). The widgets extend across the entire width of the device (regardless of size) in portrait and landscape modes. As to behaviour, the app must: 1. Equip each textbox with a hint in lieu of a label) to prompt the user. The hint gets over- written by the input and it reappears whenever the input is cleared. 2. Display a soft keyboard that is appropriate for the input. The keyboard's next button must move the focus to the next input field, if any. 3. Validate the input when the button is tapped: the cash price (aka the principle) must be a positive real number; the amortization must be an int in r20.307: and the interest rate percent must be a non-negative real number ca 50 4. Issue an error message in a brief, floating bubble if any exception is thrown. Display the analysis for valid input below the button with vertical scrolling as needed. analysis consists of the monthly payment (rounded to the nearest cent) and a table ows the balance owing (rounded to the nearest dollar) if the mortgage is stopped 0,1,2,3,4,5,10,15,20 years. All amounts must have thousands separators. hly payment must be spoken (voice output) in addition to being displayed. and any output must be cleared if the device is shaken strongly; specifically, whenever the device acceleration exceeds 20 m/s. 7. The monthly payment mu 8. All entries and any out oice receives foc ptional decimal por sboards cut down tc them. Specific DOING 98 Chapter 3 A Symphony of APIs Based on this requirement, the soft keyboard that pops when the cash price must allow the user to only enter a real number (ie. digits with an option while the amortization keyboard must allow only integers. Such soft keyboard invalid inputs (such as entering letters) but does not completely eliminate the the user can still manage to make invalid inputs in two ways Make Non-Numeric Entries For example, the user can simply leave one of the input fields blank. In thi try cannot be parsed into a real number and must be handled or else the bok. In this case the d or else the app will crash 5 for the interest. These Make Out-Of-Range Entries For example, the user can enter 12 for the amortization or 75 for the intere not create parsing problems but must still be handled as per the requirement. Requirement specifies that invalid input must be handled (i.e. it must not be allow the computation part of the app) and the handling must culminate in an error mess message must indicate why the input is invalid, must appear for a short time and then appear, and must float "above" the UI. Fig. D3.3 is shows an example of the error mese that must appear briefly when the entered interest is not within the specified range. 1 2 3 4 5 6 a o 9 Interest out of range! * 0 # DO Figure 3.3 This brief, ficating error message appears if the entered interest is invalid at your app must examine the entries in the order of their appcar reports the first invalid one. For example, if the user e button, then the error message would be "Cash Price not nu appearance in the UI and or example, if the user left all entries blank and tappe Cash Price not numeric!". ad tapped the DOING ve 03- Spor w If the input is valid, the a the left appeared when the full height of the analys the app displays the analysis as shown in D34. The screenshot hen the button was tapped. But since the device could na sis, the user had to scroll down, which led to the right MCP 400000 100000 est. Those ed to ANALYZE Monthly Payment 2,639.82 ANALYZE 388,051 2 By making this payments monthly for 20 years, the mortgage will be paid in full. But if you terminate the mortgage on its nth anniversary, the balance still owing depends onn as shown below. 375,490 362287 3 348 408 333,819 n Balance 248,886 400,000 15 139,886 388,051 375,490 Figure 13.4 The analysis appears as in the left screenshot. Scrolling down leads to the right screenshot The analysis starts with a line that shows the monthly mortgage payment properly formatted (this is the line that must be read aloud). Below this line is a fixed explanatory paragraph and then a table of two columns and ten rows (including a header row). The formatting of these clements should be as close as possible to the above screenshots. In particular, the figures in the second column should be rounded to the nearest dollar with a thousand separator. The table shows how much is still owing to the bank if the mortgage is terminated before its amortization. For example, if this mortgage is terminated on its 5 anniversary, you would need to pay the bank $333,819. The table shows the outstanding balance (still owing) on the 1", 2, 3, 4, 5, 10, 15, and 20th anniversaries. The Oh anniversary termination on start Is there as a self-check and its outstanding balance must be the full cash price 100 Chapter 3 A Symphony of APIs DOING D3.2 - DESIGN As advertised carlier, this project is about orchestrating the required functionality together a bunch of APIs. As such, there is no model for us to build our acti on ready-made components whose APIs are described in the following sections. activity will ich o n D3.2.a - The MPro API The textbook's library (12c.jar) contains a class named MPro whose API fulfills om allows us to create an instance having a user-supplied principle, amortization, and i and it has methods that compute all the figures needed to compose the required an Moreover, the class has mechanisms in place that validate the user input and return i that we can display if any entry is invalid. Hence, this class has everything we need to vali the input and to generate the output. Add the textbook's library to your project's denen cies as shown in Chapter 0. API fulfills our needs. It and interest required analysis d return messages D3.2.b - The Toast API A ready-made class named Toast has an API that provides methods for displaying a floatia message (a toast) to the user for a brief period of time. Hence, this class has everythine we need to display error messages when the input is invalid. D3.2.c - The IME API This ready-made Input-Method-Editor API allows us to customise the soft keyboard that pops when a textbox widget receives focus. We can control what keys the keyboard contains and what happens when the keyboard's action key is tapped (e.g. move to the next entry) D3.2.d - The TTS API This ready-made Text-To-Speech API allows us to synthesize voice from any string in many languages. We simply create a default instance and then mutate it for our locale. After wards, we simply invoke the speak method and pass to it the text to be spoken. D3.2.e - The Accelerometer API This ready-made API allows us to monitor the acceleration sensor on the device. Whenever the device is accelerated, an event is fired and a method in our activity is invoked with the three components of the acceleration vector passed to it. We simply clear the fields if length of that vector exceeds the threshold specified in the requirement. D3.3-IMPLEMENTATION Create a project MCalcPro with activity MCalcPro Activity and layout mcalcpro_layout. MCalcPro D3.3.a - Building the View Add three textboxes pBox, aBox, and iBox and set the hint attribute of each to the prompts as shown. Set the Input Type attribute of the P and i boxes to numberDecimal and that of the a box to number. This attribute is part of the IME (input-method-editor) API and it dictates the type of soft keyboard that pops and the allowed characters. Next, add a button with a caption and connect its onClick attribute to a method in the activity (see Fig. D3.5). Cash Price Amortization interest Below the button, add a ScrollView and anchor it under the button and make it extend to both sides and to the bottom edge of the screen. Use the techniques you learned in Chapter 0 This way, it would extend sideways and down to the edge of the device in both portrait and landscape modes. Scroll view is a container widget that can hold other widgets inside it. Its role is to enable scrolling: if the contents in the widgets inside it do not fit in the visible device window, it enables the end user to swipe up and Figure D3.5 The UI elements. down and thus be able to see the content that is hidden "below" the edge of the device. It is a good idea though not specified in the requirement) to set the scrollingIndicators attribute to right so that the user can see where about the scrolling window lies. Finally, add a label named output to the scroll view; i.e.it Component Tree should be inside the scroll view with match_parent for the ConstraintLayout layout width. The component tree should thus look as pBox (Edit Text) shown in Fig. D3.6. Set the font Family attribute of output waBox (Edit Text) Box (Edit Text) to monospace because this allows us to easily align the tabu- ok button - "ANALYZE lar part of the analysis. IscrollView A output (TextView) The requirement does not specify any particular size or Figure D3.6 The Ul component tree. colour for the output so set these as you see fit. DOING 102 Chapter 3 A Symphony of APIs D3.3.b - Mortgage Data This ready made class performs the needed analysis. Its API shows this con | MPro Constructor . public MPro ( ) Construct an instance having zero principle, AMORT_MIN amortization, and zero interest. The first observation we make here is that the description refers to "AMORT MIN known as fields in API lingo and represent public constants. Indeed, we see a field the API in addition to constructors and methods) and it looks like this: MPro Fields MEN. These a field schon public static final int AMORT MIN The minimum amortization period allowed (value=20). public static final int AMORT_MAX The maximum amortization period allowed (value=30). public static final double INTEREST_MAX The maximum interest rate percent allowed (value-50). public static final double EPSILON A small number that sets the resolution in this class. Any real number less than it in absolute value is deemed to be zero (value 0.001). As you can see all these fields are final (hence they are constants) and are all static so you refer to them in code using the class, rather than the instance, name before the dot for example, a client of MPro can include this line in its code: double x = MPro. INTEREST MAX; This effectively transfers a value across classes (from MPro to the client class). Syntax you can easily tell a field from a method by the absence of parentheses after the name Note that the API not only describes the contents of fields but also specifies tr Nevertheless, client code should refrain from referring to these values. Por es statement: double x - 50; is 100% equivalent to the one above (since INTEREST_MAX is 58) yet it should nc you think of a reason why not? For example, hould not be used Cod 103 DOING 033-IMPLEMENTATION In general, you should strive to avoid includin numbers (other than and +1) in your code because doing so makes your programs difficult to understand by others and even by you after a few weeks) and difficult to maintain (e.p. modify). Such so-called map m ers can be avoided by prefixing any declaration with the word final. For example, if the variable z holds a period measured in years and you want to convert it to months, you may be tempted to write: z-z. 12; // don't use magic numbers! But based on the above guideline and best practices, you should instead write final int MONTHS_PER_YEAR - 12; z - Z. MONTHS_PER_YEAR; It may take a few more seconds to write two lines instead of one but experience has shown that this can save months of work down the road. It makes it easier for someone reading the code to understand why z was multiplied by 12 (e. was it to convert teet to inches). In the case of MPro, the developer followed the above guidelines to handle the constants that determine the interest and amortization range, so we, as clients, should continue the practice. For example, to ensure that the interest is within range, we should ensure that: interest 20) (EditText) findViewById(R.id.pBox)).setText(""); CCEditText) findViewById(R.id.aBox)).setText(""); (EditText) findViewById(R.id. iBox)).setText(""); (TextView) findViewById(R.id.output)).setText(""); If the device is accelerated beyond 20 m/s, the boolean expression (a > 20 will true, and this will trigger the execution of the block following the if statement, turn will trigger the clearing of the four fields. On the other hand if (a > 20) eva false, the block following the if statement will be skipped, and the method will change to the displayed screen. method will end with