How can we clear All the Data of Previous Activity in Android - android

I just want to Clear all the data of Previous Activity. Means when i will go back to previous activity it need to call all the asyncatsk again as a fresh new activity.
Because when i was goes in a next activity i was doing some changes in data sequence but i will come back i need to call agin asynctask for original data
So anyone have idea about it ??
and yes i just want to clarify that Below's Function is not working
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

There are a couple options depending on your situation.
First, you could try clearing your savedInstanceState like this:
public void onCreate(Bundle savedInstanceState){
super.onCreate(null);
}
Or like this:
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.clear();
}
Second, if you're hoping to have this specifically on the "backpressed" event,
you could override onBackPressed to create a new instance of your activity, rather than the default of returning to the activity with its saved state.
#Override
public void onBackPressed(){
//super.onBackPressed(); // EXCLUDE this line
Intent intent = new Intent(this,TheNextActivity.class);
startActivity(intent);
}
#iguarna 's answer is also something to try, it all depends on the situation and what you're hoping to accomplish

If you want to re-initialize your activity in any way when you come back to it, just reset the values you want in onResume().
If that is not what you were looking for, please clarify your question.

Related

How do I save state of activities instead of always having onCreate called in Android?

I would like my application to save state after it already has loaded once. For example in one of my activities I have a ListView. If the user scrolls it, and than switches activities, I wish for them to go back to the ListView activity and have the same scrolling position. I noticed that pressing the back button goes back to a saved version of the state. This is the exact kind of save I want (where it saves the state of the previous activity). Except I want to do this from anywhere in the application, not just when the back button is pressed... Please help me.
You have to override onSaveInstanceState(Bundle savedInstanceState) and store the values you want to save in Bundle object as name value pair.
#Override public void onSaveInstanceState(Bundle savedInstanceState)
{
super.onSaveInstanceState(savedInstanceState);
savedInstanceState.putBoolean("position", 12);
savedInstanceState.putString("Name", "John");
}
also you have to override onRestoreInstanceState() where you'd extract the values:
#Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
boolean myPosition=savedInstanceState.getBoolean("position");
String name= savedInstanceState.getString("Name");
}
see this link for help LINK
It can be done with the saveInstanceState() and onRestoreInstanceState() methods. The first one called near onPause(), the second called before onResume(). To save the state of a view, call onSaveInstanceState() from view.
For example, listview.onSaveInstnceState();
Here's a detailed article
https://futurestud.io/blog/how-to-save-and-restore-the-scroll-position-and-state-of-a-android-listview

confused about android example code

