http://instinctcoder.com/android-studio-asynctask-return-value-to-caller/
Objectives
In order to demonstrate this, We’ll create a Calculator + application that helping us to add up a list of numbers. The app is a simple app which allows user to key in a list of numbers and hit the button and return a result. Assuming this is a very complex math
which will take a long time to process so we decided to put that complex math into a separate thread and will extend AsyncTask to accomplish this.
Android Studio AsyncTask Return Value to Caller
- Let’s start to create a project and name it AsyncTaskCallback, and the rest of step should be as standard, if you need guide on this step , please refer this link. These are the basic setting i’ve set.
- In src > main > res > layout > activity_main.xml. Add Button, EditText and TextView into activity_main.xml and it will look like this.
- We need to create an interface this interface is our main objective of this tutorial So whenever you need to call to another thread and expecting some result return you need to implement this interface so let’s see the code. In src > main > java > com.instinctcoder.asynctaskcallback, add a class and named it TaskCompleted.java. Paste below code into TaskCompleted.java
- In src > main > java > com.instinctcoder.asynctaskcallback, add a class and named it AsyncComplex.java. Paste below code into AsyncComplex.java
- In src > main > java > com.instinctcoder.asynctaskcallback, update MainActivity.java to look like below.
The code is quite self-explanatory it’s basically call AsyncComplex class when button is click and then calculated result will display via onTaskComplete.
- That’s all! Click Run (Shift +F10). and should see a screen like below. Input few numbers separate with comma after that click Calculate button and the result will display.
Hope you enjoy the post.
Nhận xét
Đăng nhận xét