Search code examples
javaandroidandroid-asynctaskandroid-contexttoast

Using Toast in another class file without Activity extends Android


I've 2 files: Core (extends Activity) and DwCore. I'm using AsyncTask in a Core subclass and I want to use Toast in DwCore subclass but I can't get properly the Core Context.

Core

class DwFiles extends AsyncTask<Void, Void, Long> {
    protected Long doInBackground(Void... parms) {
        long totalSize = 0;
        dwCore.mainCounter(Core.this);
        return totalSize;
    }
}

DwCore subclass

public void mainCounter(Context c){
    Integer count = 0;
    for(int i=0;i<count;i++){
        Toast.makeText(c, count.toString(), Toast.LENGTH_SHORT).show();
    }
}

Solution

  • You can't do anything that affects the UI from worker threads - that includes showing toasts.

    class DwFiles extends AsyncTask<Void, Void, Long> {
    protected Long doInBackground(Void... parms) {
        long totalSize = 0;
         publishProgress(check_point);
        return totalSize;
    }
    }
    
    protected void onProgressUpdate(Integer integers) {
       dwCore.mainCounter(Core.this);
    }