How to Save Data Passed From Another Activity In Kotlin?

14 minutes read

In Kotlin, there are different ways to save data that is passed from one activity to another. Here are a few approaches:

  1. Shared Preferences: Shared Preferences is a key-value storage mechanism offered by Android. It allows you to save small amounts of data, such as primitive data types or strings. To save data using Shared Preferences, you can use the getSharedPreferences method in the current activity and then store the data using the edit() and commit() methods.
  2. Bundle: A Bundle is an object that holds key-value pairs and is used to pass data between activities. You can store data in a Bundle using the put methods, such as putString() or putInt(). To save the data, you can create a new Bundle in the receiving activity and retrieve the data using the corresponding get methods.
  3. Parcelable or Serializable: If you need to pass more complex data objects between activities, you can make use of Parcelable or Serializable interfaces. Parcelable requires implementing the Parcelable interface and overriding its methods, while Serializable requires implementing the Serializable interface. Once implemented, you can pass the data object using Intent extras and retrieve it in the receiving activity.
  4. Database: If you want to save larger amounts of structured data, you can use a database such as SQLite. You can create a database helper class that extends SQLiteOpenHelper to handle database operations. In the sending activity, you can pass data as extras through Intents and save the data into the database. The receiving activity can then fetch the data from the database.


Remember to choose the appropriate method based on the size and complexity of the data you want to save.

Best Kotlin Books to Read in 2024

1
Atomic Kotlin

Rating is 5 out of 5

Atomic Kotlin

2
Kotlin Cookbook: A Problem-Focused Approach

Rating is 4.9 out of 5

Kotlin Cookbook: A Problem-Focused Approach

3
Head First Kotlin: A Brain-Friendly Guide

Rating is 4.8 out of 5

Head First Kotlin: A Brain-Friendly Guide

4
Kotlin in Action

Rating is 4.7 out of 5

Kotlin in Action

5
Kotlin In-Depth: A Guide to a Multipurpose Programming Language for Server-Side, Front-End, Android, and Multiplatform Mobile (English Edition)

Rating is 4.6 out of 5

Kotlin In-Depth: A Guide to a Multipurpose Programming Language for Server-Side, Front-End, Android, and Multiplatform Mobile (English Edition)

6
Kotlin Design Patterns and Best Practices: Build scalable applications using traditional, reactive, and concurrent design patterns in Kotlin, 2nd Edition

Rating is 4.5 out of 5

Kotlin Design Patterns and Best Practices: Build scalable applications using traditional, reactive, and concurrent design patterns in Kotlin, 2nd Edition

7
Kotlin Programming: The Big Nerd Ranch Guide (Big Nerd Ranch Guides)

Rating is 4.4 out of 5

Kotlin Programming: The Big Nerd Ranch Guide (Big Nerd Ranch Guides)

8
Java to Kotlin

Rating is 4.2 out of 5

Java to Kotlin

9
Kotlin Essentials (Kotlin for Developers)

Rating is 4.1 out of 5

Kotlin Essentials (Kotlin for Developers)


How to save data passed from another activity in Kotlin?

There are several ways to save data passed from another activity in Kotlin. Here are a few options:

  1. Using Intent extras: In the sending activity, you can pass data as intent extras and in the receiving activity, you can retrieve these extras and save them. Here's an example: In the sending activity:
1
2
3
val intent = Intent(this, ReceivingActivity::class.java)
intent.putExtra("key", "value")
startActivity(intent)


In the receiving activity:

1
2
val receivedData = intent.getStringExtra("key")
// Save the receivedData to use later


  1. Using Shared Preferences: This approach allows you to save the data persistently in key-value pairs using Shared Preferences. Here's an example: In the sending activity:
1
2
val sharedPreferences = getSharedPreferences("MyPrefs", Context.MODE_PRIVATE)
sharedPreferences.edit().putString("key", "value").apply()


In the receiving activity:

1
2
3
val sharedPreferences = getSharedPreferences("MyPrefs", Context.MODE_PRIVATE)
val receivedData = sharedPreferences.getString("key", "default_value")
// Save the receivedData to use later


  1. Using ViewModel: You can use ViewModel to hold and share data between activities. The ViewModel survives configuration changes and can be accessed by multiple activities. Here's an example: In the sending activity:
1
2
3
4
5
6
class MyViewModel : ViewModel() {
    val data = MutableLiveData<String>()
}

val viewModel = ViewModelProvider(this).get(MyViewModel::class.java)
viewModel.data.value = "value"


In the receiving activity:

