Search code examples
javaandroidandroid-asynctask

AsyncTask.get() in Activity.onCreate makes it take too much time to load and sometimes it crashes


When I start this activity, it takes too much time to load and sometimes my app crashes. I want to know if there is anything I can do so the activity will no start until the main activity is fully loaded in the previous activity or something like this so my activity will load without problems or crushes.

AdvertisingActivity.java

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.vectordrawable.graphics.drawable.Animatable2Compat;

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.load.resource.gif.GifDrawable;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.Target;

import java.util.concurrent.ExecutionException;

public class AdvertisingActivity extends AppCompatActivity {
    ImageView imageView;
    ImageView imageButton;
    String ImageClick = "";
    String ImageLink = "";
    private TextView Countdowner;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.advertising);
        getSupportActionBar().hide();
        imageView = findViewById(R.id.Advertisings);
        imageButton = findViewById(R.id.closebuttons);
        imageButton.setVisibility(View.GONE);
        Countdowner = findViewById(R.id.Countdowns);
        final ParseJson parsejson = new ParseJson();
        try {
            parsejson.execute().get();

        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        ImageLink = parsejson.getHouseAdsImage();
        ImageClick = parsejson.getHouseAdsClick();
        boolean ifGif = parsejson.getGIF();


        imageButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(parsejson.getHouseAdsClick()));
                AdvertisingActivity.this.startActivity(browserIntent);
            }
        });


        if (ifGif == true) {
            Glide.with(this).asGif().load(parsejson.getHouseAdsImage()).listener(new RequestListener<GifDrawable>() {
                @Override
                public boolean onLoadFailed(@Nullable @org.jetbrains.annotations.Nullable GlideException e, Object model, Target<GifDrawable> target, boolean isFirstResource) {
                    finish();
                    Toast.makeText(AdvertisingActivity.this, "Failed to load", Toast.LENGTH_SHORT).show();
                    return false;
                }

                @Override
                public boolean onResourceReady(GifDrawable resource, Object model, Target<GifDrawable> target, DataSource dataSource, boolean isFirstResource) {
                    resource.setLoopCount(1);
                    resource.registerAnimationCallback(new Animatable2Compat.AnimationCallback() {
                        @Override
                        public void onAnimationEnd(Drawable drawable) {
                            Glide.with(AdvertisingActivity.this).load(parsejson.getAfterGif()).into(imageView);
                            Toast.makeText(AdvertisingActivity.this, "GIF stopped", Toast.LENGTH_SHORT).show();
                        }
                    });
                    new CountDownTimer(13000, 1000) {

                        public void onTick(long millisUntilFinished) {
                            Countdowner.setText("You can close ad after: " + millisUntilFinished / 1000);
                        }

                        public void onFinish() {
                            imageButton.setVisibility(View.VISIBLE);
                            Countdowner.setVisibility(View.GONE);
                        }
                    }.start();
                    Toast.makeText(AdvertisingActivity.this, "Success to load", Toast.LENGTH_SHORT).show();

                    return false;
                }
            }).into(imageView);

        } else {
            Glide.with(AdvertisingActivity.this).load(parsejson.getAfterGif()).into(imageView);

        }
    }
}

Solution

  • Your problem is that you're waiting synchronously on the main thread for your AsyncTask to finish:

    parsejson.execute().get();
    

    You should basically never be calling AsyncTask.get() on the main thread: it will block the thread until it finishes, which defeats the point of an AsyncTask, which is to not block the main thread.

    Instead, you should do whatever you're waiting for in AsyncTask.onPostExecute.