Taylern
Taylern

Reputation: 116

How to display toast in AsyncTask

I want to display toast message in doInBackground as follows.

private class myAsync extends AsyncTask<Void, Integer, Void>
{
    int duration = 0;
    int current = 0;
    int inc = 0;

    @Override
    protected Void doInBackground(Void... params) {

        videoView.start();
        videoView.setOnPreparedListener(new OnPreparedListener() {

            public void onPrepared(MediaPlayer mp) {

                duration = videoView.getDuration();

            }
        });

        do {
            current = videoView.getCurrentPosition();
            inc = inc + 1;

            if(inc == 10000 || inc == 25000 || inc == 30000){
                Toast.makeText(getApplicationContext(), inc, Toast.LENGTH_LONG).show();
            }
       } while (current <= duration);          

        return null;
    }

    @Override
    protected void onProgressUpdate(Integer... values) {
        super.onProgressUpdate(values);
        Toast toast = Toast.makeText(getApplicationContext(),values[0], Toast.LENGTH_LONG);
        toast.setGravity(Gravity.CENTER, 0, 0);
        toast.show();
    }
}

I want to display the inc value when it is 10000, 25000, 30000.

I hope someone who knows this help me.

Thanks

Upvotes: 0

Views: 1014

Answers (2)

Taylern
Taylern

Reputation: 116

I solved it as I put publishProgress(inc); in if statement like

if(inc == 10000 || inc == 25000 || inc == 30000){
   publishProgress(inc);
}

it works.

Upvotes: 0

ToYonos
ToYonos

Reputation: 16833

Supposing MyAsync is nested in an Activity :

private class myAsync extends AsyncTask<Void, Integer, Void>
{
    int duration = 0;
    int current = 0;
    int inc = 0;

    @Override
    protected Void doInBackground(Void... params) {

        videoView.start();
        videoView.setOnPreparedListener(new OnPreparedListener() {

            public void onPrepared(MediaPlayer mp) {

                duration = videoView.getDuration();

            }
        });

        do {
            current = videoView.getCurrentPosition();
            inc = inc + 1;

            if(inc == 10000 || inc == 25000 || inc == 30000){
                showToast(inc);
            }
       } while (current <= duration);          

        return null;
    }

    @Override
    protected void onProgressUpdate(Integer... values) {
        super.onProgressUpdate(values);
        showToast(values[0]);
        // Todo integrate gravity parameter
    }

    private void showToast(String text)
    {
        MainActivity.this.runOnUiThread(new Runnable()
        {
            public void run()
            {
                Toast.makeText(MainActivity.this, text, Toast.LENGTH_LONG).show();
            }
        });
    }
}

Upvotes: 1

Related Questions