1. /*********************************************************************************************
*
* AsyncTaskSample.java
*
* Sample Java Code
*
* This file shows an implementation of an Asynchronous Task Object for use in an
* Android project. It does not perform any specific tasks.
*
* This sample code is Copyright by Matt Kutschera, 2017
*
* It may viewed by anyone, and may be distributed by LinkedIn only on my personal
* LinkedIn profile. Any other method of distribution is available only by approval on
* a case by case basis.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
**********************************************************************************************/
import android.os.AsyncTask;
import android.support.annotation.NonNull;
import android.widget.TextView;
import java.util.LinkedList;
public class AsyncTaskSample extends AsyncTask<String, Void, Integer> {
protected LinkedList<String> strings;
private TextView outputTextView;
/**
* AsyncTaskSample()
*
* Initializes the strings LinkedList
*
* @param textView textView object to write results to
*/
public AsyncTaskSample(@NonNull TextView textView)
{
strings = new LinkedList<String>();
outputTextView = textView;
}
/**
* doInBackground()
*
* Performs some time-consuming task in the background. As this is simply a sample,
* it artificially takes up some time using the wait() function.
*
* @param params at least one string to write to the textView object
* @return number of strings to write to textView
*/
@Override
protected Integer doInBackground(String... params)
{
int i;
for (i = 0; i < params.length; i++)
{
strings.add(params[i]);
try
{
wait(100);
} catch (InterruptedException e) {
2. e.printStackTrace();
}
}
return params.length;
}
/**
*
* onPostExecute()
*
* Writes the result of the task to the TextView object.
*
* @param result number of strings to write to textView
*/
@Override
protected void onPostExecute(Integer result)
{
super.onPostExecute(result);
String header = result.toString() + " strings.n";
outputTextView.setText(header);
for (String string: strings)
{
outputTextView.append(string + "n");
}
}
}