Search code examples
androidandroid-asynctaskdeprecated

How to replace AsyncTask in this Android code?


I'm getting this issue on my android project:

This AsyncTask class should be static or leaks might occur.

How to replace the deprecated classe AsyncTask and avoid leaks in that code ? Thanks in advance

private class FetchUrl extends AsyncTask<String, Void, String> {

    @Override
    protected String doInBackground(String... url) {

        // For storing data from web service
        String data = "";

        try {
            // Fetching the data from web service
            data = downloadUrl(url[0]);
            Log.d("Background Task data", data);
        } catch (Exception e) {
            Log.d("Background Task", e.toString());
        }
        return data;
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);

        ParserTask parserTask = new ParserTask();

        // Invokes the thread for parsing the JSON data
        parserTask.execute(result);

    }
}

Solution

  • Make a kotlin class called CoroutineAsyncTask.kt:

    abstract class CoroutineAsyncTask<Params,Progress,Result>(){
    
    
        open fun onPreExecute(){ }
    
        abstract fun doInBackground(vararg params: Params?): Result
        open fun onProgressUpdate(vararg values: Progress?){
    
        }
    
        open fun onPostExecute(result: Result?){}
    
        open fun onCancelled(result: Result?){
    
        }
    
       protected var isCancelled= false
    
    
        //Code
        protected fun publishProgress(vararg progress: Progress?){
            GlobalScope.launch(Dispatchers.Main) {
                onProgressUpdate(*progress)
            }
        }
    
        fun execute(vararg params: Params?){
            GlobalScope.launch(Dispatchers.Default) {
                val result = doInBackground(*params)
                withContext(Dispatchers.Main){
                    onPostExecute(result)
                }
            }
        }
    
        fun cancel(mayInterruptIfRunnable: Boolean){
    
        }
    }
    

    And implement the CoroutineAsyncTask in your code from

    private class FetchUrl extends AsyncTask<String, Void, String> {
    }
    

    to

    private class FetchUrl extends CoroutineAsyncTask<String, Void, String> {
    }
    

    Now you should be fine. Happy coding, hope that helps!