Kotlin Clear SharedPreference (KCSP)


KCSP:   SOLD       




Hi dev, this time I want to share my experience about shared preferences, which are commonly used by Android developers as temporary storage media.

Okay, so that this discussion doesn't get too long-winded, I'll assume you already understand how to CREATE and UPDATE SharedPreference.

Let's start with the assumption that we have 1 shared preference xml file, let's say the following static variable is the file name.

companion object {
         //shared file
        const val SHARED_USER = "shared_user"
}

Case study

  1. Deletes one of the data using ID as reference.
  2. Delete all shared preference data

Okay what we need to do is create a function with a specific task.

1. Delete one function

As with any storage concept, we need a key/id to delete a particular record.

 fun removeSelectedData(id: String) {
        share = context.getSharedPreferences(SHARED_USER, Context.MODE_PRIVATE)
        update = share.edit()
        update.remove(id).apply()
    }

2. Delete all function

Meanwhile, we simply refer to the shared preference file name to delete/clear all data in it.

 fun removeAllData() {
        share = context.getSharedPreferences(SHARED_SPAM, Context.MODE_PRIVATE)
        share.edit().clear().apply()
    }

Good luck!


Post a Comment

Previous Next

نموذج الاتصال