1
2
3
val viewModel = ViewModelProvider(this).get(MyViewModel::class.java)
val receivedData = viewModel.data.value
// Save the receivedData to use later


Choose the approach that best suits your use case depending on the lifecycle and nature of the data you want to save.


How to handle null values when saving data passed from another activity in Kotlin?

When receiving data from another activity in Kotlin, you may need to handle cases where the data passed is null. Here are a few approaches to handle null values:

  1. Use the safe call operator (?): If you don't need to perform any operation on the null data, you can simply assign it to a variable using the safe call operator ? and perform further operations only if the data is not null. val receivedData: String? = intent.getStringExtra("data") receivedData?.let { // execute the code block only if receivedData is not null // do something with the non-null receivedData }
  2. Use the Elvis operator (?:) to provide a default value: If you want to assign a default value in case the data is null, you can use the Elvis operator ?:. If the received data is null, the default value will be assigned to the variable instead. val receivedData: String? = intent.getStringExtra("data") val nonNullData: String = receivedData ?: "Default Value" // nonNullData will have the value of receivedData if it's not null, otherwise it will be "Default Value"
  3. Use requireNotNull: If null data is considered as an exceptional case, you can use the requireNotNull function to throw an IllegalArgumentException with a custom error message. val receivedData: String? = intent.getStringExtra("data") val nonNullData: String = requireNotNull(receivedData) { "Data must not be null" } // nonNullData will contain the value of receivedData if it's not null. Otherwise, an exception will be thrown with a custom error message.


Remember to always handle null values appropriately to avoid NullPointerExceptions and ensure your code's correctness.


What is the role of bundles in saving data between activities in Kotlin?

In Kotlin, bundles are used to save and transfer data between different activities in an Android application. The role of bundles is to store key-value pairs of various data types, such as strings, integers, booleans, or even complex objects.


When moving from one activity to another, you can create a new Bundle object and store the required data in it using key-value pairs. This data can then be passed along with the intent when starting the next activity.


For example, to pass a string value named "username" from Activity A to Activity B, you can add it to a bundle as follows:

1
2
3
4
5
val bundle = Bundle()
bundle.putString("username", "John")
val intent = Intent(this, ActivityB::class.java)
intent.putExtras(bundle)
startActivity(intent)


Then, in Activity B, you can retrieve the value using the same key:

1
2
val bundle = intent.extras
val username = bundle?.getString("username")


In this example, the string value "John" is stored and transferred via the bundle between Activity A and Activity B. Similarly, you can save and retrieve other data types or even custom objects using appropriate methods provided by the Bundle class.


Bundles are a convenient way to pass data between activities and ensure that the required information is available in the target activity. They help in maintaining the state of the application and enable seamless communication between various components of an Android application.


How to efficiently manage memory usage when saving large data between activities in Kotlin?

To efficiently manage memory usage when saving large data between activities in Kotlin, you can follow these approaches:

  1. Use Bundles: Bundles allow you to pass data between activities in a memory-efficient way. Instead of passing large data directly, you can use bundles to store only the necessary data. Bundles are lightweight and have a smaller memory footprint compared to other options.


Here's an example of using bundles to save data between activities:

1
2
3
4
5
6
7
// Save data to bundle in sending activity
val bundle = Bundle()
bundle.putSerializable("data", largeData)
startActivity(Intent(this, NextActivity::class.java).apply { putExtras(bundle) })

// Retrieve data from bundle in receiving activity
val data = intent.getSerializableExtra("data") as? LargeData


  1. Serialize and Deserialize Objects: Instead of passing objects directly between activities, you can serialize the data into a byte array and deserialize it when needed. This allows you to save memory by storing data in a more compact form.


Here's an example of serializing/deserializing objects:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
// Save data to byte array in sending activity
val byteStream = ByteArrayOutputStream()
val objectOutputStream = ObjectOutputStream(byteStream)
objectOutputStream.writeObject(largeData)
objectOutputStream.flush()
val byteArray = byteStream.toByteArray()

// Send byte array to receiving activity

// Retrieve and deserialize data in receiving activity
val objectInputStream = ObjectInputStream(ByteArrayInputStream(byteArray))
val data = objectInputStream.readObject() as? LargeData


  1. Use onRetainNonConfigurationInstance (deprecated): If you're targeting older Android versions, you can use the onRetainNonConfigurationInstance method. However, note that this method is deprecated in newer versions of Android and is not recommended.
  2. Use ViewModel and LiveData: ViewModel and LiveData are part of Android Architecture Components. They provide a lifecycle-aware solution for managing and preserving UI-related data. By using ViewModel and LiveData, you can retain data across configuration changes, such as screen rotations, without consuming additional memory unnecessarily.


