Lotse Lotse - 4 months ago 12
Android Question

Creating and Moving Shared Preference Method from Activity to Java

I'm still fairly new with Android Studio and I want to make my Shared Preference a Method in my Device.java class so it validates correctly. However, I'm not sure what variables should I initialise and the code placement. What my share preference code does is validates that the user is the same user and performsLogin to bypass the login screen i.e. first time requires login, life time bypasses to welcome screen.

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);
}


Java Class:

public static void login(String username, String password, String ipAddress, final Callback callback) throws JSONException {

OkHttpClient client = new OkHttpClient();

JSONObject jsonObject = new JSONObject();
jsonObject.put("username", username);
jsonObject.put("password", password);

RequestBody body = RequestBody.create(MediaType.parse("application/json"), jsonObject.toString());
Request request = new Request.Builder()
.url("http://"+ipAddress+"/api/v0/login")
.post(body)
.build();

client.newCall(request).enqueue(new com.squareup.okhttp.Callback() {


// produces exception if db connection request has fail
@Override
public void onFailure(Request request, IOException e) {
callback.onLoginFailure(e);
}

// checks is db request passed or fail
@Override public void onResponse(Response response){
if (!response.isSuccessful()) {
callback.onLoginFailure(new IOException("Unexpected code " + response));
return;
}

String jsonAsString = null;

try {
jsonAsString = response.body().string();

JSONObject json = new JSONObject(jsonAsString);

if (json.getString("status").equals("ok")){

Device device = new Device();
device.locationID = json.getInt("location_id");
//device.imageID = json.getInt("imageId");
// device.imageName = json.getString("imageName");

device.id = json.getInt("id");

Device.instance = device;

callback.onLoginSuccess(device);
} else {
throw new JSONException("Invalid service response");
}

} catch (Exception e) {
e.printStackTrace();
callback.onLoginFailure(e);
}
}
});

}

Answer

In your Device.java you can add something like this:

public class Device {
    private final SharedPreferences preferences;

    public Device(Context context) {
        preferences = PreferenceManager.getDefaultSharedPreferences(context);
    }

    public void validateLogin(String username, String password, String ipAdress) {        
        if (preferences.contains("ip") && preferences.contains("username") && preferences.contains("password")) {
            String strUsername = preferences.getString("username", username);
            String strPassword = preferences.getString("password", password);
            String strIpAddress = preferences.getString("ip", ipAddress);
            performLogin(strUsername, strPassword,strIpAddress);
        }
    }

// Your code...
}

Then from your LoginActivity you can call:

Device device = new Device(this);
device.validateLogin();