创建共享首选项方法并将其从Activity迁移到Java

时间:2016-06-11 02:03:49

标签: android android-studio sharedpreferences

我还不熟悉Android Studio,我想在我的Device.java类中将我的共享首选项设为一个方法,以便正确验证。但是,我不确定应该初始化哪些变量和代码放置。我的共享偏好代码所做的是验证用户是同一个用户并执行登录以绕过登录屏幕,即第一次需要登录,终身绕过欢迎屏幕。

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类:

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

}

1 个答案:

答案 0 :(得分:0)

Object cannot be cast from DBNull to other types. 中,您可以添加以下内容:

Device.java

然后从你的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... } 致电:

LoginActivity