Here's an example of using ViewModel and LiveData:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
// Define a ViewModel class to hold the large data
class LargeDataViewModel: ViewModel() {
    val largeData: MutableLiveData<LargeData> = MutableLiveData()
}

// Set the large data in sending activity
val largeDataViewModel = ViewModelProvider(this).get(LargeDataViewModel::class.java)
largeDataViewModel.largeData.value = largeData

// Get the large data in receiving activity
val largeDataViewModel = ViewModelProvider(this).get(LargeDataViewModel::class.java)
val largeData = largeDataViewModel.largeData.value


By implementing these memory management techniques, you can efficiently handle large data between activities in Kotlin, reducing memory consumption and improving performance.


How to use SQLite database to save data passed from another activity in Kotlin?

To use SQLite database to save data passed from another activity in Kotlin, follow these steps:

  1. Add the necessary dependencies in your module-level build.gradle file:
1
2
implementation "androidx.sqlite:sqlite-ktx:<version>"
implementation "androidx.room:room-ktx:<version>"


  1. Create a data class that represents your database table:
1
2
3
4
5
data class MyData(
    @PrimaryKey val id: Int,
    val name: String,
    val age: Int
)


  1. Create a Room database class that extends RoomDatabase and defines your data access object (DAO):
1
2
3
4
@Database(entities = [MyData::class], version = 1)
abstract class MyDatabase : RoomDatabase() {
    abstract fun myDao(): MyDao
}


  1. Create a data access object (DAO) interface that contains the database operations you want to perform:
1
2
3
4
5
6
7
8
@Dao
interface MyDao {
    @Insert
    suspend fun insert(myData: MyData)

    @Query("SELECT * FROM MyData")
    suspend fun getAllData(): List<MyData>
}


  1. In the first activity, pass the data to the second activity using Intent extras:
1
2
3
4
5
val intent = Intent(this, SecondActivity::class.java).apply {
    putExtra("name", "John")
    putExtra("age", 25)
}
startActivity(intent)


  1. In the second activity, retrieve the data passed from the first activity and save it in the SQLite database:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
val name = intent.getStringExtra("name") ?: ""
val age = intent.getIntExtra("age", 0)

val myData = MyData(1, name, age)

val db = Room.databaseBuilder(applicationContext, MyDatabase::class.java, "my-database").build()
GlobalScope.launch {
    db.myDao().insert(myData)
    db.close()
}


Note: Make sure to handle the database operations asynchronously using coroutines (like GlobalScope.launch above) to avoid blocking the main thread.

  1. To retrieve the saved data from the database, use the following code in any activity or fragment:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
val db = Room.databaseBuilder(applicationContext, MyDatabase::class.java, "my-database").build()
GlobalScope.launch {
    val allData = db.myDao().getAllData()
    db.close()
    
    // Process the retrieved data
    for (data in allData) {
        Log.d("Database", "Name: ${data.name}, Age: ${data.age}")
    }
}


Make sure to replace <version> with the actual version of the Room and SQLite libraries you are using.

Facebook Twitter LinkedIn Telegram Whatsapp Pocket

Related Posts:

To set up a callback from a service to an activity in Kotlin, you can follow these steps:Define an interface: Create an interface in your activity file that will define the callback functions. For example: interface MyCallback { fun onResult(result: String...
Working with Android extensions in Kotlin allows you to leverage the power of Kotlin&#39;s extension functions to easily enhance the functionality of Android classes. Here&#39;s how you can work with Android extensions in Kotlin.To create an Android extension,...
To run Kotlin on Ubuntu, you can follow these steps:Install Java Development Kit (JDK): Since Kotlin runs on the Java Virtual Machine (JVM), you need to have Java installed on your system. Open a terminal and run the following command to install the default JD...
To use a Kotlin function in Java, you can follow these steps:Create a Kotlin function that you want to use in Java. For example, let&#39;s consider a simple function named printMessage() that prints a message. fun printMessage() { println(&#34;Hello, world...
The Kotlin Standard Library functions are a collection of commonly used extension functions and top-level functions provided by the Kotlin programming language. These functions aim to simplify and enhance the development process by offering a set of utility fu...
In order to call a top-level Kotlin function in Java, you need to follow the steps below:Ensure that the Kotlin function is defined as a top-level function, which means it is not nested inside any class or object. Import the necessary Kotlin dependencies in yo...