布尔值不保留Sharedpreference结果的最新值

时间:2015-07-16 23:59:32

标签: android sharedpreferences

我的布尔变量没有保留sharedprefs的最新值。在此函数中,它返回成功的真实性:

// Method for Async. call
public boolean downloadMatchesAsync(String date) {

    brawtaAPIAdapter.runGetMatches(date, new Callback<JSONKeys>() {

        @Override
        public void success(JSONKeys jsonKeys, Response response) {

            Success = jsonKeys.isSuccess();
            message = jsonKeys.getErrorMessage();

            if (!message.isEmpty()) {
                Toast.makeText(MyApplication.getAppContext(), message, Toast.LENGTH_SHORT).show();
            }

            Gson gson = new Gson();
            String jsonObject = gson.toJson(jsonKeys); //converts java object into json string'

            downloaded = Preferences.saveToPreferences(activity, ApplicationConstants.match_data, jsonObject);
            Log.d(ApplicationConstants.TAG,"In networkOperation " + downloaded); //is true at this point
        }

        @Override
        public void failure(RetrofitError error) {
        }
    }); // Call Async API


    return downloaded;
}

但是当我在同一个类中的另一个方法中调用该函数时,它在这里返回false:

 // Method for Async. call
public void authenticateUserAsync(String email, String password) {

    brawtaAPIAdapter.runUserAuthentication(email, password, new Callback<JSONKeys>() {
        @Override
        public void success(JSONKeys jsonKeys, Response response) {
            Success = jsonKeys.isSuccess();
            message = jsonKeys.getMessage();

            if (Success) {

                boolean b = downloadMatchesAsync(date);
                Log.d(ApplicationConstants.TAG, "In authenticateUserAsync " + b); //is false at this point

                if(b){
                    Intent i = new Intent(activity, MatchSelect.class);

                    activity.startActivity(i);
                    activity.finish();
                }
            }
        }

        @Override
        public void failure(RetrofitError error) {

            Toast.makeText(MyApplication.getAppContext(), "Incorrect Credentials", Toast.LENGTH_SHORT).show();
        }
    }); // Call Async API

}

这是我下载的变量的定义:

  public class NetworkOperations {

private BrawtaAPIAdapter brawtaAPIAdapter; // REST Adapter
private boolean Success;
private String message;
private Activity activity;
private String data;
private String date;
private boolean downloaded = false;

这是我的偏好类的定义:

 public class Preferences {

private static final String PrefName = "net.brawtasports.brawtasportsgps";

public static boolean saveToPreferences(Context context, String key, String value) {

    SharedPreferences sharedPreferences = context.getSharedPreferences(PrefName, Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.putString(key, value);
    return editor.commit();
}

public static String readFromPreferences(Context context, String key, String defaultValue) {

    SharedPreferences sharedPreferences = context.getSharedPreferences(PrefName, Context.MODE_PRIVATE);
    return sharedPreferences.getString(key, defaultValue);

}

}

我认为这是downloaded范围的问题。我该如何解决这个问题?

2 个答案:

答案 0 :(得分:2)

确保您将同一Context个对象传递给readFromPreferences()saveToPreferences()。默认情况下,当您致电Activity.getSharedPreferences()时,Android会创建一个活动名称作为前缀的文件,因此您必须传递相同的活动才能从同一个文件中读取。

如果要存储或读取与活动无关的全局首选项文件中的数据,请改用应用程序上下文

public static String readFromPreferences(Context context, String key, String defaultValue) {
    SharedPreferences sharedPreferences = context.getApplicationContext().getSharedPreferences(PrefName, Context.MODE_PRIVATE);
    return sharedPreferences.getString(key, defaultValue);
}

答案 1 :(得分:1)

我认为这里的重点是:
在downloadMatchesAsync中,下载的变量仅在异步方法中更改 但是在authenticateUserAsync中,您使用downloadMatchesAsync,就像普通的同步方法一样(在downloadMatchesAsync.success中完成工作之前返回值'已下载',您将在'在networkOperation'之前看到日志'在authenticateUserAsync'中出现)
我认为下面改变的那些可以解决你的问题:

    private boolean downloaded = false;
private HashMap<String, Boolean> authenticateUsers = new HashMap<String, Boolean>();
public boolean downloadMatchesAsync(String date, final String email) {

brawtaAPIAdapter.runGetMatches(date, new Callback<JSONKeys>() {

    @Override
    public void success(JSONKeys jsonKeys, Response response) {

        Success = jsonKeys.isSuccess();
        message = jsonKeys.getErrorMessage();

        if (!message.isEmpty()) {
            Toast.makeText(MyApplication.getAppContext(), message, Toast.LENGTH_SHORT).show();
        }

        Gson gson = new Gson();
        String jsonObject = gson.toJson(jsonKeys); //converts java object into json string'

        downloaded = Preferences.saveToPreferences(activity, ApplicationConstants.match_data, jsonObject);
        Log.d(ApplicationConstants.TAG,"In networkOperation " + downloaded); //is true at this point
        // if downloaded and user is authenticated, start the activity
        if (downloaded) {
            Boolean isAuthenticated = authenticateUsers.get(email);
            if (isAuthenticated != null && isAuthenticated) {
                Intent i = new Intent(activity, MatchSelect.class);

                activity.startActivity(i);
                activity.finish();
            }
        }
    }

    @Override
    public void failure(RetrofitError error) {
    }
}); // Call Async API


 return downloaded;
}
 public void authenticateUserAsync(final String email, String password) {

brawtaAPIAdapter.runUserAuthentication(email, password, new Callback<JSONKeys>() {
    @Override
    public void success(JSONKeys jsonKeys, Response response) {
        Success = jsonKeys.isSuccess();
        message = jsonKeys.getMessage();
        // store the authenticate result
        authenticateUsers.put(email, Success);
        if (Success) {

            // boolean b = downloadMatchesAsync(date);
            // check if work in downloadMatchesAsync completed;
            boolean b = downloaded;
            Log.d(ApplicationConstants.TAG, "In authenticateUserAsync " + b); //is false at this point

            if(b){
                Intent i = new Intent(activity, MatchSelect.class);

                activity.startActivity(i);
                activity.finish();
            } else {
                downloadMatchesAsync(date, email);
            }
        }
    }

    @Override
    public void failure(RetrofitError error) {

        // store the authenticate result
        authenticateUsers.put(email, false);
        Toast.makeText(MyApplication.getAppContext(), "Incorrect Credentials", Toast.LENGTH_SHORT).show();
    }
 }); // Call Async API

}

希望这个帮助