Passing Dimensional Arrays to Another Activity in Kotlin
Sometimes, we need to pass values from activity to another activity. For this, we use Intent methods. Firstly, let’s remember how to pass a value to another activity.
Please do not forget importing Intent;
import android.content.Intent // ActivityClass1
We have ActivityClass1 and ActivityClass2, while passing it to the ActivityClass2;
public class ActivityClass1:AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity1_layout)
var number1 = 123456
val intent = Intent(this@ActivityClass1,ActivityClass2::class.java)
intent.putExtra("number1", number1)
startActivity(intent)
}
}
}
We passed it, and right now we would like to get it.
public class ActivityClass2:AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity2_layout)
val readintent = getIntent()
var passedNumber = readintent.getIntExtra("number1")
}
}
}
As you can see, we have assigned the variable number1 in Activity 1 to the “passedNumber” variable in ActivityClass2. Now we have made this variable available in ActivityClass2 as well.
In order to send 1D-Array, it is easy. You will use the same way as above. While recieving, “getArrayExtra()” method that you can use. However, it is different a bit to send 2D-Array or Multi-Dimensional Arrays. Let’s show how to recieve 2D-Arrays.
public class ActivityClass1:AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity1_layout)
var matrix = Array(3){IntArray(3)}
var count = 1
for(i in 0 until 3)
{
for(j in 0 until 3)
{
matrix[i][j]=count
}
count++
}
val intent = Intent(this@ActivityClass1,ActivityClass2::class.java)
intent.putExtra("matrix", matrix)
startActivity(intent)
}
}
}
2D-Array has been defined above. Right now, we will get this at the ActivityClass2.
public class ActivityClass2:AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity2_layout)
val readintent = getIntent()
var passedMatrix : Array<IntArray> = readintent.getSerializableExtra("matrix") as Array<IntArray>
}
}
}
As seen above, we used the “getSerializableExtra()” method to get the 2D array. Notice that we sent the matrix as a Bundle in the “intent.putExtra(“matrix”, matrix) method in ActivityClass1, so we ordered the Bundle to be a 2D array with the keyword “as”. You can ask, if it is 3D, 4D or Multi Dimensional Array, what should we do? You will just define it like this;
var passedMatrix : Array<Array<IntArray>> = readintent.getSerializableExtra("matrix") as Array<Array<IntArray>> //3D-Array
var passedMatrix2 : Array<Array<Array<IntArray>>> = readintent.getSerializableExtra("matrix") as Array<Array<Array<IntArray>>> //4D-Array