Question

Exercise 10-4   Move a task to an asychronous thread In this exercise, you’ll modify an app...

Exercise 10-4   Move a task to an asychronous thread

In this exercise, you’ll modify an app that downloads an image file from the Internet, writes that image to a file, and reads that image from the file.

Review and test the app

  1. Start Android Studio and open the project named ch10_ex4_TestAsync.
  2. Review the code for this app. Note that it uses an asynchronous task to download an image file from the Internet.
  3. Run the app. When it starts, it should briefly display the standard Android image. Then, it should download another image from the Internet, write it to a file, read that file, and display the image in an ImageView widget.

Move a task from the UI thread to another thread

  1. Create an asynchronous class named ReadFile that you can use to read and display the image file that’s stored on the device.
  2. Move all code within the readFile method to the doInBackground method of the ReadFile class. Then, delete the readFile class and clean up the code so there are no syntax errors.
  3. Run the app. You should get an error that indicates that you can’t update the UI thread from the background thread.
  4. Modify the declaration of the ReadFile class so it returns a Drawable object.
  5. Modify the doInBackground method so it returns a Drawable object.
  6. Modify the onPostExecute method so it uses the Drawable object to display the image.
  7. Run the app. It should work as before. However, the app now uses a separate thread to read the image file.
0 0
Add a comment Improve this question Transcribed image text
Answer #1

/main.xml

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:layout_width="fill_parent"

    android:layout_height="fill_parent"

    android:orientation="vertical" >

    <ImageView

        android:id="@+id/imageView1"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:src="@drawable/android" />        

</LinearLayout>

--------------------------------------------------------------------------------------------------------------

MyAndroidAppActivity.java

import android.graphics.Bitmap;

import android.graphics.BitmapFactory;

import android.support.v7.app.AppCompatActivity;

import android.os.Bundle;

import android.widget.ImageView;

public class ReadFile extends AppCompatActivity, AsyncTask<URL, Integer, Long>

{

    @Override

    protected void readFile(Bundle savedInstanceState) {

      File imgFile = new File("/storage/emulated/0/DCIM/Camera/IMG_20151102_193132.jpg");

      if(imgFile.exists()){

        Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());

        ImageView myImage = (ImageView) findViewById(R.id.imageviewTest);

        myImage.setImageBitmap(myBitmap);

      }

   Drawable d = getResources().getDrawable(android.R.drawable.ic_dialog);

   ImageView image = (ImageView)findViewById(R.id.image);

   image.setImageDrawable(d);

onPostExecute(d);

    }

protected Long doInBackground(URL urls) {
int count = urls.length;
long totalSize = 0;
for (int i = 0; i < count; i++) {
totalSize += Downloader.downloadFile(urls[i]);
publishProgress((int) ((i / (float) count) * 100));

onProgressUpdate(i);

if (isCancelled()) break;
}
return totalSize;
}

protected void onProgressUpdate(Integer  progress) {
setProgressPercent(progress[0]);
}

protected void onPostExecute(Drawable result) {
showDialog("Downloaded " + result + " bytes");
}

}

Add a comment
Know the answer?
Add Answer to:
Exercise 10-4   Move a task to an asychronous thread In this exercise, you’ll modify an app...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Exercise 11-4 Create a Reminder app In this exercise, you’ll add a service to a Reminder...

    Exercise 11-4 Create a Reminder app In this exercise, you’ll add a service to a Reminder app that displays a notification every hour that says, “Look into the distance. It’s good for your eyes.” Test the app 1. Start Android Studio and open the project named ch11_ex4_Reminder. 2. Review the code. Note that it contains a layout and a class for an activity, but no class for a service. 1. Run the app. Note that it displays a message that...

  • Develop a file loading app as shown below: User enters URL in an EditText. On the...

    Develop a file loading app as shown below: User enters URL in an EditText. On the on click listener of the load button, url’s data should be read into a html file in a separate thread as an asynchronous task.  Display a progress bar too. On the post execute method, display done text in a text view. On the click of Display button, data that’s stored in html file gets retrieved and displayed in text view. USING ANDRIOD STUDIO /...

  • Match each of these tasks with the classes that perform them. Some answers may be used...

    Match each of these tasks with the classes that perform them. Some answers may be used more than once. Obtain a task request to be sent from a different thread A. Message Queue and to be performed by this thread. B. Message Accept a new task request, then store it in another class C. Handler until this thread has time to perform the task. D. Looper Remove the top task request from the class that is storing it when the...

  • Include a second string auto-implemented property that represents the name of the course’s instructor. Modify the...

    Include a second string auto-implemented property that represents the name of the course’s instructor. Modify the constructor to specify two parameters—one for the course name and one for the instructor’s name. Modify method DisplayMessage such that it first outputs the welcome message and course name, then outputs "This course is presented by: ", followed by the instructor’s name. Use your modified class in a test app that demonstrates the class’s new capabilities. NOTE: You will need both a GradeBook file...

  • Java Programming Task #2 String.split and the StringBuilder Class 1. Copy the file secret.txt (Code Listing...

    Java Programming Task #2 String.split and the StringBuilder Class 1. Copy the file secret.txt (Code Listing 9.3) from the Student CD or as directed by your instructor. This file is only one line long. It contains 2 sentences. 2. Write a main method that will read the file secret.txt, separate it into word tokens. 3. You should process the tokens by taking the first letter of every fifth word, starting with the first word in the file. Convert these letters...

  • In this problem, you will create a selectable “To Do” List. To add a task to...

    In this problem, you will create a selectable “To Do” List. To add a task to this list, the user clicks the Add Task button and enters a description of the task. To delete a task from the list, the user selects the task and then clicks the Delete Task button. Open the HTML and JavaScript files provided as start-up files (index.html from within todo_list_Q.zip file). Then, review the HTML in this file. Note, within the div element, there is...

  • package _solution; /** This program demonstrates how numeric types and operators behave in Java Do Task...

    package _solution; /** This program demonstrates how numeric types and operators behave in Java Do Task #1 before adding Task#2 where indicated. */ public class NumericTypesOriginal { public static void main (String [] args) { //TASK #2 Create a Scanner object here //identifier declarations final int NUMBER = 2 ; // number of scores int score1 = 100; // first test score int score2 = 95; // second test score final int BOILING_IN_F = 212; // boiling temperature double fToC;...

  • In this exercise, you’ll modify the Future Value Calculator application to include a header and footer....

    In this exercise, you’ll modify the Future Value Calculator application to include a header and footer. Review the project Open the header.jsp file and note that it contains the code necessary for the start of an HTML page including the opening html, head, and body tags, the title for the web page, and a link including the CSS file. Open the footer.jsp file and note that includes a copyright notice and the closing body and html tags. Modify the code...

  • 1. The first task in this assignment creates the pid manager whose implementation can simply be...

    1. The first task in this assignment creates the pid manager whose implementation can simply be a single class. Of course, you can create any other classes you might need to implement the pid manager. You may use any data structure of your choice to represent the availability of process identifiers. One strategy adopts Linux’s approach of a bitmap in which a value of 0 at position i indicates that a process id of value i is available and a...

  • Modify your code from the previous exercise so that it could easily be modified to display...

    Modify your code from the previous exercise so that it could easily be modified to display a different range of numbers (instead of 1234567890) and a different number of repetitions of those numbers (instead of 60 total characters), with the vertical bars still matching up correctly. Write a complete class named NumbersOutput. Use two class constants instead of "magic numbers,", with one constant set to 6 for the number of repetitions, and the other set to 10 for the range...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT