>>> Create project - - - Select File New - New Project... Choose Empty Activity template,...
Fantastic news! We've Found the answer you've been seeking!
Question:
Transcribed Image Text:
>>> Create project - - - Select "File" "New" - "New Project..." Choose "Empty Activity" template, and click "Next". On "New Project" window, fill out information. Click "Finish". o Project name: AsyncTask o Package name: edu.csustan.cs3810.asynctask Save location: <your any directory>\codes\AsyncTask >>> Resources - - Define constants in resource files. Create dimens.xml, and add a constant, "layout_space". <resources> <dimen name="layout_space">20dp</dimen> </resources> - In themes.xml, add a text size, "textSize" as shown in rectangle. <!-- Customize your theme here. --> <item name="android:textSize">24sp</item> </style> </resources> >>> Main (View): UI Design In this step, we add UI components and arrange them on the screen. Go to "activity_main.xml". (Design). Change layout to "Relative Layout". For "Relative Layout", set "padding" attribute with "layout_space" constant. padding padding [@dimen/layout_space, ?, ?, ?, ?] @dimen/layout_space Add an input field and a button. Set IDs and Texts, and some attributes ID: inputTime Text: (none) InputType: number Hint: Enter time in seconds Component Tree RelativeLayout inputTime(Number) btnRun- "RUN" + Ab IblMsg ID: btnRun Text: RUN ID: IblMsg Text: (none) о btn Run and inputTime has 20dp gap. ✓ layout_margin layout_margin layout_marginStart layout_marginLeft [?, ?, 20dp, ?, ?] layout_marginTop 20dp Locate "IblMsg" TextView. o IblMsg is aligned to the left of the btnRun. layout_alignLeft @id/btnRun layout_alignParen layout alignParen o IblMsg is below btnRun. layout_below layout_centerHori layout_centerinPal @id/inputTime @id/btnRun @id/btnRun @id/inputTime @id/btnRun o IblMsg and btn Run has 20dp gap. ✓ layout_margin [?, ?, 20dp, ?, ?] - Locate "btnRun" button. layout_margin layout_marginStart o btnRun is aligned to the left of the inputTime. layout_alignLeft @id/inputTime layout_alignParen @id/inputTime 10 layout_marginLeft layout_marginTop 20dp Expected result is as follows. layout_alignParen@id/lblMsg о btnRun is below inputTime. layout_below @id/inputTime layout_centerHori @id/inputTime layout_centerInPa @id/lblMsg Enter time in seconds 20 RUN >>> AsyncTask (Model) In this step, we create a class (inheriting AsyncTask) that runs in background, receives input from main activity, and returns result to the main activity. Create "Task.java". ○ Right-click on package “edu.csustan.cs3810.asynctask". Select "New" "Java Class". о Fill out class name and hit Enter key. " Name: Task We see "error" (underlined in red color) on the class definition. We need to implement required methods for the AsyncTask class. Add "doInBackground()" method. о Click "Task", and hit alt + enter key. Click "Implement methods”. public class Task extends AsyncTask<Integer, Void, String> { Implement methods } Make 'Task' abstract C Task C Class Interface Enum @Annotation We create "Task" class. app manifests java New Java Class edu.csustan.cs3810.asynctask MainActivity C Task ivity_main.xml x Task.java X MainActivity.java package edu.csustan.cs3810.asynctask; public class Task { "Task" inherits "AsyncTask" class to run in the background. Add codes shown in rectangle. 5: integer "Finished": String public class Task extends AsyncTask<Integer Void, String> { } o "dolnBackground()" is chosen. Click "OK". 12 Select Methods to Implement ==> android.os.AsyncTask (m) dolnBackground(params:Params...): Result о Skeleton "dolnBackground()" is created. public class Task extends AsyncTask<Integer, Void, String> { @Override protected String doInBackground (Integer... integers) { return null; o Add codes as shown in rectangle. Change the name of parameters to params. @Override protected String doInBackground (Integer... params) { } ■ ◉ ■ int runningTime =params[0] 1000; // in seconds SystemClock.sleep(running Time); return "Finished"; // result "params[0]" is the time value retrieved from the input field. "runningTime" is time in seconds. "SystemClock.sleep(<time in milli seconds>) sleeps for the given time. The method returns result, "Finished". - Add "onPostExecute()" method. @Override protected void onPostExecute(String result) { } о ○ lblMsg.setText(result); "result" is the result that "dolnBackground()" method returns. "onPostExecute()" method is called after "dolnBackground()" finishes. It shows the result to "lblMsg" Ul component. о Please ignore the error of IblMsg. The error on "IblMsg" will be gone when we define the IbIMsg at the next step. [Variable] Define an instance variable as shown in rectangle. public class Task extends AsyncTask<Integer, Void, String> { private TextView lblMsg; o "lblMsg" is the UI component (in main activity) to which result is returned. [ Constructor] Add a constructor as shown in rectangle. public class Task extends AsyncTask<Integer, Void, String> { private TextView lblMsg; public Task(TextView lblMsg) { this.lblMsg = lblMsg; >>> Main (Controller): Logic Code In this step, we will make codes that run methods in Task object (in the background). Open "MainActivity.java". [Variable] Add a TextView instance variable as shown in rectangle. public class MainActivity extends AppCompatActivity private TextView lblMsg; [Method: onCreate()] In onCreate(), add codes (shown in rectangle) to access IblMsg UI component. @Override protected void onCreate(Bundle savedInstanceState) { } super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); |ɩblMsg = findViewById(R.id.lblMsg); [Method: run()] Add a method (that is called by click event of "RUN" button) to call methods in Task object. public void run(View v) { // make result empty lblMsg.setText(""); // get time EditText inputTime = findViewById(R.id.inputTime); int time = Integer.parseInt(inputTime.getText().toString()); // run task in background Task task = new Task(lblMsg); task.execute(time); time Main activity 5 RUN IblMsg AsyncTask<params, progress, result> >>> Test task.execute(time) "Finished" setText("") Run application. "Main" screen (activity) is shown. 7:25 AM AsyncTask Enter time in seconds RUN We make "IblMsg" empty. We get time from input field, and run methods (In task object) in the background (with input value, time). Type 5, and click "RUN" button. After 5 seconds, we see "Finished". The "sleep(5 seconds)" is running in the background. о The value of result ("Finished") is returned and shown to lblMsg. Connect the button UI component to event handler. о о Go back to "activity_main.xml", and choose "btnRun" on Component Tree. Component Tree RelativeLayout Ab inputTime (Number) btnRun "RUN" Ab IblMsg Choose "run" method for onClick event. 7:26 " AsyncTask 5 RUN Finished onClick overScrollMode > padding run MainActivity run he >>> Update AsyncTask: show progress In this step, we will change Task class to show progress of background thread. We want to print the remaining time before printing "Finished". Main activity AsyncTask<params, progress, result> 5 onProgressUpdate() dolnBackground() 5 RUN 5,4,3, 2,1 5, 4, 3, 2, 1 publishProgress( <remaining time>) every second result ("Finished") "Finished" IblMsg Notify end of process onPostExecute() "onProgressUpdate()" method is called when background thread ("doln Background()") runs "publishProgress()" method. In our case, "doln Background()" method runs "publishProgress()" with remaining time every second. "onProgressUpdate()" sends the remaining time to main Activity which shows the remaining time to lblMsg UI component. The type of "<remaining time>” in publishProgress() method should be same as the type of the progress (second parameter of AsyncTask). In our case, the type is "Integer". - Change the type of progress in Task class definition as shown in rectangle. progress: remaining time (5, 4, 3, 2, or 1) public class Task extends AsyncTask<Integer, Integer, String> { private TextView lblMsg; Create "onProgressUpdate()" method. @Override protected void onProgressUpdate (Integer... progress) { int remainingTime = progress[0]; lblMsg.setText(String.valueOf(remaining Time)); o "progress[0]" is the remaining time that "dolnBackground()" method returns. The remaining time is shown to IblMsg UI component. Change codes (as shown in rectangle) of "doInBackground()" method. @Override protected String doInBackground (Integer... params) { int runningTime = params[0]; // in seconds for (int i=runningTime; i > 0; i--) { } } о publishProgress (i); SystemClock.sleep( ms: 1000); return "Finished"; // result For example, runningTime is 5. In the "for" loop, it calls publish Progress() with 5, 4, 3, 2, and 1 every second. "i" variable means the remaining time. o "publishProgress()" is the built-in method. We don't have to implement the method. o System Clock.sleep(1000) waits for one second. >>> Test Run application. Type 5, and click "RUN" button. The remaining time is shown from 5 to 1 (which is the progress status), and last, "Finished" is printed. 7:38 A AsyncTask 5 3 RUN 7:38 A ☐ AsyncTask 5 RUN Finished >>> Create project - - - Select "File" "New" - "New Project..." Choose "Empty Activity" template, and click "Next". On "New Project" window, fill out information. Click "Finish". o Project name: AsyncTask o Package name: edu.csustan.cs3810.asynctask Save location: <your any directory>\codes\AsyncTask >>> Resources - - Define constants in resource files. Create dimens.xml, and add a constant, "layout_space". <resources> <dimen name="layout_space">20dp</dimen> </resources> - In themes.xml, add a text size, "textSize" as shown in rectangle. <!-- Customize your theme here. --> <item name="android:textSize">24sp</item> </style> </resources> >>> Main (View): UI Design In this step, we add UI components and arrange them on the screen. Go to "activity_main.xml". (Design). Change layout to "Relative Layout". For "Relative Layout", set "padding" attribute with "layout_space" constant. padding padding [@dimen/layout_space, ?, ?, ?, ?] @dimen/layout_space Add an input field and a button. Set IDs and Texts, and some attributes ID: inputTime Text: (none) InputType: number Hint: Enter time in seconds Component Tree RelativeLayout inputTime(Number) btnRun- "RUN" + Ab IblMsg ID: btnRun Text: RUN ID: IblMsg Text: (none) о btn Run and inputTime has 20dp gap. ✓ layout_margin layout_margin layout_marginStart layout_marginLeft [?, ?, 20dp, ?, ?] layout_marginTop 20dp Locate "IblMsg" TextView. o IblMsg is aligned to the left of the btnRun. layout_alignLeft @id/btnRun layout_alignParen layout alignParen o IblMsg is below btnRun. layout_below layout_centerHori layout_centerinPal @id/inputTime @id/btnRun @id/btnRun @id/inputTime @id/btnRun o IblMsg and btn Run has 20dp gap. ✓ layout_margin [?, ?, 20dp, ?, ?] - Locate "btnRun" button. layout_margin layout_marginStart o btnRun is aligned to the left of the inputTime. layout_alignLeft @id/inputTime layout_alignParen @id/inputTime 10 layout_marginLeft layout_marginTop 20dp Expected result is as follows. layout_alignParen@id/lblMsg о btnRun is below inputTime. layout_below @id/inputTime layout_centerHori @id/inputTime layout_centerInPa @id/lblMsg Enter time in seconds 20 RUN >>> AsyncTask (Model) In this step, we create a class (inheriting AsyncTask) that runs in background, receives input from main activity, and returns result to the main activity. Create "Task.java". ○ Right-click on package “edu.csustan.cs3810.asynctask". Select "New" "Java Class". о Fill out class name and hit Enter key. " Name: Task We see "error" (underlined in red color) on the class definition. We need to implement required methods for the AsyncTask class. Add "doInBackground()" method. о Click "Task", and hit alt + enter key. Click "Implement methods”. public class Task extends AsyncTask<Integer, Void, String> { Implement methods } Make 'Task' abstract C Task C Class Interface Enum @Annotation We create "Task" class. app manifests java New Java Class edu.csustan.cs3810.asynctask MainActivity C Task ivity_main.xml x Task.java X MainActivity.java package edu.csustan.cs3810.asynctask; public class Task { "Task" inherits "AsyncTask" class to run in the background. Add codes shown in rectangle. 5: integer "Finished": String public class Task extends AsyncTask<Integer Void, String> { } o "dolnBackground()" is chosen. Click "OK". 12 Select Methods to Implement ==> android.os.AsyncTask (m) dolnBackground(params:Params...): Result о Skeleton "dolnBackground()" is created. public class Task extends AsyncTask<Integer, Void, String> { @Override protected String doInBackground (Integer... integers) { return null; o Add codes as shown in rectangle. Change the name of parameters to params. @Override protected String doInBackground (Integer... params) { } ■ ◉ ■ int runningTime =params[0] 1000; // in seconds SystemClock.sleep(running Time); return "Finished"; // result "params[0]" is the time value retrieved from the input field. "runningTime" is time in seconds. "SystemClock.sleep(<time in milli seconds>) sleeps for the given time. The method returns result, "Finished". - Add "onPostExecute()" method. @Override protected void onPostExecute(String result) { } о ○ lblMsg.setText(result); "result" is the result that "dolnBackground()" method returns. "onPostExecute()" method is called after "dolnBackground()" finishes. It shows the result to "lblMsg" Ul component. о Please ignore the error of IblMsg. The error on "IblMsg" will be gone when we define the IbIMsg at the next step. [Variable] Define an instance variable as shown in rectangle. public class Task extends AsyncTask<Integer, Void, String> { private TextView lblMsg; o "lblMsg" is the UI component (in main activity) to which result is returned. [ Constructor] Add a constructor as shown in rectangle. public class Task extends AsyncTask<Integer, Void, String> { private TextView lblMsg; public Task(TextView lblMsg) { this.lblMsg = lblMsg; >>> Main (Controller): Logic Code In this step, we will make codes that run methods in Task object (in the background). Open "MainActivity.java". [Variable] Add a TextView instance variable as shown in rectangle. public class MainActivity extends AppCompatActivity private TextView lblMsg; [Method: onCreate()] In onCreate(), add codes (shown in rectangle) to access IblMsg UI component. @Override protected void onCreate(Bundle savedInstanceState) { } super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); |ɩblMsg = findViewById(R.id.lblMsg); [Method: run()] Add a method (that is called by click event of "RUN" button) to call methods in Task object. public void run(View v) { // make result empty lblMsg.setText(""); // get time EditText inputTime = findViewById(R.id.inputTime); int time = Integer.parseInt(inputTime.getText().toString()); // run task in background Task task = new Task(lblMsg); task.execute(time); time Main activity 5 RUN IblMsg AsyncTask<params, progress, result> >>> Test task.execute(time) "Finished" setText("") Run application. "Main" screen (activity) is shown. 7:25 AM AsyncTask Enter time in seconds RUN We make "IblMsg" empty. We get time from input field, and run methods (In task object) in the background (with input value, time). Type 5, and click "RUN" button. After 5 seconds, we see "Finished". The "sleep(5 seconds)" is running in the background. о The value of result ("Finished") is returned and shown to lblMsg. Connect the button UI component to event handler. о о Go back to "activity_main.xml", and choose "btnRun" on Component Tree. Component Tree RelativeLayout Ab inputTime (Number) btnRun "RUN" Ab IblMsg Choose "run" method for onClick event. 7:26 " AsyncTask 5 RUN Finished onClick overScrollMode > padding run MainActivity run he >>> Update AsyncTask: show progress In this step, we will change Task class to show progress of background thread. We want to print the remaining time before printing "Finished". Main activity AsyncTask<params, progress, result> 5 onProgressUpdate() dolnBackground() 5 RUN 5,4,3, 2,1 5, 4, 3, 2, 1 publishProgress( <remaining time>) every second result ("Finished") "Finished" IblMsg Notify end of process onPostExecute() "onProgressUpdate()" method is called when background thread ("doln Background()") runs "publishProgress()" method. In our case, "doln Background()" method runs "publishProgress()" with remaining time every second. "onProgressUpdate()" sends the remaining time to main Activity which shows the remaining time to lblMsg UI component. The type of "<remaining time>” in publishProgress() method should be same as the type of the progress (second parameter of AsyncTask). In our case, the type is "Integer". - Change the type of progress in Task class definition as shown in rectangle. progress: remaining time (5, 4, 3, 2, or 1) public class Task extends AsyncTask<Integer, Integer, String> { private TextView lblMsg; Create "onProgressUpdate()" method. @Override protected void onProgressUpdate (Integer... progress) { int remainingTime = progress[0]; lblMsg.setText(String.valueOf(remaining Time)); o "progress[0]" is the remaining time that "dolnBackground()" method returns. The remaining time is shown to IblMsg UI component. Change codes (as shown in rectangle) of "doInBackground()" method. @Override protected String doInBackground (Integer... params) { int runningTime = params[0]; // in seconds for (int i=runningTime; i > 0; i--) { } } о publishProgress (i); SystemClock.sleep( ms: 1000); return "Finished"; // result For example, runningTime is 5. In the "for" loop, it calls publish Progress() with 5, 4, 3, 2, and 1 every second. "i" variable means the remaining time. o "publishProgress()" is the built-in method. We don't have to implement the method. o System Clock.sleep(1000) waits for one second. >>> Test Run application. Type 5, and click "RUN" button. The remaining time is shown from 5 to 1 (which is the progress status), and last, "Finished" is printed. 7:38 A AsyncTask 5 3 RUN 7:38 A ☐ AsyncTask 5 RUN Finished
Expert Answer:
Answer rating: 100% (QA)
Based on the provided instructions heres how you can set up you... View the full answer
Related Book For
Intermediate Accounting
ISBN: 978-1260481952
10th edition
Authors: J. David Spiceland, James Sepe, Mark Nelson, Wayne Thomas
Posted Date:
Students also viewed these programming questions
-
Planning is one of the most important management functions in any business. A front office managers first step in planning should involve determine the departments goals. Planning also includes...
-
The following sample data have been collected from two independent samples from two populations. Test the claim that the second population median will exceed the median of the first population. a....
-
Consider the following events for Byer's Innovations Co. that occurred during 2017. 1. Leased factory space from Whole Properties Company for a one-year period starting November 1, 2017. Six months...
-
The following table lists six pairs of m and f values. Calculate the value of each of the following: a. f b. m 2 c. mf d. m 2 f 6 25 12 5 18 9 f 16 14
-
a. For the allowed energies of a particle in a box to be large, should the box be very big or very small? Explain. b. Which is likely to have larger values for the allowed energies: an atom in a...
-
The synthesis of ethyl chloride is accomplished by reacting ethylene with hydrogen chloride in the presence of an aluminum chloride catalyst: C 2 H 4 (g) + HC1 (g) catalyst ? C 2 H 5 C1 (g): ?H ?...
-
A first order liquid-phase reaction with an activation energy of 40 kcal mol takes place in an isothermal PFR at 200 C. (a) What temperature must a CSTR (having the same volume as the PFR) be...
-
Duck Corporation "forecasted" on December 21, 2020 to sell a machine to a company in Italy. The selling price was 500,000 euros, to be paid on March 21, 2021. To hodge against fluctuations in the...
-
If you put $5,790.42 into your 401(K) account that earns 7.5% interest annually, how much will be in your account after 45 years?
-
1. Describe any two conflict management/resolution Styles. Compare and contrast their effectiveness. 2. Describe at least one situation in which each of those two styles can be used, and discuss...
-
Analysis Questions Describe how the causes of software failures differ from hardware failures . Give at least three examples to support your explanation. Explain the concept of modular?
-
Reproduction of copyrighted works is permitted without payment of royalties under the fair use doctrine. The factors used in determining whether a use qualifies as fair are (1) the purpose and...
-
A call option with a strike price of $78 on a stock selling at $97 costs $21.5. What are the call options intrinsic and time values? what are the Intrinsic value and Time value?
-
What are the Ethical characteristics that will help improve the health organization?
-
Question 6.10 Current and deferred tax worksheets and tax entries From the hip Ltd?s statement of profit or loss for the year ended 30 June 2007 and extracts from its statements of financial position...
-
S&L Financial buys and sells securities expecting to earn profits on short-term differences in price. On December 27, 2021, S&L purchased Coca-Cola bonds at par for $875,000 and sold the bonds on...
-
The following is a portion of the condensed income statement for Rowan, Inc., a manufacturer of plastic containers: Required: 1. Determine Rowan's inventory turnover. 2. What information does this...
-
The way a debtor accounts for the restructuring depends on the extent of the reduction in cash payments called for by the restructured arrangement. Describe, in general, the accounting procedure for...
-
Figure 7.18 shows a liquid-level system in which two tanks have cross-sectional areas \(A_{1}\) and \(A_{2}\), respectively. The volume flow rate into tank 1 is \(q_{\mathrm{i}}\). A pump is...
-
For the three-room house shown in Figure 7.35, all rooms are perfect squares and have the same dimensions. An air conditioner produces an equal amount of heat flow \(q_{\mathrm{ho}}\) out of each...
-
Consider the single-tank liquid-level system shown in Figure 7.19, where the volume flow rate into the tank through a pipe is \(q_{\mathrm{i}}\). The liquid leaves the tank through an orifice of area...
Study smarter with the SolutionInn App