Deleting values when the user closes the application - android

So in my application I am using SharedPreferences to save fragment state. But I would like to delete those entries inside the SharedPreferences once the user steps outside of the application. I tried the following:
In my main class:
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
if(isFinishing() == true)
{
SM.removePreferences();
}
}
where SM is an instance of a helper class I created. removerPreferences does the following:
public void removePreferences(){
editor.clear();
editor.commit();
}
But I noticed that this was never executed. With the log, I did see that the app goes inside the isFinishing() if statement, but the method is never executed. I also did try the onDestroy(), but the method never got called.
Can someone help me on this ?

use onstop override to do that
like this:
#Override
protected void onStop() {
// TODO Auto-generated method stub
super.onStop();
if(isFinishing() == true)
{
SM.removePreferences();
}
}

Don't save your Fragment's instance state in SharedPreferences, but in the Bundle that is meant to do that. You can access it like this:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if ((savedInstanceState != null) {
// get your values, for example:
mID = savedInstanceState.getInt("ID");
}
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
// put your values, for example:
outState.putInt("ID", mID);
}
This way you don't have to manage the values yourself.
If you have custom Objects, you can make them implement Parcelable.
In contrast, SharedPreferences are meant to save values that should persist even after the application closes, i.e.: preferences.

The better location to do that is onDestroy() without the if statement.
however, you can read from Android documentation about onDestroy() that:
There are situations where the system will simply kill the activity's hosting process without calling this method (or any others) in it, so it should not be used to do things that are intended to remain around after the process goes away.
So, in my opinion, if you don't want data remains after activity ends, you should use a class to hold it.

I think that what you're looking for can be achieved using onSaveInstanceState mechanism.
Nonetheless, I'll try answering your specific question while assuming that by saying that "the method is never implemented" you mean that the if statement value is always false and that your method doesn't get called.
isFinishing() returns true only when you called finish() on the Activity or if someone else has requested that it will be finished.
If you just click on the home button, you will get isFinishing() == false, thus your method doesn't gets called. So make sure you're actually finishing the Activity and not just pausing it.
Anyways, the best way to find out what's the problem is to use the debugger.

Related

OnResume from specific activity

Im integrating TapResearch in my Android app. As mentioned here in the documentation https://www.tapresearch.com/docs/android-integration-guide that the to show the survey I need to use TapResearch.getInstance().showSurvey();. This method open an activity from the library.
In the documentation there is a listener onSurveyModalClosed() so I can put anything once the activity is finished, but this listener does not work.
Since onSurveyModalClosed() does not function. In the MainActivity I want the app to do something OnResume from TapResearch Activity.
#Override
protected void onResume() {
If the resume happens upon returning from TapResearch Activity {
Do something.
}
}
I think this is the activity path import
com.tapr.internal.activities.survey.SurveyActivity;
This may not be the best answer available but a workaround as this is the only thing I found for myself.
Whenever a specific activity is launched, I set a boolean variable as True in OnCreate() of that launched activity using TinyDB (sample code below), and when returning back to MainAcitivity, I check whether the variable is true and if true, then a specific code is executed.
In OnCreate() of launched activity:
TinyDB tinydb = new TinyDB(this);
tinydb.putBoolean("isMyActivity",true);
And in OnResume() of MainActivity:
#Override
protected void onResume() {
if(tinydb.getBoolean("isMyActivity")) {
yourMethod();
}
super.onResume();
}
You can use SharedPreferences to store the boolean or a public static boolean variable. I use TinyDB for many things. This works great.

Issue in using onStop() and onResume()

