Reputation:
I want to make a toast in the foo method. I have already tried different accesses (see comments). What am I doing wrong?
This didn't work:
class SettingsActivity : AppCompatActivity() {
companion object{
fun foo(context : Context){
Toast.makeText(context, "Bar", Toast.LENGTH_LONG).show()
}
}
private fun createListener() {
var listener = SharedPreferences.OnSharedPreferenceChangeListener { sharedPreferences, key ->
foo(this)
//foo(this.applicationContext)
//foo(this@SettingsActivity)
}
}
}
Working Example:
I could only call Foo if I passed a string instead of context and replaced the toast with a logging object. I called foo in the example with "foo("ttt")"
:
//this works:
fun foo(context : String){
Log.v("TTTTTT", "QQQQQQQQQQQQ")
}
There were no errors in the logcat.
Solved: Add lateinit var hi : SettingsActivity
in the companion object and fill it before calling foo. Then you can omit the context parameter.
Upvotes: 0
Views: 104
Reputation: 70
Your code seems correct, but just make sure you register the listener to your shared preference
getSharedPreferences("MyPre",Context.MODE_PRIVATE).registerOnSharedPreferenceChangeListen(listener)
Also you can modified your code from
class SettingsActivity : AppCompatActivity() {
companion object{
fun foo(context : Context){
Toast.makeText(context, "Bar", Toast.LENGTH_LONG).show()
}
}
private fun createListener() {
var listener = SharedPreferences.OnSharedPreferenceChangeListener { sharedPreferences, key ->
foo(this)
//foo(this.applicationContext)
//foo(this@SettingsActivity)
}
}
}
to
class SettingsActivity : AppCompatActivity() {
companion object{
fun foo(context : Context){
Toast.makeText(context, "Bar", Toast.LENGTH_LONG).show()
}
}
private fun createListener() {
var listener = SharedPreferences.OnSharedPreferenceChangeListener { sharedPreferences, key ->
run{
foo(this)
}
} }}
Upvotes: 0
Reputation: 4039
Please try below:
class SettingsActivity : AppCompatActivity() {
companion object{
fun foo(context : Context){
Handler().post {
Toast.makeText(context, "Bar", Toast.LENGTH_LONG).show()
}
}
}
private fun createListener() {
var listener = SharedPreferences.OnSharedPreferenceChangeListener { sharedPreferences, key ->
foo(this@SettingsActivity)
}
}
}
Upvotes: 0
Reputation: 1385
You'll need to pass context to your companion object for that, inside your activity on create just pass your context to companion object:
class SettingsActivity : AppCompatActivity() {
companion object{
var context:Context?=null
fun foo(context){
Toast.makeText(context, "Bar", Toast.LENGTH_LONG).show()
}
}
override fun onCreate(savedInstanceState: Bundle?) {
context = this
}
private fun createListener() {
var listener = SharedPreferences.OnSharedPreferenceChangeListener { sharedPreferences, key ->
foo(this)
//foo(this.applicationContext)
//foo(this@SettingsActivity)
}
}
Upvotes: 0