How to pass values from one activity to another activity in Kotlin
In previous article we have discussed on what is Intent and types of intent check on this link if required Intent and is type with example this will be continued article of previous
activity_first.xml
In this activity_first.xml file we are creating an button which on click will send data from current activity to another specified activity
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".FirstActivity"
android:orientation="vertical"> <Button android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/button"
android:text="Data Passing Example"/> </LinearLayout>
FirstActivity.kt
In this FirstActivity.kt file we are defining button click and the activity which asto be connected on click of the button along with it we are passing sample data of Name,Languageand Channel data into the specified activitypackage com.example.kotlinsampleproject import android.content.Intent import android.support.v7.app.AppCompatActivity import android.os.Bundle import kotlinx.android.synthetic.main.activity_first.* class FirstActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_first) button.setOnClickListener {intent = Intent(this, SecondActivity::class.java) intent.putExtra("Name","Sushmitha") intent.putExtra("Language","Kotlin") intent.putExtra("Channel", "SDK Book") startActivity(intent) } } }
SecondActivity.kt
In this SecondActivity.kt we are receving the data sent by FirstActivity.kt using key name specified in the bundle
package com.example.kotlinsampleproject import android.content.Intent import android.net.Uri import android.support.v7.app.AppCompatActivity import android.os.Bundle import android.widget.Toast class SecondActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_second) val bundle:Bundle = intent.extras
var name =bundle.get("Name") var lang= bundle.get("Language") var channel= bundle.get("Channel") Toast.makeText(this,"$name $lang $channel",Toast.LENGTH_LONG).show();
} }
Happy Reading 😊 Thank You Sushmitha N Hi there ! Im a experienced android developer with 4years of revelant exprience.My Skills include Android,Core Java ,Oops and Kotlin. Youtube Channel : SDK Book
Comments
Post a Comment