I'm looking over some code on the android developer's site and have a quick question about the example show here - http://developer.android.com/guide/components/fragments.html
In particular, I'm looking at this piece of code -
public static class DetailsActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getResources().getConfiguration().orientation
== Configuration.ORIENTATION_LANDSCAPE) {
// If the screen is now in landscape mode, we can show the
// dialog in-line with the list so we don't need this activity.
finish();
return;
}
if (savedInstanceState == null) {
// During initial setup, plug in the details fragment.
DetailsFragment details = new DetailsFragment();
details.setArguments(getIntent().getExtras());
getFragmentManager().beginTransaction().add(android.R.id.content, details).commit();
}
}
What is the point of the second if statement -
if (savedInstanceState == null) {
I can't find any situation where this if statement wouldn't be true. I've tested this code by adding an else statement and setting a breakpoint in it. I could not get to that breakpoint no matter I tried. So why even bother with an if statement? Why not leave it out all together?
There are situations in which your Activity is stopped by the Android operating system. In those cases, you get a chance to save the state of your Activity by a call to [onSaveInstanceState](http://developer.android.com/reference/android/app/Activity.html#onSaveInstanceState(android.os.Bundle). If after this, your Activity is started again, it'll be passed the Bundle you created so that you can restore the state properly.
You have to look at the complete example code. With this part it makes sense.
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("curChoice", mCurCheckPosition);
}
If you start your Activity the first time the Bundle savedInstanceState will be null and the body of the if statement will be executed. If onSaveInstanceState is called, because you navigated away from the Activity, the Bundle isn't null anymore and the if body will be not executed.
If your app was paused/killed, etc and you saved state by onSaveInstanceState then
savedInstanceState will contain the state of your app that you saved. Otherwise it will be null.
Apparently this was added to the example for future expansion on this code. While it has absolutely no functionality as it stands right now, if this activity were to launch another activity and get killed while the new activity had focus, this code would rebuild the activity when the user hits the back button, rather than rebuilding from scratch.

surfaceview, activity, startactivityforresult, dialog in activity

Im working on a little game and having some issues.
There is the Menu
public void onClick(View arg0) {
// TODO Auto-generated method stub
switch (arg0.getId()){
case R.id.bStartGame:
Intent a = new Intent(Menu.this, Action.class);
startActivityForResult(a, 1);
break; }
then the activity which starts a surfaceview
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(new GameView(this));
}
and then the the surfaceView with the game mechanics.
Most of my code is in this view.
Now I have the problem to find a good solution for the gameoverscreen.
If I start a new activity inside the surfaceview, it works - but i dont get the result() which is the score achieved during a session.
So now I wanted to ask you guys how to solve this issue.
I thought of a way, but dont know how to implement it.
It would be to pass the highscore from the surfaceview to the activity and set it as a result(which the menu activity gets back) there.
And start an xml file via dialog, which would be the gameoverscreen and as soon as the player touches the back button he gets back to the menu where he can see his achieved score.
Can you please tell me how to code this?
Kind regards
Denis
There's a number of ways to solve this:
-use startActivityForResult and then send it back from your new activity, catching it in the old activity using onActivityResult (check https://developer.android.com/reference/android/app/Activity.html)
-do what i did (the lazy, hacky way :): start the new activity with startActivity() and add the highscore as extra data added to the intent. In your new activity, use getIntent().getInt (ow whatever) to get the sent score data and do with it what you will. Then close that activity and you'll return to the previous one holding your surfaceview.
NOW THE TRICK: before you start your new activity with it's score added to the intent, just run the same score calculation in your surfaceview's activity as you would in your new activity! That way, when you return to your surfaceview's activity, you will still have the correct, new score (if stored/onresume'd correctly; don't forget to add it to your save/restore state and/oror the surfaceview's private variables)!
The only downside is that you'll have two location you have to update your scoring mechanics at. And it's not good programming. But it works and it's easy.

onCreate not called

I have 2 Activities : First activity user clicks on a button which launches the 2nd activity. The 2nd Activity does all the work.
I launch the 2nd Activity as follows which is inside a onClickListener Inner Class and I have tried explicitly calling it with (FirstActivity.this,Simple.Class) but same thing happens.
Intent test = new Intent(arg0.getContext(),Simple.class);
startActivity(test);
On the emulator, I see the screen move over like its calling the 2nd activity but all I get is a black screen but nothing is loaded from my layout. I looked at logcat and I do see some binder thread failed messages. This is the onCreate function from my 2nd activity but I do not get any results from either the screen or logcat showing me that the Log functions were called:
public void onCreate(Bundle savedState)
{
Log.d("SimpleActivity","OnCreate Started");
super.onCreate(savedState);
setContentView(R.layout.simple);
Log.d("SimpleActivity","OnCreate Ended");
}
Note : I have called the base constructor in OnCreate() with super.onCreate(savedState) in my code above.
What happened to me was I was overriding the wrong onCreate method. I was overriding public void onCreate(Bundle savedInstanceState, PersistableBundle persistentState) when I really needed to override protected void onCreate(#Nullable Bundle savedInstanceState). Maybe this might help someone!
It's possible that onCreate doesn't get called, if the activity has never been destroyed,
if for some reason an activity hangs around, next time its instantiated it is not recreated but resumed instead...
At least that's what im Dealing with right now in my code... Life cycle of Activities seem a good logical explanation.. However 99% of time I do rely on onCreate being called when startingActivity and it doesn't fail me....
Edit: And of course its because I wasn't calling finish() when exiting the activity. Doh.
This is not related to this certain issue, but also this can happen when activity is not declared in manifest file)
Be careful that if your method belongs to AppCompatActivity or Activity .
It is up to what you implemented to your Class
If you want to add lifecycle or any override methods, I recommend you to press
CTRL+O or do Code > Override methodsand there you can see where the method belongs
remove android:launchMode="singleTask" from manifest
you should #Override onCreate and add super.onCreate() in it
#Override
public void onCreate(Bundle savedState)
{
super.onCreate(savedState);
Log.d("SimpleActivity","OnCreate Started");
setContentView(R.layout.simple);
Log.d("SimpleActivity","OnCreate Ended");
}
my case
(1) mainActivity -> (2) open Adaptor - startActivity -> (3) mainActivity onCreate() doesn't get to triggered.
I resolved this by adding finish();. in mainActivity.
follow the below steps to check your application.
1.did you override the right method? if not overriding the below method, this method will be triggered, when you startActivity.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
2.Make sure that you registered the activity in manifest.xml
2.1 is your activity has android:launchMode="singleInstance" ?
(if your application doesn't need to be singleinstance, consider to remove.
but my case I need singleinstance. hence i moved to the next step)
use finish()
public void openSearch(View view) {
Intent intent = new Intent(this, BookInfoActivity.class);
intent.putExtra(...);
startActivity(intent);
finish(); // add like this.}
why do we need to use "finish()"?
Screen A -> click button on A -> Screen B -> click button on B -> screen A with some new data that you get from Screen B
if you don't call finish() method(in A button) , that means the A is still in your background
even you are seeing the screen B.
hence, when you trigger startActivity on screen B, it just simply shows the running A screen.
however if you use finish() method (in A button), when you go to B Screen,
it destroys the A screen, so when you go back to A screen by clicking B method( 'StartActivity') it creates A screen and trigger onCreate() Method .
You need to call the super.onCreate(savedState) method. Take a look at Activity doc.
public void onCreate(Bundle savedState)
{
super.onCreate(savedState);
}

Kill and destroy activity

The first screen of my application is a login screen, so I used the method finish () after user have logged. However when i return the application I would like to be already logged. I tried to use onDestroy (), but without success.
It'll be better if you implement your logic otherwise. The first screen in your application can be HomeScreenActivity in which you'll check if the user is logged and start LoginActivity if needed.
public class HomeScreenActivity extends Activity {
/* some declaration */
public void onCreate(Bundle savedInstanceState) {
/* some other stuff */
if (!userIsLogged()) {
Intent intent = new Intent(this,LoginActivity.class);
startActivity(intent);
}
}
}
You have to use SharedPreferences.
See Data Storage on Android Developer
You might want to have a look at the Activity Life Cycle... Furthermore SharedPreferences can be used to save username/login details but im of the understanding that they can be accessed by any application, so be careful what you put there.

Categories

Resources