How to make a Toast in top-level AsyncTask class












-1















I have a top-level Fetch class that extends AsyncTask and I have a MainActivity. I can't get the Fetch class to make a toast due to not having an instance of the MainActivity or its context. I have tried to pass the MainActivity to the Fetch class but it potentially leaks memory. I have tried setting a WeakReference instance of the context, but I can't make a toast from that.



I have read many other posts about this and most seem to have a static inner-class but mine is top-level and I would prefer to keep it that way.



The MainActivity creates an instance of Fetch and then executes it.



public class Fetch extends AsyncTask<Void, Integer, List<List<String>>>
{
@Override
protected void onPreExecute()
{
super.onPreExecute();
}
@Override
protected List<List<String>> doInBackground(Context... params)
{
// run tasks
}
@Override
protected void onProgressUpdate(Integer... progress)
{
}
@Override
protected void onPostExecute(List<List<String>> result)
{
super.onPostExecute(result);
}
}









share|improve this question





























    -1















    I have a top-level Fetch class that extends AsyncTask and I have a MainActivity. I can't get the Fetch class to make a toast due to not having an instance of the MainActivity or its context. I have tried to pass the MainActivity to the Fetch class but it potentially leaks memory. I have tried setting a WeakReference instance of the context, but I can't make a toast from that.



    I have read many other posts about this and most seem to have a static inner-class but mine is top-level and I would prefer to keep it that way.



    The MainActivity creates an instance of Fetch and then executes it.



    public class Fetch extends AsyncTask<Void, Integer, List<List<String>>>
    {
    @Override
    protected void onPreExecute()
    {
    super.onPreExecute();
    }
    @Override
    protected List<List<String>> doInBackground(Context... params)
    {
    // run tasks
    }
    @Override
    protected void onProgressUpdate(Integer... progress)
    {
    }
    @Override
    protected void onPostExecute(List<List<String>> result)
    {
    super.onPostExecute(result);
    }
    }









    share|improve this question



























      -1












      -1








      -1








      I have a top-level Fetch class that extends AsyncTask and I have a MainActivity. I can't get the Fetch class to make a toast due to not having an instance of the MainActivity or its context. I have tried to pass the MainActivity to the Fetch class but it potentially leaks memory. I have tried setting a WeakReference instance of the context, but I can't make a toast from that.



      I have read many other posts about this and most seem to have a static inner-class but mine is top-level and I would prefer to keep it that way.



      The MainActivity creates an instance of Fetch and then executes it.



      public class Fetch extends AsyncTask<Void, Integer, List<List<String>>>
      {
      @Override
      protected void onPreExecute()
      {
      super.onPreExecute();
      }
      @Override
      protected List<List<String>> doInBackground(Context... params)
      {
      // run tasks
      }
      @Override
      protected void onProgressUpdate(Integer... progress)
      {
      }
      @Override
      protected void onPostExecute(List<List<String>> result)
      {
      super.onPostExecute(result);
      }
      }









      share|improve this question
















      I have a top-level Fetch class that extends AsyncTask and I have a MainActivity. I can't get the Fetch class to make a toast due to not having an instance of the MainActivity or its context. I have tried to pass the MainActivity to the Fetch class but it potentially leaks memory. I have tried setting a WeakReference instance of the context, but I can't make a toast from that.



      I have read many other posts about this and most seem to have a static inner-class but mine is top-level and I would prefer to keep it that way.



      The MainActivity creates an instance of Fetch and then executes it.



      public class Fetch extends AsyncTask<Void, Integer, List<List<String>>>
      {
      @Override
      protected void onPreExecute()
      {
      super.onPreExecute();
      }
      @Override
      protected List<List<String>> doInBackground(Context... params)
      {
      // run tasks
      }
      @Override
      protected void onProgressUpdate(Integer... progress)
      {
      }
      @Override
      protected void onPostExecute(List<List<String>> result)
      {
      super.onPostExecute(result);
      }
      }






      android android-asynctask android-toast






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 16 '18 at 2:18







      Samuel

















      asked Nov 16 '18 at 1:19









      SamuelSamuel

      76311




      76311
























          2 Answers
          2






          active

          oldest

          votes


















          1














          One way, in doInBackground:



          runOnUiThread(new Runnable() {
          public void run() {
          Toast.makeText(<your class name>.this, "hello", Toast.LENGTH_SHORT).show();
          }
          });


          Or in onPostExecute(which invoked on the UI thread after the background computation finishes)



          Toast.makeText(<your class name>.this, "hello", Toast.LENGTH_SHORT).show();


          Edited: if you want to pass context to AsyncTask,you could do like:



          public class MyAsyncTask extends AsyncTask<Void, Integer, List<List<String>>>

          private final Context mContext;

          public MyAsyncTask(final Context context) {
          mContext = context;
          }
          }


          And in MainActivity :



          final MyAsyncTask task = new MyAsyncTask(getApplicationContext());
          task.execute();


          Edited again:
          I tested WeakReference successfully.



          public class ExampleAsyncTask extends AsyncTask {
          private WeakReference<Context> contextRef;

          public ExampleAsyncTask(Context context) {
          contextRef = new WeakReference<>(context);
          }


          @Override
          protected void onPostExecute(Object result) {
          Context context = contextRef.get();
          if (context != null) {
          Toast.makeText(context, "hello", Toast.LENGTH_SHORT).show();
          }
          }
          }


          In MainActivity:



            new ExampleAsyncTask(MainActivity.this).execute();





          share|improve this answer


























          • This does not work, the class that extends AsyncTask does not have an instance of the MainActivity or its context

            – Samuel
            Nov 16 '18 at 2:21











          • @Samuel create the AsyncTask class as an inner class of MainActivity

            – navylover
            Nov 16 '18 at 3:06











          • Yes I know, I said I didn't want to go that route unless I have to. Is there another way?

            – Samuel
            Nov 16 '18 at 3:10











          • @Samuel plz see my edited

            – navylover
            Nov 16 '18 at 3:10













          • I told you I already tried passing that and it gives a warning about it could leak memory.

            – Samuel
            Nov 16 '18 at 3:16



















          0














          yeah,Don't be worry ,you can use the application context.may be as follow:




          implement your App.getContext() in your Application.




          and use it in your "Fetch" class and execute it in MainThread.






          share|improve this answer























            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53330121%2fhow-to-make-a-toast-in-top-level-asynctask-class%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            2 Answers
            2






            active

            oldest

            votes








            2 Answers
            2






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            1














            One way, in doInBackground:



            runOnUiThread(new Runnable() {
            public void run() {
            Toast.makeText(<your class name>.this, "hello", Toast.LENGTH_SHORT).show();
            }
            });


            Or in onPostExecute(which invoked on the UI thread after the background computation finishes)



            Toast.makeText(<your class name>.this, "hello", Toast.LENGTH_SHORT).show();


            Edited: if you want to pass context to AsyncTask,you could do like:



            public class MyAsyncTask extends AsyncTask<Void, Integer, List<List<String>>>

            private final Context mContext;

            public MyAsyncTask(final Context context) {
            mContext = context;
            }
            }


            And in MainActivity :



            final MyAsyncTask task = new MyAsyncTask(getApplicationContext());
            task.execute();


            Edited again:
            I tested WeakReference successfully.



            public class ExampleAsyncTask extends AsyncTask {
            private WeakReference<Context> contextRef;

            public ExampleAsyncTask(Context context) {
            contextRef = new WeakReference<>(context);
            }


            @Override
            protected void onPostExecute(Object result) {
            Context context = contextRef.get();
            if (context != null) {
            Toast.makeText(context, "hello", Toast.LENGTH_SHORT).show();
            }
            }
            }


            In MainActivity:



              new ExampleAsyncTask(MainActivity.this).execute();





            share|improve this answer


























            • This does not work, the class that extends AsyncTask does not have an instance of the MainActivity or its context

              – Samuel
              Nov 16 '18 at 2:21











            • @Samuel create the AsyncTask class as an inner class of MainActivity

              – navylover
              Nov 16 '18 at 3:06











            • Yes I know, I said I didn't want to go that route unless I have to. Is there another way?

              – Samuel
              Nov 16 '18 at 3:10











            • @Samuel plz see my edited

              – navylover
              Nov 16 '18 at 3:10













            • I told you I already tried passing that and it gives a warning about it could leak memory.

              – Samuel
              Nov 16 '18 at 3:16
















            1














            One way, in doInBackground:



            runOnUiThread(new Runnable() {
            public void run() {
            Toast.makeText(<your class name>.this, "hello", Toast.LENGTH_SHORT).show();
            }
            });


            Or in onPostExecute(which invoked on the UI thread after the background computation finishes)



            Toast.makeText(<your class name>.this, "hello", Toast.LENGTH_SHORT).show();


            Edited: if you want to pass context to AsyncTask,you could do like:



            public class MyAsyncTask extends AsyncTask<Void, Integer, List<List<String>>>

            private final Context mContext;

            public MyAsyncTask(final Context context) {
            mContext = context;
            }
            }


            And in MainActivity :



            final MyAsyncTask task = new MyAsyncTask(getApplicationContext());
            task.execute();


            Edited again:
            I tested WeakReference successfully.



            public class ExampleAsyncTask extends AsyncTask {
            private WeakReference<Context> contextRef;

            public ExampleAsyncTask(Context context) {
            contextRef = new WeakReference<>(context);
            }


            @Override
            protected void onPostExecute(Object result) {
            Context context = contextRef.get();
            if (context != null) {
            Toast.makeText(context, "hello", Toast.LENGTH_SHORT).show();
            }
            }
            }


            In MainActivity:



              new ExampleAsyncTask(MainActivity.this).execute();





            share|improve this answer


























            • This does not work, the class that extends AsyncTask does not have an instance of the MainActivity or its context

              – Samuel
              Nov 16 '18 at 2:21











            • @Samuel create the AsyncTask class as an inner class of MainActivity

              – navylover
              Nov 16 '18 at 3:06











            • Yes I know, I said I didn't want to go that route unless I have to. Is there another way?

              – Samuel
              Nov 16 '18 at 3:10











            • @Samuel plz see my edited

              – navylover
              Nov 16 '18 at 3:10













            • I told you I already tried passing that and it gives a warning about it could leak memory.

              – Samuel
              Nov 16 '18 at 3:16














            1












            1








            1







            One way, in doInBackground:



            runOnUiThread(new Runnable() {
            public void run() {
            Toast.makeText(<your class name>.this, "hello", Toast.LENGTH_SHORT).show();
            }
            });


            Or in onPostExecute(which invoked on the UI thread after the background computation finishes)



            Toast.makeText(<your class name>.this, "hello", Toast.LENGTH_SHORT).show();


            Edited: if you want to pass context to AsyncTask,you could do like:



            public class MyAsyncTask extends AsyncTask<Void, Integer, List<List<String>>>

            private final Context mContext;

            public MyAsyncTask(final Context context) {
            mContext = context;
            }
            }


            And in MainActivity :



            final MyAsyncTask task = new MyAsyncTask(getApplicationContext());
            task.execute();


            Edited again:
            I tested WeakReference successfully.



            public class ExampleAsyncTask extends AsyncTask {
            private WeakReference<Context> contextRef;

            public ExampleAsyncTask(Context context) {
            contextRef = new WeakReference<>(context);
            }


            @Override
            protected void onPostExecute(Object result) {
            Context context = contextRef.get();
            if (context != null) {
            Toast.makeText(context, "hello", Toast.LENGTH_SHORT).show();
            }
            }
            }


            In MainActivity:



              new ExampleAsyncTask(MainActivity.this).execute();





            share|improve this answer















            One way, in doInBackground:



            runOnUiThread(new Runnable() {
            public void run() {
            Toast.makeText(<your class name>.this, "hello", Toast.LENGTH_SHORT).show();
            }
            });


            Or in onPostExecute(which invoked on the UI thread after the background computation finishes)



            Toast.makeText(<your class name>.this, "hello", Toast.LENGTH_SHORT).show();


            Edited: if you want to pass context to AsyncTask,you could do like:



            public class MyAsyncTask extends AsyncTask<Void, Integer, List<List<String>>>

            private final Context mContext;

            public MyAsyncTask(final Context context) {
            mContext = context;
            }
            }


            And in MainActivity :



            final MyAsyncTask task = new MyAsyncTask(getApplicationContext());
            task.execute();


            Edited again:
            I tested WeakReference successfully.



            public class ExampleAsyncTask extends AsyncTask {
            private WeakReference<Context> contextRef;

            public ExampleAsyncTask(Context context) {
            contextRef = new WeakReference<>(context);
            }


            @Override
            protected void onPostExecute(Object result) {
            Context context = contextRef.get();
            if (context != null) {
            Toast.makeText(context, "hello", Toast.LENGTH_SHORT).show();
            }
            }
            }


            In MainActivity:



              new ExampleAsyncTask(MainActivity.this).execute();






            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Nov 16 '18 at 5:08

























            answered Nov 16 '18 at 2:04









            navylovernavylover

            3,63031120




            3,63031120













            • This does not work, the class that extends AsyncTask does not have an instance of the MainActivity or its context

              – Samuel
              Nov 16 '18 at 2:21











            • @Samuel create the AsyncTask class as an inner class of MainActivity

              – navylover
              Nov 16 '18 at 3:06











            • Yes I know, I said I didn't want to go that route unless I have to. Is there another way?

              – Samuel
              Nov 16 '18 at 3:10











            • @Samuel plz see my edited

              – navylover
              Nov 16 '18 at 3:10













            • I told you I already tried passing that and it gives a warning about it could leak memory.

              – Samuel
              Nov 16 '18 at 3:16



















            • This does not work, the class that extends AsyncTask does not have an instance of the MainActivity or its context

              – Samuel
              Nov 16 '18 at 2:21











            • @Samuel create the AsyncTask class as an inner class of MainActivity

              – navylover
              Nov 16 '18 at 3:06











            • Yes I know, I said I didn't want to go that route unless I have to. Is there another way?

              – Samuel
              Nov 16 '18 at 3:10











            • @Samuel plz see my edited

              – navylover
              Nov 16 '18 at 3:10













            • I told you I already tried passing that and it gives a warning about it could leak memory.

              – Samuel
              Nov 16 '18 at 3:16

















            This does not work, the class that extends AsyncTask does not have an instance of the MainActivity or its context

            – Samuel
            Nov 16 '18 at 2:21





            This does not work, the class that extends AsyncTask does not have an instance of the MainActivity or its context

            – Samuel
            Nov 16 '18 at 2:21













            @Samuel create the AsyncTask class as an inner class of MainActivity

            – navylover
            Nov 16 '18 at 3:06





            @Samuel create the AsyncTask class as an inner class of MainActivity

            – navylover
            Nov 16 '18 at 3:06













            Yes I know, I said I didn't want to go that route unless I have to. Is there another way?

            – Samuel
            Nov 16 '18 at 3:10





            Yes I know, I said I didn't want to go that route unless I have to. Is there another way?

            – Samuel
            Nov 16 '18 at 3:10













            @Samuel plz see my edited

            – navylover
            Nov 16 '18 at 3:10







            @Samuel plz see my edited

            – navylover
            Nov 16 '18 at 3:10















            I told you I already tried passing that and it gives a warning about it could leak memory.

            – Samuel
            Nov 16 '18 at 3:16





            I told you I already tried passing that and it gives a warning about it could leak memory.

            – Samuel
            Nov 16 '18 at 3:16













            0














            yeah,Don't be worry ,you can use the application context.may be as follow:




            implement your App.getContext() in your Application.




            and use it in your "Fetch" class and execute it in MainThread.






            share|improve this answer




























              0














              yeah,Don't be worry ,you can use the application context.may be as follow:




              implement your App.getContext() in your Application.




              and use it in your "Fetch" class and execute it in MainThread.






              share|improve this answer


























                0












                0








                0







                yeah,Don't be worry ,you can use the application context.may be as follow:




                implement your App.getContext() in your Application.




                and use it in your "Fetch" class and execute it in MainThread.






                share|improve this answer













                yeah,Don't be worry ,you can use the application context.may be as follow:




                implement your App.getContext() in your Application.




                and use it in your "Fetch" class and execute it in MainThread.







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Nov 16 '18 at 2:25









                alei longalei long

                256




                256






























                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53330121%2fhow-to-make-a-toast-in-top-level-asynctask-class%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    Florida Star v. B. J. F.

                    Danny Elfman

                    Lugert, Oklahoma