Android how to save the tab state when switching between tabs - android

I have TabActivity which holds 4 tabs.
the tabs created in the tabhost activity like this
TabSpec firstTabSpec = tabHost.newTabSpec("tid1");
Intent send_names_intent1 = new Intent(this,tab1.class);
//here is some data I receive it from previous activity
//and want to send them to the tab
send_names_intent1.putExtra("names", names);
send_names_intent1.putExtra("check", test1);
firstTabSpec.setIndicator("Kingdom I").setContent(send_names_intent1);
tabHost.addTab(firstTabSpec);
in every tab the user do some work and the result will displayed in the tab,
the problem is that when switching to the 2nd tab and then go back to the 1st tab all the results will gone and the tab will be created again.
NOTICE : I tried to use the getsharedprefrences() but it will loads the saved data even if the application closed and opens again.

You can use a boolean value boolean test; and int value int last=0 then use this method
tabHost.setOnTabChangedListener(new OnTabChangeListener(){
#Override
public void onTabChanged(String tabId) {
int currenttab = tabHost.getCurrentTab();
if (currenttab != last){
test[last] = false;
send_names_intent [last].putExtra("check", test[last]);
last = currenttab;
}
}
});
when you use this method you will have a boolean value in your tab1.class
Intent names_intent = getIntent();
prefcheck = names_intent.getBooleanExtra("check", false);
then check the prefcheck value if (prefcheck == false) save the SharedPreferences.

Have you tried onSaveInstanceState?
protected void onSaveInstanceState(Bundle icicle) {
super.onSaveInstanceState(outState);
icicle.putString("names", names);
}

You say you used shared preferences right? Why not have it so that when a tab is opened, it increments a value of a shared preference by one, and om destroy decrements it, and then checks to see if the value is 0, if so it deletes all the save preferences you want by setting them to the default value, or the value you want.

Related

Android keep selected fragment state / loaded url after orientation change,

I am new to fragments and have a lot of problems understanding and working with them. I will try to describe my problem step by step:
I start with a list
after selecting an item i start an activity with a dynamic url in a webview
If portrait, only the webview is showed, if landscape the list is presented next to it
In landscape when i select another item, it is showd in the webview (check the code)
Problem: When i turn back now to portrait the first selected item is showd instead of the last one.
How can i update the activity so it will keep the last opened url after orientation change?
if (fragment==null || ! fragment.isInLayout()) {
Intent intent = new Intent(this.getActivity(), DetailViewActivity.class);
intent.putExtra("link", urlforwebview);
startActivity(intent);
} else {
DetailView detailFragment =
(DetailView)
getFragmentManager().findFragmentById(R.id.detailfragment);
detailFragment.changeWebviewURL(urlforwebview);
}
FIX:
Added this to my detailfragment:
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString("currentUrl", url);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (savedInstanceState != null) {
// Restore last state for checked position.
url = savedInstanceState.getString("currentUrl", "");
changeWebviewURL(url);
}
}
Have a look at : onSaveInstanceState.
http://developer.android.com/reference/android/app/Activity.html#onSaveInstanceState(android.os.Bundle)
This answer here can help you: android fragment- How to save states of views in a fragment when another fragment is pushed on top of it

android tab activity go to previous tab

I have an activity with five tabs. Everything looks okay when I go from tab 1 to tab 2 or tab 3. How can I go back programatically from tab 2 to tab 1?
Intent myIntent = new Intent(this, Tab1.class);
myIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(myIntent);
This is not working properly because it starts activity 1 without any tab.
When going from tab 1 to tab 2 I can both see tab 1 and tab 2 (current tab activated). But when going from tab 2 to tab 1, both tab 1 and tab 2 disappear from the activity. What could cause this?
This will surely help you.
TabHost tabHost = (TabHost) getParent().findViewById(android.R.id.tabhost);
tabHost.setCurrentTab(1);
OR you can refer to this link
How to programmatically switch tabs using buttonclick in Android
Thanks :)
just use finish() method
public void onClick(View v)
{
finish();
startActivity(new Intent(Activity2.this, Activity1.class));
}
I don't know about the Intent.FLAG_ACTIVITY_CLEAR_TOP, never needed that, but the mentioned effect of loosing your tabs is produced by calling startActivity() from your TabHost, not one of your tabs. If that's the case, move the call there and your tabs should stay.
I have a similar situation but seems none of the answers help. so, I post my solution here:
// tab selection history, each tab has a tag which is a string
private List<String> tabIdHistory = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstance) {
super.onCreate(savedInstanceState);
// this layout contains TabHost and TabWidget
setContentView(R.layout.activity_main);
TabHost tabHost = (TabHost) findViewById(android.R.id.tabhost);
tabHost.setup();
tabHost.setOnTabChangedListener(new TabHost.OnTabChangeListener() {
#Override
public void onTabChanged(String tabId) {
tabIdHistory.remove(tabId); // ensure uniqueness
tabIdHistory.add(tabId);
}
});
// continue your tab initialisation, such as
// tabHost.addTab(tabHost.newTabSpec(TAG)
// .setContent(...).setIndicator(...));
}
#Override
public void onBackPressed() {
if (tabIdHistory.size() > 1) {
// pop the current last item, we want the second last
tabIdHistory.remove(tabIdHistory.size() - 1);
tabHost.setCurrentTabByTag(tabIdHistory.get(tabIdHistory.size() - 1));
} else {
super.onBackPressed();
}
}
If use select tab#1, tab#3, tab#2, tab#1, then the back stack is "3, 2, 1" and app will exit to main screen if user press back button three times. If you want to keep full history, comment out this line:
tabIdHistory.remove(tabId);

