>>> 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
-
What are some benefits of the unwritten rules in corporate culture? And are they always bad? Thank you. Good answer will receive thumbs up
-
Past experiences, individual knowledge and history will shape customer's expectation. Furthermore, customers may each perceive a service or product in different ways. Briefly describe any FOUR (4)...
-
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....
-
Describe the major controls for cash receipts.
-
How would you decide when the benefits have been permanently achieved in the Routine phase?
-
a. Sketch possible arrangements for the piping and valves for Figure 14-6. Note that every tank needs to be able to receive fresh washwater or overflow from the next higher letter tank, except for...
-
Refer to Exercise 6-1. Calculate the amount of the noncontrolling interest to be deducted from consolidated income in arriving at 2011 controlling interest in consolidated net income.
-
Illustrate the put-call parity relationship for European options. Explain the major differences between the European and the American put-call parity relationship.
-
Of all the price analysis methodologies that exist, which are the foundational methods. Longing & Shorting. Trading & Investing. Volume & sentiment. On-chain & Macroeconomic. Mean reversion &...
-
For this milestone, you will frame the entity relationship model (ERM) and define the entities and attributes for the business. Your next steps will be to normalize your entities, define primary and...
-
An object of mass m = 1 kg hits a horizontal flat surface as shown in the figure. Find the magnitude of the impulse exerted by the ball on the surface. ( cos 3 7 = sin 5 3 = 0 , 8 , cos 5 3 = sin 3 7...
-
A factor tree is a way of accurately representing a number as the product of its prime factors. Here is an example. 12 So, 12 - 2x 2x 32x 3 (product of primes) The answer will be the same no matter...
-
A decedent's interest and taxes are deductible on both Forms 706 and 1041 only if: A. The decedent's will did not provide instructions. B. Either item is a deduction in respect of a decedent (DRD)....
-
Calculate the average cost per unit, using a perpetual inventory system. (
-
1. What is the market value of a bond that has an eleven year maturity, a coupon rate of 6.57 percent, a par value of $1,000, and pays interest semiannually? The current market yield is 5.68 percent....
-
The 8-bit registers A and B initially have binary values 11001010 and 10100011 respectively. Compute the 8-bit values in each register after the execution of the following sequence of...
-
Research an article from an online source, such as The Economist, Wall Street Journal, Journal of Economic Perspectives, American Journal of Agricultural Economics, or another academic journal. The...
-
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...
-
Which of the following is not true about producer surplus? a. Producer surplus is the difference between what sellers are paid and their cost of producing those units. b. Producer surplus is shown...
-
In a supply and demand graph, the triangular area between the demand curve and the supply curve lost because of the imposition of a tax, price ceiling, or price floor is a. the consumer surplus. b....
-
In a supply and demand graph, the triangular area under the demand curve but above the supply curve is a. the consumer surplus. b. the producer surplus. c. the marginal cost. d. the deadweight loss....
Study smarter with the SolutionInn App