How to finish current activity in Android

Shah picture Shah · Feb 15, 2011 · Viewed 242k times · Source

I have an Android application. I am making a loading screen with a progress bar.

I entered a delay in the onCreate method. When the timer finishes, I want to finish the current activity and start a new one.

It just gives me an exception when it calls the finish() method.

public class LoadingScreen extends Activity{
    private LoadingScreen loadingScreen;
    Intent i = new Intent(this, HomeScreen.class);
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.loading);

        CountDownTimer timer = new CountDownTimer(10000, 1000) //10 second Timer
        {
            public void onTick(long l) 
            {

            }

            @Override
            public void onFinish() 
            {
                loadingScreen.finishActivity(0);
                startActivity(i);
            };
        }.start();
    }
}

How can I change the code so that it ends when the progress bar is done?

Answer

Alex Orlov picture Alex Orlov · Feb 15, 2011

If you are doing a loading screen, just set the parameter to not keep it in activity stack. In your manifest.xml, where you define your activity do:

<activity android:name=".LoadingScreen" android:noHistory="true" ... />

And in your code there is no need to call .finish() anymore. Just do startActivity(i);

There is also no need to keep a instance of your current activity in a separate field. You can always access it like LoadingScreen.this.doSomething() instead of private LoadingScreen loadingScreen;