【问题标题】:Creating and Moving Shared Preference Method from Activity to Java创建共享首选项方法并将其从 Activity 移动到 Java
【发布时间】:2016-06-11 02:03:48
【问题描述】:

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

}

【问题讨论】:

    标签: android android-studio sharedpreferences


    【解决方案1】:

    在您的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 拨打电话:

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

    【讨论】:

    • 谢谢你,我也忘了提,.commit 部分怎么样?是否超出了 device.id = json.getInt("id"); ?
    • 如果您想在收到成功回复后才保存信息,那么可以,您可以将其放在那里
    • 当我放置提交代码时,需要将变量声明为final。我应该在哪里做这个?
    • ALT + Enter,它会将变量声明为final
    猜你喜欢
    • 2016-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多