11
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

android開発でContextをどこからでも参照できるように

Posted at

shared preferenceを使う際に引数で使われるContextをsingletonにして使い回すようにしました

SingletonContext.kt

import android.app.Application
import android.content.Context

/**
 * contextをどこからでも呼べるようにしたクラス
 */
class SingletonContext : Application() {

    // 他にやることないなら消してもいい
    override fun onCreate() {
        super.onCreate()
    }

    init {
        instance = this
    }

    companion object {
        private var instance: SingletonContext? = null

        fun applicationContext() : Context {
            return instance!!.applicationContext
        }
    }
}

それに加えて、AndroidManifest.xmlのapplication以下に追加します。

AndroidManifest.xml
+            android:name=".SingletonContext"

これがわからなくて、ずっとNULL参照でハマってた

11
10
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?