Abdulrhman Alanazi
Abdulrhman Alanazi

Reputation: 88

How to pass activity values to another activity (Kotlin)

I am a new learner for Kotlin and I am trying to make a setting activity for my app and I want this activity to pass it's values to other activities. I tried different codes but none of them works and I tried to make a shared preference file but I don't know how to write the code

to be clear, I want to pass the font types from setting [main] activity to another activity but i don't know how!

my Main Activity

val preferences = applicationContext.getSharedPreferences("MyPrefs", Context.MODE_PRIVATE)
    val prefEditor = preferences.edit()

    val fonts = arrayOf("Data1", "Data2", "Data3", "Data4")
    val adapterCountry = ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, fonts)
    val spinner = findViewById(R.id.spinner) as Spinner
    spinner.adapter = adapterCountry
    spinner.setSelection(preferences.getInt("position", 0))

    spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {

        override fun onItemSelected(parent: AdapterView<*>, view: View, position: Int, id: Long) {
            spinner.setSelection(position)
            prefEditor.putInt("position", position)
            prefEditor.apply()
            val selecteditem = parent.getItemAtPosition(position).toString()
            if (selecteditem == "Data1"){

            }
        }

        override fun onNothingSelected(parent: AdapterView<*>) {
        }
    }

and this is my main 2 activity:

class Main2Activity : AppCompatActivity() {

internal lateinit var sh : SharedPreferences
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main2)

    sh = PreferenceManager.getDefaultSharedPreferences(this)





}

override fun onStart() {
    super.onStart()
    if (sh.getBoolean("positon", false)){
        when(sh.getInt("position", 0)){
           0->{
               t1.typeface = Typeface.createFromAsset(assets, "andlso.ttf")
           }
            1->{
                t1.typeface = Typeface.createFromAsset(assets, "frsspbl")
            }
        }
    }


}

i found the solution of this question here it is enter link description here

Upvotes: 0

Views: 10676

Answers (2)

Son Truong
Son Truong

Reputation: 14173

So basically you want to pass data (font type) in Int from an activity to another one. You can use SharedPrefenrences but it isn't recommended in Android.

I give you 2 solutions:

1. Using bundle

MainActivity.kt

class MainActivity : AppCompatActivity() {

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

        val fonts = arrayOf("Data1", "Data2", "Data3", "Data4")
        val adapterCountry = ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, fonts)
        val spinner = findViewById(R.id.spinner) as Spinner
        spinner.adapter = adapterCountry

        spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {

            override fun onItemSelected(parent: AdapterView<*>, view: View, position: Int, id: Long) {
                spinner.setSelection(position)
                val selecteditem = parent.getItemAtPosition(position).toString()
                if (selecteditem == "Data1") {

                }

                // Start another activity with position
                val intent = Intent(this@MainActivity, Main2Activity::class.java)
                intent.putExtra("position", position);
                startActivity(intent)
            }

            override fun onNothingSelected(parent: AdapterView<*>) {
            }
        }
    }
}

Main2Activity.kt

class Main2Activity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        val position = intent.getIntExtra("position", 0)
    }
}

2. Using SharedPreferences

MainActivity.kt

class MainActivity : AppCompatActivity() {

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

        val preferences = PreferenceManager.getDefaultSharedPreferences(this)

        val fonts = arrayOf("Data1", "Data2", "Data3", "Data4")
        val adapterCountry = ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, fonts)
        val spinner = findViewById(R.id.spinner) as Spinner
        spinner.adapter = adapterCountry
        spinner.setSelection(preferences.getInt("position", 0))

        spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {

            override fun onItemSelected(parent: AdapterView<*>, view: View, position: Int, id: Long) {
                spinner.setSelection(position)
                val selecteditem = parent.getItemAtPosition(position).toString()
                if (selecteditem == "Data1"){

                }

                // Save position to prefs.
                preferences.edit()
                        .putInt("position", position)
                        .apply()
            }

            override fun onNothingSelected(parent: AdapterView<*>) {
            }
        }
    }
}

Main2Activity.kt

class Main2Activity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        // Get position from prefs.
        val position = PreferenceManager.getDefaultSharedPreferences(this).getInt("position", 0)
    }
}

Upvotes: 1

Jon
Jon

Reputation: 1763

Intent has already existing functionality to send information from one activity to another.

// in your first activity:

val intent = Intent(context, Main2Activity::class.java)
               .putExtra("position", position)
startActivity(intent)

// in your second activity, you can fetch the extras like this:

class Main2Activity : AppCompatActivity() {

  override fun onCreate(savedInstanceState: Bundle?) {
      super.onCreate(savedInstanceState)
      val position = intent.getIntExtra("position", -1)

  }
}

I don't recommend using shared preferences to pass events between screens because you can get stuck in awkward states if your app crashes before it can cleanup it's shared pref state.

Upvotes: 1

Related Questions