Get data from intent kotlin

Android Kotlin example to pass data from one Activity to another

In this example, we will learn how to pass data from one Activity to another in Android. We will use Kotlin and Android Studio in this exercise. For passing data in Android, we need to use objects of class Intent . Intent is a messaging object. We can use one intent to pass data from one Activity to another Activity, starting service or delivering broadcasts. The intent object takes the start activity and destination activity names. Optionally, we can set data to an intent.

In this example, we will create one Application with two screens or Activities: the first Activity will hold one EditText and one Button. The user will enter text in the EditText and click on the button. On click, we will start the second Activity and pass the string that was entered in the EditText . The second activity will read the data and show it in a TextView .

MainActivity.kt is our first activity name and activity_main.xml is its layout file. Below is the layout xml file content :

 androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> EditText android:id="@+id/editText" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginBottom="359dp" android:ems="10" android:inputType="textPersonName" android:text="Name" app:layout_constraintBottom_toTopOf="@+id/button" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginBottom="100dp" android:text="Button" android:onClick="onButtonClicked" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" /> androidx.constraintlayout.widget.ConstraintLayout>

We have one EditText and one Button . On button click, it will invoke the method onButtonClicked in MainActivity.kt . The id of the EditText is editText and the id of the Button is button .

Below is the source code for MainActivity.kt :

import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.View import android.widget.EditText class MainActivity : AppCompatActivity()  lateinit var editText: EditText override fun onCreate(savedInstanceState: Bundle?)  super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) editText = findViewById(R.id.editText) > fun onButtonClicked(view: View)  val i = Intent(this, SecondActivity::class.java).apply  putExtra("Data",editText.text.toString()) > startActivity(i) > >
  • Here, we have defined one lateinitEditText variable.
  • Inside onCreate , we are initializing the editText variable.
  • onButtonClicked method is called if the user clicks on the button. It creates one Intent object. We are adding data to this intent object using putExtra method. This method takes data as key-value pairs. The key is “Data” and the data is the text that the user has entered in the edit text. We are converting the text to String using the toString method.

The Kotlin file of the SecondActivity is SecondActivity.kt and the layout file is activity_second.xml. One TextView is placed in the center of the layout file as like below :

 androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".SecondActivity"> TextView android:id="@+id/secondTextView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> androidx.constraintlayout.widget.ConstraintLayout>

We can get the data from the intent and assign that value to this TextView :

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 intentValue = intent.getStringExtra("Data") findViewByIdTextView>(R.id.secondTextView).apply text = intentValue.toString() > > >
  • getStringExtra gets the string data that was passed with the intent with key “Data” . Different methods are available similar to this method like getBooleanExtra , getCharExtra etc.

That’s it. If you run this program, it will start the MainActivity and you can enter any text in the EditText as like below :

Android intent pass data between activities

If you click on the Button, it will start the SecondActivity and the entered text will be shown :

Android intent pass data between activities

Источник

Android Kotlin Basics – Passing Data Between Activities

This “Android Kotlin Basics” blog series is all about fundamentals. We’ll take a look at the basics of building Android apps with Kotlin from the SUPER basics, to the standard basics, to the not-so-basics. We’ll also be drawing comparisons to how things are done in Kotlin vs. Java and some other programming languages to build Android apps (like C# and Xamarin or JavaScript/TypeScript for Hybrid implementations).

Check Out the Pluralsight Course!

If you like this series, be sure to check out my course on Pluralsight – Building Android Apps with Kotlin: Getting Started where you can learn more while building your own real-world application in Kotlin along the way. You can also join the conversation and test your knowledge throughout the course with learning checks through each module!

Watch it here: https://app.pluralsight.com/library/courses/building-android-apps-kotlin-getting-started/table-of-contents

Passing Data Between Activities

This topic is covered in depth in the course above, but in this post, we’ll quickly go over this basic, but very important concept when developing your Android mobile apps.

I Have No Idea What an “Activity” Is

Not to worry! Here’s the basic idea – it’s a construct (and a class in your code) that represents an entry point for your app and can be called into by your other Activities. You can think of an Activity as a contextual “page”, and thus your app will likely have multiple Activities.

Activities can do a lot, but for simplicity sake, we’ll only talk about the most common implementation which is this idea of a drawing a window of your application.

Starting an Activity

When you create your application, you’ll have to register your Activities to your Android manifest. Doing this tells the operating system which Activities you have in your app, where to find them, what they can do, and some other information we won’t get into in this topic.

That looks something like this:

AndroidManifest.xml

This is a manifest with 3 Activities, MainActivity , SearchActivity , and ArticleDetailActivity .

Once all Activities are registered in the Manifest, we can start any of them from any other.

Let’s look at a quick example where we are in the MainActivity and want to start the SearchActivity on a button click:

MainActivity.kt

class MainActivity : Activity() < override fun onCreate(savedInstanceState: Bundle?) < my_button.setOnClickListener < // create an "Intent" val searchIntent = Intent(this, SearchActivity::class.java) // start the activity with the intent startActivity(searchIntent) >> >

So what’s this Intent object?

An Intent in Android is a construct to tell the operating system that your application is trying to execute something that needs to be communicated back to the application or a different application. This is used for many things outside just starting Activities – it can be used for executing Services, Activities, and BroadcastReceivers.

Screen Shot 2018-03-23 at 11.02.59 AM.png

Here’s a quick diagram on how this works at a basic level:

Adding Data to an Intent

So now we know we use Intents to start Activities (and do other things!), but how do we use them to actually send data to another Activity?

The Intent object has a the concept of a Extras . This means we can add different primitive datatypes to the Extras , or add Serializable data.

Here’s what that looks like in Kotlin!

// 1. create an intent from another activity val intent = Intent(context, AnotherActivity::class.java) // 2. put key/value data intent.putExtra("message", "Hello From MainActivity") // 3. start the activity with the intent context.startActivity(intent)

The putExtra has many overloads, so play around with all the types of data you can add.

You can also add Bundles of data to group the data being sent up together:

// 1. create an intent from another activity val intent = Intent(context, AnotherActivity::class.java) // 2. put key/value data to bundle val extras = Bundle() extras.putString(“message”, “Hello from MainActivity”) intent.putExtras(extras) // 3. start the activity with the intent context.startActivity(intent)

Reading Data From the Intent

Now when we use an intent to start an Activity, and add Extras , we need to be able to read those extras on the new Activity.

This works by using the intent property on the Activity . This intent property is set by the Operating System when starting the Activity, and sets it to the Intent that created it.

We usually use this data in the onCreate override, but you can use it wherever you want!

DetailActivity.kt

class DetailActivity : Activity() < override fun onCreate(savedInstanceState: Bundle?) < // In onCreate get the value from the auto-mapped “intent” val message = intent.getStringExtra(“message”) // Or get it from the bundle and auto-mapped “extras” val message = intent.extras.getString(“message”) // now do something with the message value >>

Conclusion

There’s plenty more you can do with these data structures in Android such as sending over full datatypes and reference types, receiving data back from the detail Activity, and so much more. Be sure to check out my course: Building Android Apps with Kotlin: Getting Started to learn so much more!

Also, let me know what else you’d like to learn about with Android and Kotlin! Either drop a comment here or tweet at me @Suave_Pirate!

If you like what you see, don’t forget to follow me on twitter @Suave_Pirate, check out my GitHub, and subscribe to my blog to learn more mobile developer tips and tricks!

Interested in sponsoring developer content? Message @Suave_Pirate on twitter for details.

Источник

Читайте также:  Java read text file as one string
Оцените статью