开发者

Android SharedPreference - TabHost issue

I'm working on Android application which have two different tabhost : Main and Child. In Main tabhost I have 5 different tabs and the last one opens new activity where I have login page.I want to create a boolean type isLoggedIn in login activity and pass true or false to the Main Tab bar,because I want to change the number of tabs.If user is logged in I'll have 5, if not I'll have 4 tabs.So any suggestions how to code this problem?

Update :

For now I'm using this code.In user LogIn.class I use :

SharedPreferences isLogged = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
        SharedPreferences.Editor editor = isLogged.edit();
        editor.putBoolean("isLoggedIn", isLoggedIn);
开发者_开发问答        editor.commit();

in MainActivity i use almost the same code :

SharedPreferences isLogged = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
        SharedPreferences.Editor editor = isLogged.edit();
        editor.putBoolean("isLoggedIn", false);
        editor.commit();

And I check for two states like this :

if(editor.putBoolean("isLoggedIn", false) != null){
// show 5 tabs
}else
{
// show 4 tabs;

But when I open my application I get 5 tabs, even before check the status of user. Any idea how to fix that? }


you check for the value in shared preferences with

editor.getBoolean("isLoggedIn", false)

not with putBoolean, and you don't have to put a null against it, if the name "isLoggedIn" is not present in shared preference, it will return false, that is what the second argument is for , to return a default value if it can't find the name. as i understand you need the following code.

if(editor.getBoolean("isLoggedIn", false)){
// show 5 tabs
}else
{
// show 4 tabs;

This code will check for "isLoggedIn" value , and will show 5 tabs if the value is true and 4 if the logged in is false.

As for the another problem, you are updating the value with false in the main activity, don't do that, do that only after the user logs out. so remove the following 2 lines from your code.

editor.putBoolean("isLoggedIn", false);
        editor.commit();


Use sharedPreference, which is common to whole application.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