SharedPreferences问题 - 丢失上次保存的值

时间:2017-06-23 18:01:06

标签: java android sqlite sharedpreferences

我遇到一个奇怪的问题,我的应用程序从用户输入中收集一些数据并将其保存在SQLite数据库中。我还有一个不断运行的服务(START_STICKY),每30分钟通过查看SQLite DB来检查用户的新更新。如果添加了新记录,则会使用AsyncTask将其发送到我的服务器以上载数据。为了跟踪已经上传的记录,我在我的SharedPreferences上存储了一个int值。所以,这从0值开始,在每次上传时,我得到我的SQLite DB上的最后一个索引,并将其保存在我的SharedPreferences上。如果在启动应用程序后我将10条记录发送到我的服务器,我将保存" 10"在SharedPreferences和下次更新(30分钟后)之后,我将选择索引大于10的所有记录。

一切正常,但有时Android会杀死我的服务,可能是为了内存优化,然后服务重新启动(START_STICKY),应用程序继续工作。只有在这种情况下,我才会在SharedPreferences上丢失上次保存的值,因为我使用此值作为选择并将新记录上传到我的服务器的参考,我的应用程序在发生时发送重复信息。 。 我改变了从#34; apply()"中保存SharedPreferences的int值的方式。方法到" commit()"因为最后一个将信息直接保存在文件中,但问题并未解决。

欢迎任何有关如何处理此问题或其他方法的想法。

我的SharedPreferences类看起来像这样:

public class MySharedPreferences {
    private SharedPreferences sharedPref;

    public MySharedPreferences(Context context) {
        sharedPref = context.getSharedPreferences("com.mypackage", Context.MODE_PRIVATE);
    }

    public void setIndex(int n) {
        //sharedPref.edit().putInt("index", n).apply();
        SharedPreferences.Editor editor = sharedPref.edit();
        editor.putInt("index", n);
        editor.commit();
    }

    public int getIndex() {
        return sharedPref.getInt("index", 0);
    }
}

我的SharedPreferences对象是在Service onCreate方法上实现的:

MySharedPreferences mySharedPref = new MySharedPreferences(context);

这是我的服务中运行的AsyncTask的一个示例:

private class UpdateData extends AsyncTask<String, Void, Void> {
    @Override
    protected Void doInBackground(String... strings) {
        try {
            String response = utils.postDataHttps("https://my_url.com", params);
            if (response.equals("OK")) {
                // Access SQLite DB and select last index
                // by using this query: SELECT id FROM my_table ORDER BY id DESC LIMIT 1;
                int lastIndex = myDb.getLastIndex(); 
                // Set last index on SharedPreferences:
                mySharedPref.setIndex(lastIndex);
            } 
        } catch (Exception e) {
            Log.e(LOG_TAG, "UpdateData.doInBackground() - Exception: " + e.getMessage() + "\n" + Log.getStackTraceString(e));
        }
        return null;
    }
}

提前致谢!

3 个答案:

答案 0 :(得分:1)

您确定在ondestroy之后没有清理共享偏好数据吗?

<强>更新 尝试使用应用程序的上下文而不是活动的上下文。

答案 1 :(得分:0)

SharedPreference保存在ApplicationMultiDexApplication级别。好像重新创建Service时,只要您的Android应用安装在应用中,“共享优先is being reset but I am not 100% sure if that is the issue. But if you keep you value as mentioned above, the value will not set to 0 unintentionally. Since应用or MultiDexApplication”类就会保持活动状态。

答案 2 :(得分:0)

经过对SO的新研究后,我发现了这篇文章:User settings saved in SharedPreferences removed or lost between reloads of app并且由于其他选项对我不起作用,我通过创建一个表只有一个代表的记录来将我的引用变量移动到我的SQLite DB我需要存储的int值。因此,在我的应用程序的第一次运行中,如果表上没有记录,并且在将数据发送到服务器之后,我只返回0,我使用INSERT语句将最后一个索引存储在表的第一行中。每30分钟,我只检查存储在此行中的值,以确定需要向服务器发送哪些更新,并且在成功上载数据后,我使用UPDATE语句再次将最后一个索引存储在我的i​​nt变量引用中。

也许这不是最聪明的解决方案,但它的工作就像一个魅力!