We have an existing Android Avocado Facts application created in an older Kotlin Thursdays post, but for any Android application to be seriously useful, we will have to upgrade our facts to be more than just hard-coded. Feel free to follow along with our Github repo. In this post, we will set up an Async Task like a pro!

References

Async Tasks in Android

Async Tasks are a lightweight threading construct given by Android OS. Being an Android-specific concept, it is not created by Java or Kotlin. Async Tasks makes most common task of doing some heavy-weight operation off main thread easy and simple.

The Android OS is able to refresh the UI 64 frames per second — to achieve this, the UI Thread, or the Main Thread, needs to be free as much as possible. Long running tasks like communicating with APIs or databases could lock up your UI thread if it is not done in a background thread. One way to achieve this is by off-loading any longer running tasks to other threads. AsyncTasks is very powerful construct provided by OS to help achieve this.[more details]






Creating an AsyncTask in Android

An AsyncTask has three generic parameter types:

AsyncTask<Params, Progress, Result> 
- params: the type of the parameters sent to the task upon execution
- progress: the type of the progress units published during the background computation
- result: the type of the result of the background computation

We can actually think about implementing our Async tasks in the order these parameter types are defined!

Step 1:

We must analyze if any runtime parameters need to be sent for execution of the task. In our example to generate a new fact, we only need to invoke the function. Hence, the param type is Void.

Step 2:

Do we need to know about the progress percentage of this task?

In our async task, there is no concept of progress hence the progress type is also Void. One example where this is crucial will be downloading a big file.

Step 3:

What is the result of task? The type we designate here also tells us how will we can update our UI with the result. In particular, we want to show the user new fact which is of type String.

All these steps gives us our signature

AsyncTask<Void, Void, String>() {

Step 4:

Start by extending the abstract class and implementing minimum

override fun doInBackground(vararg params: Void?): String {

Step 5:

Any ui update if need will need.

Shortcut tip: ctrl + o (override method shortcut in android studio) will help do method setup
override fun onPostExecute(result: String?) {

Here we need to set result string as Textview’s text value. We have method in activity that will update it for us. So to call it we need to pass that to task so it can call it. Changing class to have

private class NewAvocadoFactTask(val activity: MainActivity)

Okay! Now just call is left

Step 6:

In onClick method call

moarButton.setOnClickListener {
NewAvocadoFactTask(this).execute();
}

Now for the MOST important step: you are leaking your activity!

How?? What??

AsyncTask is a threading construct. AsyncTask started a new thread and it doesn’t know your app may or may not have been killed by the time we have our response. In other words, AsyncTask runs independent of the main app in the background thread. So if the app is closed first without first ending the task, that task could still be running. After the response is returned, AsyncTask is responsible for returning the result to the main thread itself as a callback.

Is passing the actual activity val activity: MainActivity really safe? Should we try to call something that could be garbage collected?? Maybe we should use a wrapper called WeakReference.

var reference: WeakReference<MainActivity> = WeakReference(activity)

What is WeakReference? Glad you asked. It is a wrapper type that would be ok if the object it was keeping track of was garbage collected. Incase that happens it will indicate you the object you wanted reference for is no longer present.

reference.get() will yield a null. So we make our UI update call with elvis operator

reference.get()?.updateAvocadoFact(it)



Gotcha(s)

  1. Always pass any context in AsyncTask with WeakReference Wrapper
var reference: WeakReference<MainActivity> = WeakReference(activity)

2. Use OnProgressUpdate() and OnPostExecute() to show something on UI

override fun onPostExecute(result: String?) {
Log.v(tag,”onPostExecute is running on ${Thread.currentThread().name}”)
  super.onPostExecute(result)
result?.let {
// if reference.get is not null execute the function
reference.get()?.updateAvocadoFact(it)
}
}

Logging will help you see which functions are executed on Main thread since UI elements can only be touched by Main thread.

3. Always create a new Task object for a execute.

moarButton.setOnClickListener {
NewAvocadoFactTask(this).execute()
}

From threading rules of Async Task

The task can be executed only once (an exception will be thrown if a second execution is attempted.)



You can see the complete Github repo here:

We’ve set up our Async Task, but we actually need the request for the task to connect to a database so we can grab our Avocado Facts. In the next post, we will set up a database in Firebase and get our Async Task connected! See you next week.

Views: 168

Happy 10th year, JCertif!

Notes

Welcome to Codetown!

Codetown is a social network. It's got blogs, forums, groups, personal pages and more! You might think of Codetown as a funky camper van with lots of compartments for your stuff and a great multimedia system, too! Best of all, Codetown has room for all of your friends.

When you create a profile for yourself you get a personal page automatically. That's where you can be creative and do your own thing. People who want to get to know you will click on your name or picture and…
Continue

Created by Michael Levin Dec 18, 2008 at 6:56pm. Last updated by Michael Levin May 4, 2018.

Looking for Jobs or Staff?

Check out the Codetown Jobs group.

 

Enjoy the site? Support Codetown with your donation.



InfoQ Reading List

Presentation: Production Comes First - An Outside-In Approach to Building Microservices

Martin Thwaites introduces outside-in testing, how to use Observability techniques in a local development to build applications that are easier to debug locally and run as a first class citizen.

By Martin Thwaites

Physical Intelligence Unveils Robotics Foundation Model Pi-Zero

Physical Intelligence recently announced π0 (pi-zero), a general-purpose AI foundation model for robots. Pi-zero is based on a pre-trained vision-language model (VLM) and outperforms other baseline models in evaluations on five robot tasks.

By Anthony Alford

AWS Launches Lambda SnapStart for Python and .NET Functions

AWS has unveiled Lambda SnapStart for Python and .NET, enhancing serverless app performance by reducing cold start latency. This feature builds on the success of Lambda SnapStart for Java, allowing faster initializations through early environment caching. Available in multiple global regions, it offers efficient management of caching costs with Python 3.12+ and .NET 8+.

By Steef-Jan Wiggers

AWS Reveals Multi-Agent Orchestrator Framework for Managing AI Agents

AWS has introduced Multi-Agent Orchestrator, a framework designed to manage multiple AI agents and handle complex conversational scenarios. The system routes queries to the most suitable agent, maintains context across interactions, and integrates seamlessly with a variety of deployment environments, including AWS Lambda, local setups, and other cloud platforms.

By Daniel Dominguez

Java News Roundup: Last of the JEPs Targeted to JDK 24, Quarkus 3.17, Maven 4.0-RC1, Kotlin 2.1

This week's Java roundup for November 25th, 2024 features news highlighting: the last of the JEPs targeted to JDK 24 before Rampdown Phase One; the release of Quarkus 3.17.0, Hibernate Search 7.2.2, Kotlin 2.1.0 and JDKUpdater 14.0.67+100; the second release candidate of Vert.x 5.0 and the first release candidate of Maven 4.0.0.

By Michael Redlich

© 2024   Created by Michael Levin.   Powered by

Badges  |  Report an Issue  |  Terms of Service