I have a ViewPager with a FragmentStatePagerAdapter and the starting page should be somewhere in the middle. But when the user goes to another Activity and then comes back, the page number should be saved, so that he returns to the same page. There is probably an easy way to get this done, but I can't find the solution.
Usually the current page number will be saved, so this is not the point. The problem is that I don't know where to put the code that sets the starting page at first, because when I put it in onCreate, the starting page will be shown even if I come back from a different Activity.
I also tried saving the number in a variable in the onPause method:
this.currentPageNumber = viewPager.getCurrentItem();
But next time when onStart() is called, the variable currentPageNumber is null, so it seems that variables are not saved after onDestroy().
I could use a static variable, but it feels wrong. Is there a better solution?
EDIT: Sorry, I didn't make clear enough, that I want the saved page only be opened, if I come back to this Activity after I launched it. Every time I start the Activity from the launcher, the starting page should be shown and not the saved page.
EDIT 2: The behaviour I want to have is exactly the same as the Google Calendar app has when you open the day or week perspective. If I open this app, the current day will be shown. If I swipe to another day, then open settings, then press back, this other day is still be shown. But if I restart the app, again today will be shown.
After you have initialised your viewpager, use this method :
viewPager.setCurrentItem(int position)
Or this :
viewPager.setCurrentItem(int position, boolean withAnimation)
You can save the last position by using SharedPreference in the onPageSelect() method where you can get the position of each page. You have to implement the OnPageChangeListner in order to have this method.
Edit
Your question wasn't clear :
Sorry, maybe I didn't express my problem well enough. I want the starting page to appear everytime I start my app. But if I enter the activity by the back-button (for example if I opened my settings activity and then go back) the last viewed page should be shown. The solution provided in the link will lead to the safed page everytime I open the app
I don't know why you want to change this, it's a normal behavior, read this.
But if you insist, you can always use setCurrentItem() method in the onResume of your Activity/Fragment, thus the first page will always be shown after your Activity/Fragment gets resumed.
Edit 2
That can still be done by setCurrentItem. In your adapter, try to detect the index of the page of the current day. Create a method that returns that field from outside the adapter. And then after you have initialised your ViewPager,
viewpager = (ViewPager) findViewById(R.id.viewpager);
viewpager.setAdapter(adapter);
setCurrentItem(adapter.getCurrentDayPosition()) // or something like that ...
The method in the adapter :
public int getCurrentDayPosition() {
return this.currentDayPosition // this a field of the adapter.
}
I have the same requirement to show the default page whenever the onCreate of the ViewPager hosting Activity is called and show the current page for all the other cases including the motivating case: when user navigate back from the Activity started from the current page (onCreate won't be called in this case). My solution is based on the time spend between onCreate and onResume.
If the time between onCreate and onResume is shorter then a threshold (I use 1s assuming onCreate could be finished within 1s which we really wanted for the good programming practice), then we believe this is the first time the onStart/onResume is called right after the onCreate, otherwise we believe it is about all the other cases including our motivating case.
Then we only need to set the current timestamp in onCreate and do the time comparison in onResume to make the decision to set the current item of ViewPager to default or current. Note that we need to save the current page number in onPause in SharedPreference.
I am not claiming this idea is perfect but it works fine for me so far. Let me know if you are interested in the implementation and I will post my code upon your request.
i think this solve your problem , because first time you launch your activity there is no instance saved (savedInstanceState) ...
read comments in the post ...Android :Save View Pager State ...
Related
I am calling a Master/Detail activity in android by clicking on a button placed in another activity (UserActivity). The strange thing is, that if i click the back button in the Master/Detail activity, I loose the Data in the state of the UserActivity. It wants to execute the onCreate Method again.
If I click on the login-button in the LoginActivity where i am redirected to the UserActivitiy and i go back with the Back-Button of the "Smartphone", the username and password i typed are still there. So there i do not loose the data.
Is there a difference between the back-button of the Smartphone and the back-button at the top of the program? I am a bit confused now and i know how to persist the state of the Activity. But my question is, why i am having this behavior on the one side and on the other not.
Just in case you will leave the question like this and don't add code:
What will probably help is checking for the amount of items that are already there. When I ran into this issue, the onStart() got called so quickly that it seemed to me that the Activity has lost the data. Actually it DID have the data, but calling onCreate/onStart (I'm in a Fragment) NULLed it.
What I did to avoid this is to check if there is a need to load items in the list. If there is, it calls a method that contains what the old onCreate/onStart did. If there is no need to load data, it will just skip the step and live with the "old" data happily for the rest of its life.
#Override
public void onStart() {
super.onStart();
if(DummyContent.ITEMS.size()<3){
initializeApp();
}
}
void initializeApp(){
videoTitles=new ArrayList<String>();
videoUrls=new ArrayList<String>();
. . .
}
I would like to check if a fragment was created for the first time so that I can launch a different fragment for introduction before coming to the retained fragment.
Normally for an activity I know I would use a sharedPreference-object to store a boolean value that tells me if this is the first time the user opens the activity, check the preference when the user starts the application, and if it returns true then show the middle screen.
Is the same possible for fragments?
Yes, you can use sharedPrference, but maybe it will be better to check the state when you actually switch to this fragment.
I mean you can decide in activity if to show introduction fragment or regular one before you create the fragment.
I have an activity, DogActivity, with a slider. When the user slides view PawsView to a certain degree, I start another activity, CatActivity, using startActivity(intent). If the user clicks the back button, normally the user returns to DogActivity. Here is my problem: if in Developer options I set Do not keep activities then when the user clicks the back button and thus returns to DogActivity, the slider is not asserted and so PawsView is back to its original position; however, if I don't have that option selected, upon returning to DogActivity the slider is still asserted (the sliding already occurred).
Since I don't want to depend on the user selecting or deselecting Do not keep activities, I need to do this programmatically. So does anyone know how to do this? I have tried putting the appropriate code inside onResume but that has no effect. It's as if finishing CatActivity has no effect on DogActivity. BTW, the view I am using to display PawsView is a custom view.
I already tried using a handler with postDelayed to pull PawsView back to normal, but the handler always executes before the startActivity is executed. If on the other hand I start a proper Thread to run the call to close the slider, I get an error about the wrong thread trying to change the layout.
Another way of asking the question may be: How do I force onResume to be called even when Do not keep activities is NOT selected on a user's device.
You could try to launch CatActivity using startActivityForResult and then handle the result in onActivityResult and do the necessary setup from there. It's sort of like forcing onResume.
I'm a very new to Java. I thought I was doing okay but have now hit a brick wall, so to speak.
The idea is I use the 'home button' '_menu' for the user to choose one of 26 formats. The format they choose has 3 variables. Those 3 variables are then used in the first xml view, along with 2 user inputs to calulate another variable. This variable is then used in a second xml view, along with a third user input here, to calculate the final answer.
I have created the 26 choices and if for example I choose option 5, on the emulator screen I see all the correct values associated with this choice. I don't think those values are getting stored anywhere. I say this because if I come out of that view and return back into it, it's not showing, as in my example, choice 5. It's showing its initial state, as though I was going into it the first time. I assume it's something to do with launching this activity from the start but is there anyway around this. Or really where do I start.
My second question is with the integer variables that I created from this choice. I need to pass them into another java file for the first set of calculations. I've tried to pass the variables/data with the, 'new intent putExtra' but can't get it to work. But I don't think I can use this anyway since the I don't want to launch the second view directly from the res/menu/ .xml view.
Not sure if this is making sense to anyone. Can someone help point me in the right direction?
I don't quite understand your first question, but it sounds like you're launching a new activity and when you quit and come back to it, everything is reset. If you're launching a new activity after selecting the options from your phone's menu button, you should implement a method that saves data to the shared preferences of the main activity. This method should be called on the activities onPause(), onDestroyed(), or onStop() method. You can also add a method on onResume() where the activity checks if there's any data stored in shared preferences and if so, make the desired changes.
As for your second question...I kinda don't understand it either. new intent and putextra is used when you're starting a new activity and want to pass data to it. Views are not "launched" they are only inflated and brought on display whenever you want. I did an app once where I had everything in one activity and just using setContentView() method all the time. In the long run, it just complicated everything. It is easier to keep things simple and launch activities. Here is an example of some variables being passed to a new activity:
On my main activity (FirstActivity) I have:
(when newActivityButton is clicked)
case R.id.newActivityButton:
Intent mIntent = new Intent(FirstActivity.this,SecondActivity.class);
String[] luckyNumbers = {
luckyNumber[0].getText().toString(),
luckyNumber[1].getText().toString(),
luckyNumber[2].getText().toString(),
luckyNumber[3].getText().toString(),
luckyNumber[4].getText().toString(),
luckyNumber[5].getText().toString()};
mIntent.putExtra("luckyNumbers", luckyNumbers);
mIntent.putExtra("message", messageField.getText().toString());
FirstActivity.this.startActivity(mIntent);
break;
luckyNumbers[] is an array of textviews.
Then on my NewActivity onCreate(), I have:
message = getIntent().getExtras().getString("message");
Log.i("TAG", message);
luckyNumbers = getIntent().getExtras().getStringArray("luckyNumbers");
cv.setLuckyNumbers(this.luckyNumbers);
cv.setMessage(this.message);
where cv is just a custom view I created with its own methods
In my project I have three tabs. I want to know, each time that I click a tab onCreate function runs or it runs just one time when it creates.
Actually, in one tab I want to show a picture. for the first time, default picture is shown. However, if user creates his picture (in other tabs), when he clicks this tab the new picture should be shown.
My problem is, only default picture is shown and it doesn't show new picture. I think onCreate method don't run each time that I click the tab. Am I right?
hi friend it depends up on whether the activity is still active or not, if the activity is in paused mode then only the onResume() method will be called, if the activity is destroyed then the onCreate() method will be called,
my suggestions is that if u want to write any code u can use onResume()
or else
u can explicitly kill previous activities using finish method of activity. to make sure that every time onCreate() method is invoked..
u can call this finish() in the tab class u have written for tabs before switching to other tabs
I had the same problem. Copied the same code in onResume() method & it worked as expected.