How to clean the data stored in memory, in cache or then reset an application (App) in android studio?

Asked

Viewed 808 times

0

I am developing an application in android studio and need to solve this problem.

I am using an internal database in Sqlopenhelper to store the products chosen by the user and show in a shopping cart. There are at most three products that the user can buy by delivery.

But what is happening is that the first time the user logs into the app it works perfectly and only allows the user to add at most three products in the shopping cart. However, if by chance the user already has with their full cart and press the "Home" button of the device and come back in the app again, it automatically allows the user to add three more products beyond the limit and I do not want this.

What I want is to know what I need to do to "reset" the app, if by chance, the user click the Home button of the device and not the right button for it to exit?

There is some specific method that when finalizing the app it re-remembers all memory?

I’ve heard of the onDestroy(){...}, But I think he’s just a detritus from Activity and that’s not what I want. I want the user to be independent of Activity, if the app closes, it resets.

1 answer

2

The onDestroy does not serve to destroy a Activity. It runs whenever an Activity is finished. To finish an Activity, you use the finish().

Independent of Activity that you use, onDestroy of Activity will be called every time this Activity is finalized. If your application has 5 activitys open and the entire application is finished, all 5 activitys will call your method onDestroy. Even if they’re not overwritten.

So, within the method you can create code to wipe the data.

@Override
public void onDestroy() {
    super.onDestroy();

    /* ... Códigos .... */
    limparDados();
}

You can also use the onPause. This method is called when the Activity is in "background" and you could already wipe the data at that moment, no matter if it opened a new Activity or pressed the home of the mobile phone.

@Override
public void onPause() {
    super.onPause();

    /* ... Códigos .... */
    limparDados();
}

If you want to reset the application when the user returns, you can use the onRestart:

@Override
public void onRestart(){
    super.onRestart();
    // cria uma nova activity
    startActivity(new Intent(this, MinhaActivity.class));
    finish(); // finaliza a activity aberta
}

Although this is what was requested, this is not the most viable solution, because in my view, the biggest problem is in your algorithm. In his logic. A logical condition somewhere would solve this problem to not let you add more products.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.