Explicit Intent (Serilizable)

PHOTO EMBED

Fri Apr 15 2022 04:00:18 GMT+0000 (UTC)

Saved by @anasrathore #kotlin

//serliaze class
import java.io.Serializable

class MyCustomObject: Serializable {

	var name = ""
	var id = 0
	var place = ""

	constructor(mName: String, mId: Int, mPlace: String){
		name = mName
		id = mId
		place = mPlace
	}

	constructor()
}

//XML
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
	xmlns:android="http://schemas.android.com/apk/res/android"
	xmlns:tools="http://schemas.android.com/tools"
	android:layout_width="match_parent"
	android:layout_height="match_parent"
	tools:context=".MainActivity">

	<Button
		android:id="@+id/btnSend"
		android:layout_width="wrap_content"
		android:layout_height="wrap_content"
		android:layout_centerInParent="true"
		android:text="Send" />

</RelativeLayout>


//Main Activity
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import java.io.Serializable

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

		val btn = findViewById<Button>(R.id.btnSend)

		btn.setOnClickListener {
			val intent = Intent(this, SecondActivity::class.java)
			val passingObject = MyCustomObject()
			passingObject.name = "Geek"
			passingObject.id = 1
			passingObject.place = "India"
			intent.putExtra("object", passingObject)
			startActivity(intent)
		}
	}
}
//Second Activity
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.TextView

class SecondActivity : AppCompatActivity() {
	override fun onCreate(savedInstanceState: Bundle?) {
		super.onCreate(savedInstanceState)
		setContentView(R.layout.activity_second)

		val myIntent = intent
		val derivedObject = myIntent.getSerializableExtra("object") as MyCustomObject

		val myTextView = findViewById<TextView>(R.id.tv1)
		myTextView.append(derivedObject.name + "\n")
		myTextView.append(derivedObject.id.toString() + "\n")
		myTextView.append(derivedObject.place + "\n")
	}
}
//XmL
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
	xmlns:android="http://schemas.android.com/apk/res/android"
	android:layout_width="match_parent"
	android:layout_height="match_parent">

	<TextView
		android:id="@+id/tv1"
		android:layout_width="match_parent"
		android:layout_height="wrap_content"
		android:gravity="center"
		android:layout_centerInParent="true"/>

</RelativeLayout>
content_copyCOPY