Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get reference to getSharedPreferences outside fragment or activity

Thanks for stopping by! Not a duplicate of Unresolved reference: getPreferences as they had an issue with fragment and I had issues with abstract classes

I am creating an abstract class named Inspector. This class will mostly be for inspecting low-level stuff like if the app was run for the first time or is the internet working, etc.

Here is my first implementation of checking the first run:


import android.content.SharedPreferences

abstract class Inspector{
    private var PRIVATE_MODE = 0
    private var firstRun : String = "first_run"

    //Function returns if the app was run for the first time or not
    fun firstRun(): Boolean{
        return checkPref(firstRun)
    }

    private fun checkPref(PREF_NAME : String): Boolean {
        val sharedPref: SharedPreferences = getSharedPreferences(PREF_NAME, PRIVATE_MODE)
        return sharedPref.getBoolean(PREF_NAME, false)
    }
}

That's all I have in my Inspector.kt file. However I've been stuck at this issue:

Unresolved reference: getSharedPreferences

I have created this in a class that doesn't do anything yet.

  • What could be the cause of this error?
  • How do I fix it?
  • Is it because my class doesn't extend AppCompatActivity?
like image 330
SowingFiber Avatar asked Oct 23 '25 05:10

SowingFiber


1 Answers

You have to pass context as a constructor argument Please change your class with the following code. I hope it helps you

abstract class Inspector(val context: Context){
    private var PRIVATE_MODE = 0
    private var firstRun : String = "first_run"

    //Function returns if the app was run for the first time or not
    fun firstRun(): Boolean{
        return checkPref(firstRun)
    }

    private fun checkPref(PREF_NAME : String): Boolean {
        val sharedPref: SharedPreferences = context.getSharedPreferences(PREF_NAME, PRIVATE_MODE)
        return sharedPref.getBoolean(PREF_NAME, false)
    }
}

Pass activity or fragment object in constructor argument when you create class object.

like image 66
Deep Sheth Avatar answered Oct 25 '25 19:10

Deep Sheth



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!