I am using onStop() to save a boolean value which I need when the activity resumes.
Here is my code:
#Override
protected void onStop()
{
super.onStop();
Bundle bundle = new Bundle();
bundle.putBoolean("value",value);
getIntent().putExtras(bundle);
}
#Override
protected void onResume()
{
super.onResume();
if(getIntent().getExtras() != null)
{
Bundle bundle = getIntent().getExtras();
value = bundle.getBoolean("value");
}
}
My issue is no matter what the value of the boolean is, my onResume() always retrieves it as FALSE. This issue only occurs if I leave my activity using the BACK button. If I press home, things seem to work fine(i.e if the boolean was TRUE then onResume() retrieves it as TRUE.
Please do help me because I don't understand why onResume() always gets the value of the boolean as FALSE even when I save it as TRUE in onStop().
I also tried onRestart(), onPause() and onBackPressed() but I still can't get the proper boolean value to be saved.
You have two issues here.
the correct way to save values during activity destruction is to use onSaveInstanceState(Bundle) and get the value from the Bundle passed to onCreate(Bundle).
Check example below:
public class SavedInstanceExample extends AppCompatActivity {
private boolean myBoolean;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_savded_instace_example);
if (savedInstanceState != null) {
myBoolean = savedInstanceState.getBoolean("key");
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putBoolean("key", myBoolean);
}
}
When you press the back button the activity will be finished. That means completely gone. And values saved one the methods explained above will not be there.
The way to save something to survive the Activity being finished is to save it to the disk. One common/simple way to do it is using the SharedPreferences
When the Android application opens the following activity lifecycle methods will be called.
onCreate();
onStart();
onResume();
and when you press the back button, the application will be destroyed by calling following methods
onPause();
onStop();
onDestroy();
And in the second case when you press home button the following methods will be called
onPause();
onStop();
That means your application is not destroyed completely and you can open it from recent apps so that the activity re-appears by calling
onStart();
onStop();
That is why your code works in this case.
Activity gives onSavedInstanceState() method to save your data during configuration changes or something else.
Here is the link for Android documentation for
Activity
I would suggest you to read the Google Developers Link for Activity documentation.Google Developers Activity
The OP's code is basically right. onSavedInstanceState is no good if you are not destroying the activity but, for example, replacing a fragment in an activity with another fragment and then returning to it, in which case you have to use onStop and onResume as follows. This is Kotlin and it works but the principle is the same.
override fun onStop() {
super.onStop()
val bundle = Bundle()
bundle.putBoolean("BOOL", false)
activity?.intent?.putExtras(bundle)
}
override fun onResume() {
super.onResume()
if (activity?.intent?.extras != null) {
val bundle = activity?.intent?.extras
val bool = bundle?.getBoolean("BOOL")
println("BOOL is $bool")
}
}
My Java's a bit rusty but I suspect the OP's problem might have been that he mixed up boolean and Boolean?

onResume() is not called in physical device instead onCreate() is called

Iam little bit amazed with this.I have an onResume() in my activity.Its called and works well in my emulator, but in a physical device samsung galaxy note for specific with jellybean installed,its not called.Instead onCreate() is called all the time.Why this happens?
public void onResume(){
super.onResume();
if(firsttime){
try {
Toast.makeText(getApplicationContext(), "Resuming Activity",Toast.LENGTH_LONG).show();
addReminder();
} catch(Exception exception) {
exception.printStackTrace();
}
} else {
firsttime=true;
}
}
This is my code.firsttime is a static boolean variable.It is used to prevent onResume() being called when app is started for the first time
Considering your current scenario, you should save variable in preferences instead of relying on activities lifecycle since lifecycle depends on many things.
Using static variable for this scenario is bad choice in general.I think this should solve your problem.
Try to print something inside the onResume and check it in LogCat.... the code inside onResume may be causing this.
or else can you elaborate your question?
I think here is what happens,
when your app not the Top app, the activity manager actually destroy the activity, it only called
public void onSaveInstanceState(Bundle savedInstanceState)
no
onStop
called, so no
noResume
will be called.
The correct to do this is, when put all states of this activity when
public void onSaveInstanceState(Bundle savedInstanceState)
called.
and in your onCreate() function, do such thing
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); // Always call the superclass first
// Check whether we're recreating a previously destroyed instance
if (savedInstanceState != null) {
// Restore value of members from saved state
mCurrentScore = savedInstanceState.getInt(STATE_SCORE);
mCurrentLevel = savedInstanceState.getInt(STATE_LEVEL);
} else {
// Probably initialize members with default values for a new instance
}
...
}
to check if you have some saved state.
Most code was copy from android developer site:
http://developer.android.com/training/basics/activity-lifecycle/recreating.html

Android onPause and onResume Method

