Search code examples
variablesandroid-studioandroid-activitysharedpreferencesmobile-application

Shared Preference Method Call From Activity to Java Class


So I'm currently having an issue with the context inside SharedPreferences where it says LoginActivity.this. This is my device.java class and LoginActivity is the Activity I want to call this method from. So would it be like Device.This or something along those lines?

Methods:

public void validateLogin(String username, String password, String ipAddress) {

    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(LoginActivity.this);

    if (sharedPreferences.contains("ip") && sharedPreferences.contains("username") && sharedPreferences.contains("password")) {
        String strUsername = sharedPreferences.getString("username", username);
        String strPassword = sharedPreferences.getString("password", password);
        String strIpAddress = sharedPreferences.getString("ip", ipAddress);
        //performLogin(strUsername, strPassword, strIpAddress);
    }
}

public void saveSP(String username, String password, String ipAddress) {

    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(LoginActivity.this);

    sharedPreferences.edit()
            .putString("ip", ipAddress)
            .putString("username", username)
            .putString("password", password)
            .commit();
}

Solution

  • Try this:

    public class MyActivity extends Activity{
    
        private static MyActivity activity;
    
        @Override
        protected void onCreate(Bundle savedInstanceState){
            super.onCreate(savedInstanceState);
    
            activity = this;
    
            //...
        }
    
        public static MyActivity getActivity(){
            return activity;
        }
    
    }
    

    And then when you need the context object:

    PreferenceManager.getDefaultSharedPreferences(MyActivity.getActivity());
    

    That's my usual approach when I need a context object outside of the Activity class. Hope it helps!