如何只使用sharedpref.edit()一次

jv2fixgn  于 2021-09-13  发布在  Java
关注(0)|答案(2)|浏览(198)

我有一段代码,其中多次调用了sharedpref.edit()和sharedpref.apply()。如何将其转换为仅调用一次。

if (success) {
                                val data = response.getJSONObject("data")
                                sharedPreferences.edit().putBoolean("isLoggedIn", true).apply()
                                sharedPreferences.edit()
                                    .putString("user_id", data.getString("user_id")).apply()
                                sharedPreferences.edit().putString("name", data.getString("name"))
                                    .apply()
                                sharedPreferences.edit().putString("email", data.getString("email"))
                                    .apply()
                                sharedPreferences.edit()
                                    .putString("mobile_number", data.getString("mobile_number"))
                                    .apply()
                                sharedPreferences.edit()
                                    .putString("address", data.getString("address")).apply()

                                StyleableToast.Builder(this)
                                    .text("Welcome " + data.getString("name"))
                                    .backgroundColor(Color.RED)
                                    .textColor(Color.WHITE).show()

                                userSuccessfullyLoggedIn()
                            }

我只想使用方法调用一次。
这可以调用一次,返回的编辑器示例可以存储在变量中并重新使用。
怎么做??

idfiyjo8

idfiyjo81#

这些小步骤将组织您的代码。
你可以这样说:

val editor =  sharedPreferences.edit()

然后使用它:

editor.putBoolean("isLoggedIn", true)

并添加不带“.apply()的其他值
然后在末尾加上:

editor.apply()
ct3nt3jp

ct3nt3jp2#

您可以创建自定义共享首选项

class CustomSharedPreferences {

    companion object {

        private val PREFERENCES_USER_NAME = "preferences_user_name"
        private var sharedPreferences: SharedPreferences? = null

        @Volatile private var instance: CustomSharedPreferences? = null

        private val lock = Any()
        operator fun invoke(context: Context) : CustomSharedPreferences = instance ?: synchronized(lock){
            instance ?: makeCustomSharedPreferences(context).also {
                instance = it
            }
        }

        private fun makeCustomSharedPreferences(context: Context) : CustomSharedPreferences{
            sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context)
            return CustomSharedPreferences()
        }
    }

    fun saveUser(name: String, email: String){
        sharedPreferences?.edit(commit = true){
            putString(PREFERENCES_USER_NAME, name)
        }
    }

    fun getUser() = sharedPreferences?.getString(PREFERENCES_USER_NAME, "")

}

您可以在saveuser()中将所有信息保存到sp。

相关问题