0

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();
}
Lotse
  • 51
  • 8

1 Answers1

1

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!

Namnodorel
  • 385
  • 5
  • 17
  • You just need to put `activity = this;` somewhere in onCreate. I usually put it at the beginning of the class, because it makes sure getActivity() returns an object in any case. – Namnodorel Jun 11 '16 at 08:40
  • Cheers worked nicely! Ye I completely blanked out but you were right at first :S – Lotse Jun 11 '16 at 08:47
  • Oh ye one more thing, you see where I commented out performLogin. This method is also in the LoginActivity and I'm trying to use it in my Java class. How can I achieve this? – Lotse Jun 11 '16 at 08:49
  • If performLogin() is like here https://stackoverflow.com/questions/37696925/mobile-application-shared-preferences-saving-and-calling-user-login you can't because it's a private method and can't be accessed from anywhere outside the original class. You need to change the access level and then just use `MyActivity.getActivity().performLogin(username, password, ipAdress)` or move the method to your other class – Namnodorel Jun 11 '16 at 08:56