how to check the SharedPreferences string is empty or null *android

后端 未结 4 432
广开言路
广开言路 2020-12-10 05:11

I want to check a string in SharedPreferences used it to store username and password, so if username and password is not null or empty it will be directed to home, otherwise

相关标签:
4条回答
  • 2020-12-10 05:43
     if(appSettings.contains(Constants.WEATHER_SUBN_POSTION)) {
            savedSubPostion = appSettings.getInt(Constants.WEATHER_SUBN_POSTION, 0);
     }
    

    First check it contains the value.

    0 讨论(0)
  • 2020-12-10 05:49
    public static final String DEFAULT_VALUE = "default";
    public static final String ANY_FIELD = "any_field";
    
    SharedPreferences prefs = context.getPreferences(Activity.MODE_PRIVATE);
    String text = prefs.getString(ANY_FIELD, DEFAULT_VALUE);
    if (text.equals(DEFAULT_VALUE)) {
        //TODO:
    } else {
        //TODO:
    }
    

    Good luck!

    0 讨论(0)
  • 2020-12-10 05:55

    Do this:

    SharedPreferences myPrefs = this.getSharedPreferences("myPrefs", MODE_WORLD_READABLE);
    String username = myPrefs.getString("USERNAME",null);
    String password = myPrefs.getString("PASSWORD",null);
    

    if username and password are present, they will have a value otherwise they will be null.

    if (username != null && password != null )
    {
        //username and password are present, do your stuff
    }
    

    You don't have to check their presence separately. Trying to retrieve their value will return null ( if not present ) or the value ( if present ) automatically.

    0 讨论(0)
  • 2020-12-10 06:06

    Try this

      if(PreferenceConnector.getString("USERNAME")!=null){   
          Intent intent = new 
          Intent(MainActivity.this,MainHome_Activity.class);
          startActivity(intent);
       }
       else 
       {
         Intent intent = new Intent(MainActivity.this,LoginFormPegawai_Activity.class);
         startActivity(intent);
       }
    
    0 讨论(0)
提交回复
热议问题