How to identify Tabhost tabs ID from another activity

i have tabs in a TabActivity that is being populated by a listview from a method in another Activity. when i click on the listview in the tab, i am trying to delete an item in the listview from onContextItemSelected and let the tab in the tabhost callback the same method in the Activity that populated the listview. please does anyone know how i can identify the tab where the action was performed from the Activity that has the listview method?
There seems to be know method like setTag() on the tabs in other to identify them. i tried this which works if i am in the TabActivity class but if i am in the other Activity, i want it to call fillAllData(). but am getting a warning from eclipse that the line is a dead code and its calling fillShopData() instead. Any ideas on how to go around this?.. i hope i have made myself clear. Thanks.
/* code in activity class after delete is pressed in onContextItemSelected*/
if( Categories.SHOP_TAB_TAG == 1) { // tab in categories TabActivity identified as int
fillShopData(); // fill this data back in tab
}else {
fillAllData(); // Dead Code from Activity
}
You can have a static variable in the Constants class which will keep the track of the Tab selected which you'll modify in the OnTabChangedListener like:
#Override
public void onTabChanged(String tabId) {
if (tabId.equalsIgnoreCase("Assigned")) {
Constants .LIST_ACTIVITY = 0;
} else if (tabId.equalsIgnoreCase("Accepted")){
Constants .LIST_ACTIVITY = 1;
}else if (tabId.equalsIgnoreCase("Rejected")){
Constants .LIST_ACTIVITY = 2;
}else if (tabId.equalsIgnoreCase("Completed")){
Constants .LIST_ACTIVITY = 3;
}
}
where tabId is the one you give while creating the tabs.
Since this is a static variable you can access it in any of the classes as a flag.

Edittext and Tab Issue

In my application, I'm creating dynamic tabs.Inside framelayout I've created a edittext.For
each tab i create content of tab will be edittext. When i type in editext of one tab and later if i create a new tab and when I switch between these tabs, it shows the content of editext as empty.
Update:
I don't want to create a separate activity for each tab.I'l explain along with the code.
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final TabHost tabs = (TabHost)this.findViewById(R.id.tabs);
tabs.setup();
TabHost.TabSpec spec1=tabs.newTabSpec(f);
spec1.setContent(R.id.content1);
spec1.setIndicator(f);
tabs.addTab(spec1);
tabs.setCurrentTab(i);
list.add(spec1);
i++;
Addbtn.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View arg0)
{
final TabHost tabs = (TabHost)this.findViewById(R.id.tabs);
tabs.setup();
TabHost.TabSpec spec1=tabs.newTabSpec(f);
spec1.setContent(R.id.content1);
spec1.setIndicator(f);
tabs.addTab(spec1);
tabs.setCurrentTab(i);
list.add(spec1);
i++;
});
Default one tab will be there. here content of tab is edittext. When i click on button new tab will be created. problem is with the content of tab. In default tab if i type in edittext, and create a new tab and switch to the default tab the content of default would be lost.
You need to store the value of the EditText in some manner. A good way is to show tab content through an activity and use this method to store instance state.
You can use an EditorActionListener, which is called when someone presses the 'Enter' or IME_ACTION key to store the values of your EditText.
Instead of doing spec1.setContent(R.id.content1);, create an EditText dynamically (new EditText(context)) and put a number (Tab Number) as a Tag, which you can retrieve and store in a List.
mEditText.setOnEditorActionListener(new OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int actionId,
KeyEvent event) {
int position = (int) v.getTag();
String s = ((EditText) v).getText()
// store in an object
return false;
}
});
Not sure how you will retrieve this without launching subActivities!

Get index of selected tab in tabHost

I'm trying to store the index of the currently selected tab in onSaveInstanceState so I can restore it. However the getCurrentTab apparantely gives me back the String I used in the etTabHost().newTabSpec, which I find a bit weird since the documentation says it returns an int and setCurrentTab also taking an int.
Does anyone know how I can get the index of my currently selected tab so I can restore it?
you are on the right way, use setOnTabChangedListener to get your selected tab.
public class MainActivity extends TabActivity {
static TabHost mytabs;
mytabs = getTabHost();
mytabs.setOnTabChangedListener(new OnTabChangeListener() {
#Override
public void onTabChanged(String arg0) {
Log.i("***Selected Tab", "Im currently in tab with index::" + mytabs.getCurrentTab());
}
});
...
...
...
You can use getCurrentTab() that returns index of tab start from 0.
Use tabHost.getCurrentTab() to get Tab ...
tabHost= getTabHost();
tabHost.addTab(tab0); // TabSpec tab0=tabHost.newTabSpec(...
tabHost.addTab(tab1); // TabSpec tab1=tabHost.newTabSpec
int current = tabHost.getTabHost() ;

Categories

Resources