Am trying to implementent onPause() and onResume(), such that when am out of the activity the the text in my text view is still there, but its displaying "null" when i start the the activity please assist!
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
etPassenger.setText(""+ gotPassenger );
etStaffNumber.setText("" + gotStaffNumber);
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
etPassenger.setText(""+ gotPassenger );
etStaffNumber.setText("" + gotStaffNumber);
}
I think gotPassenger and gotStaffNumber vars are null - if you want to save them than you have to use prefs or save them to some bundle to restore later.
When you are minimizing your activity your variables becoming null.
Add the following code in your activity,
#Override
public void onSaveInstanceState(Bundle savedInstanceState)
{
savedInstanceState.putString("gotPassenger",gotPassenger);
savedInstanceState.putString("gotStaffNumber",gotStaffNumber);
}
And, in your onCreate() method, add the following,
if(savedInstanceState!=null)
{
etPassenger.setText(savedInstanceState.getString("gotPassenger"));
etStaffNumber.setText(savedInstanceState.getString("gotStaffNumber"));
}
When you are leaving your activity, you will loose the data stored inside gotPassenger and gotStaffNumber.
If you want to reuse them after exiting your application, you have to use SharedPreferences to save them first and retrieve them when you are back.
If you want to save your data even when closing your app you need to use sharedPreferences. Here's how you use them

Why do OnCreate should be called only once on the start of Activity?

I would like to know, why OnCreate() is called only once at the start of an activity?
Can we call OnCreate() more than once in the same activity?
If yes, than how can we call it? can anyone give an example?
Thanks a lot!!!
Why would you want to called it again? unless the activity is reconstructed, which is called by system. You cannot call OnCreate manually , it is the same reason why you won't call setContentView() twice. as docs:
onCreate(Bundle) is where you initialize your activity. Most
importantly, here you will usually call setContentView(int) with a
layout resource defining your UI, and using findViewById(int) to
retrieve the widgets in that UI that you need to interact with
programmatically.
Once you finish init your widgets Why would you?
UPDATE
I take some words back, you CAN do this manually but I still don't understand why would this be called. Have you tried Fragments ?
Samplecode:
public class MainActivity extends Activity implements OnClickListener {
private Button btPost;
private Bundle state;
private int counter = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
state = savedInstanceState;
btPost = (Button) findViewById(R.id.btPost);
btPost.setOnClickListener(this);
Toast.makeText(getBaseContext(), " " + counter, Toast.LENGTH_LONG)
.show();
}
#Override
public void onClick(View v) {
counter++;
this.onCreate(state);
}
}
onCreate() method performs basic application startup logic that should happen only once for the entire life of the activity .
Once the onCreate() finishes execution, the system calls the onStart() and onResume() methods in quick succession.
The initialization process consumes lot of resources and to avoid this the activity once created is never completely destroyed but remains non visible to user in background so that once it is bring back to front , reinitialization doesn't happen .
Where you want to call onCreate manually.
Then just do this.
finish();
Intent intent = new Intent(Main.this, Main.class);
startActivity(intent);
finish() calls the current stuff.
And if you are doing somethong getExtra in this activity then do this,
#Override
protected void onSaveInstanceState(Bundle outState) {
outState.putString("key",your_variable);
super.onSaveInstanceState(outState);
}
And add this to your onCreate()
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
if(savedInstanceState != null)
{
your_variable= savedInstanceState.getString("key");
}
}
Why would you want to call onCreate more than once? You will be re-creating the activity. If this is what you need for whatever reason then finish the activity and use an intent to create a new instance of that activity. Otherwise, you have two instances of the activity at the same time. Hope that helps but if that doesn't make sense then add more information as to what you want so we have context
OnCreate is basically use to create your activity (UI). If you have already created your activity then you need not create it again as you have already created.
It is basically used to initialize your activity and to create user interface of your activity. Activity is a visual part which you can use again and again so.. I think your problem is not to recreate activity but to reinitialize all components of your activity. For that purpose you can create a method initialize_act() and call it from anywhere...
#OnCreate is only for initial creation, and thus should only be called once.
If you have any processing you wish to complete multiple times you should put it elsewhere, perhaps in the #OnResume method.
Recently i realized that onCreate is called on every screen orientation change (landscape/portrait). You should be aware of this while planning your initialization process.
Recreation can be suppressed in AndroidManifest.xml:
<activity
android:configChanges="keyboardHidden|orientation"
android:name=".testActivity"
android:label="#string/app_name"></activity>

Categories

Resources