gpt4 book ai didi

android - 执行一段代码一次

转载 作者:行者123 更新时间:2023-11-30 01:39:17 25 4
gpt4 key购买 nike

我目前正在开发一个应用程序,该应用程序需要从服务器获取数据并将其存储在我的本地数据库中。为了确保这段代码仅在我执行以下操作时运行。

      SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
boolean dialogShown = settings.getBoolean("dialogShown", false);


if (!dialogShown) {
//Asyntask executed here

if (haveNetworkConnection()) {

new xyz().execute();



} else {
Toast.makeText(getApplicationContext(), "Sorry... No Internet Connection", Toast.LENGTH_LONG).show();
}

SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("dialogShown", true);
editor.apply();
}

上面我正在设置共享首选项,以便它只执行一次。现在的问题是,如果没有互联网连接,共享首选项将被执行,数据将不会被加载,我该如何克服这种情况。任何帮助表示感谢

最佳答案

Now the Problem is in case if there is no internet connection the shared preference will be executed and the data will not be loaded how can I overcome this situation.

不是在 dialogShownfalse 时更新值,而是在网络连接可用时更新 SharedPreferences 中的值,否则将其设为 false:

if (haveNetworkConnection()) {         
new xyz().execute();
// update value in SharedPreferences for dialogShown to true
} else {
// update value in SharedPreferences for dialogShown to false
}

或者使用xyz类的onPostExecute方法在所有操作成功时更新标志值

关于android - 执行一段代码一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34715225/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com