how to save and retrieve application info to shared preference in kotlin?

203 Views Asked by At

I want to hide app icon from grid view and save it. I can save application info to shared preferences as mutable set string and get it but cant convert string to application info and show in my grid view

my app activity

private var applist: List<ApplicationInfo>? = null
private var listadaptor: ApplicationAdapter? = null
private var grid: GridView? = null

private var mSelected: ArrayList<Any> = ArrayList()
var context: Activity = this

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_apps)

   val packageManager = getPackageManager()
   LoadApplications().execute()
   grid = findViewById<View>(R.id.grid) as GridView
   grid!!.setChoiceMode(AbsListView.CHOICE_MODE_MULTIPLE)
   grid!!.adapter = listadaptor
   grid!!.onItemClickListener = AdapterView.OnItemClickListener { parent: AdapterView<*>?, view: View?, position: Int, id: Long ->
       val app = applist!![position]
       try {
           val intent = packageManager.getLaunchIntentForPackage(app.packageName)
           intent?.let { startActivity(it) }
       } catch (e: Exception) {
           Toast.makeText(this@appsActivity, e.message, Toast.LENGTH_LONG).show()
       }
   }
   grid!!.onItemLongClickListener = AdapterView.OnItemLongClickListener { parent, view, position, id ->

       val position1: String = (position).toString()
       if (mSelected.contains(position1)) {
           mSelected.remove(position1)
           view.setBackgroundColor(Color.TRANSPARENT) // remove item from list
           // update view (v) state here
           // eg: remove highlight
       } else {
           mSelected.add(position1)
           view.setBackgroundColor(Color.LTGRAY) // add item to list
           // update view (v) state here
           // eg: add highlight
       }
       button3.setOnClickListener(
               object : View.OnClickListener {
                   override fun onClick(view: View?) {
                       val builder1: AlertDialog.Builder = AlertDialog.Builder(this@appsActivity)
                       builder1.setMessage("Are you sure you want to delete it ?")
                       builder1.setCancelable(true)
                       builder1.setPositiveButton(
                               "Yes",
                               DialogInterface.OnClickListener { dialog, id ->

                                   deleteSelectedItems()
                                   mSelected.remove(position)
                                   listadaptor!!.notifyDataSetChanged()

                                   val app = applist!![position]
                                   listadaptor!!.remove(app)
                               })
                       builder1.setNegativeButton(
                               "No",
                               DialogInterface.OnClickListener { dialog, id -> dialog.cancel() })
                       val alert11: AlertDialog = builder1.create()
                       alert11.show()
                   }
               })
       true
   }
}
private fun deleteSelectedItems() {
    val checked: SparseBooleanArray = grid!!.getCheckedItemPositions()
    if (checked != null) {
        val list: List<Any> = mSelected
        for (i in 0 until checked.size()) {
            if (checked.valueAt(i)) {
                mSelected.remove(checked.keyAt(i))
            }
        }
    }
}
private fun checkForLaunchIntent(list: List<ApplicationInfo>): List<ApplicationInfo> {
    val applist = ArrayList<ApplicationInfo>()
    for (info in list) {
        try {
            if (null != packageManager!!.getLaunchIntentForPackage(info.packageName)) {
                applist.add(info)
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }
    Collections.sort(applist, ApplicationInfo.DisplayNameComparator(packageManager))
    return applist
}
@SuppressLint("StaticFieldLeak")
private inner class LoadApplications : AsyncTask<Void?, Void?, Void?>() {
    override fun doInBackground(vararg params: Void?): Void? {

        applist = checkForLaunchIntent(packageManager!!.getInstalledApplications(
                PackageManager.GET_META_DATA))
        listadaptor = ApplicationAdapter(this@appsActivity,
                R.layout.grid_item, applist!!)
        return null
    }
    override fun onPostExecute(result: Void?) {
        grid!!.adapter = listadaptor
        super.onPostExecute(result)
    }
}

items are deleted, but after re-running the application, all installed apps will be restored in gridview

1

There are 1 best solutions below

2
On

You can look into my open source project LibTron which has one module library for SharedPref written in Kotlin. To use the library follow the instruction in Project ReadMe Example to use the library:

val applicationInfo: ApplicationInfo = sharedprefrence.Object(name = "sharedprefKey", defaultValue = null)

Or in case you want to use it without the help of the you can use GSON, Moshi, Jackson type libraries to convert to/from string to your ApplicationInfo class while saving or reading from the Sharedprefrence