0

I have a list of CustomClass and a function which returns this list in their own kotlin file. The function is only ever called from MainActivity but since it is not in the same file I cannot pass context when building the list.

In the custom class definition I want to access a variable in shared preferences, but to do this I need a context, which would be MainActivity. So my question is how do I grab MainActivities context from elsewhere, or is there another way to access shared preferences?

The custom class contains:

open class ListItems(
    open val title: String,
    ...
)

class GameName(
    override val title: String,
    ...
) : ListItems(title, active) {
    init {
        val context: Context = MainActivity::class
        val savedData = context.getSharedPreferences("CompletedGames", Context.MODE_PRIVATE)
        ...
    }
}
  • You can create static context in your application class. You can access it from anywhere in app. – pratik vekariya Jun 15 '22 at 12:26
  • Great, thanks for pointing me in the right direction – Rory Nesbitt Jun 15 '22 at 12:27
  • 1
    you can pass context through the constructor of the item – Ajay K S Jun 15 '22 at 12:27
  • you're not focusing on the correct problem, why do you specifically need the context from this activity ? there's a lot of ways to get context, probably even from your custom class – a_local_nobody Jun 15 '22 at 12:28
  • @a_local_nobody I suppose it doesn't have to come from the activity, I'm going by the shared preferences docs that say you need `activity?.getShared..` – Rory Nesbitt Jun 15 '22 at 12:30
  • 3
    well, my point is that this sounds like an [XY problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem) where you're stuck on getting context from the main activity, you haven't actually show us what the problem is or what you're trying to achieve. if you had shown your custom class and asked how to get context, you would have probably received more relevant feedback – a_local_nobody Jun 15 '22 at 12:32
  • @a_local_nobody I didn't think the contents would effect that one bit but fair enough, I've added the class to the original post – Rory Nesbitt Jun 15 '22 at 12:40
  • 1
    Does this answer your question? [How to retrieve a context from a non-activity class?](https://stackoverflow.com/questions/6867084/how-to-retrieve-a-context-from-a-non-activity-class) – a_local_nobody Jun 15 '22 at 12:41
  • 1
    Though static context should be avoided to prevent memory leak. Passing context to the respective class is the best practice to adopt. – Abu bakar Jun 15 '22 at 12:55

0 Answers0