Passing one or more values through Intent

Posted by Paulkirkewalker on Sat, 05 Oct 2019 20:43:51 +0200

Intent is used to transfer parameters between activities and jumps of active interfaces.
Here we first create an activity to generate a button in the activity MainActivity to pass parameters and jump the interface.
intent is mainly transmitted by the following methods:
The following is the transmission of a single parameter:

Intent intent =new Intent(MainActivity.this,SecondActivity.class);
intent.putExtra("key","value");
startActivity(intent);

Multiple parameters are transmitted through bundle s:

Bundle bundle =new Bundle();
bundle.putString("key","value");
bundle.putString("key2","value2");
intent.putExtras(bundle);
package com.game.intent822;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;

public class MainActivity extends AppCompatActivity {
private LinearLayout layout;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        final  Bundle bundle =new Bundle();
        bundle.putString("name","jack");
        bundle.putString("name2","job");

        Button button = new Button(this);
        layout=(LinearLayout)findViewById(R.id.layout);
        layout.addView(button);
        button.setText("send");
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                Intent intent = new Intent(MainActivity.this,SecondActivity.class);
                intent.putExtras(bundle);
                startActivity(intent);
            }
        });

    }
}

Then the parameters of the transmission are received in Second Activity.

Intent intent =getIntent();
intent.getStringExtra("key");
package com.game.intent822;

import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

public class SecondActivity extends AppCompatActivity {

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);
        TextView textView=(TextView)findViewById(R.id.tv);
        Intent intent = getIntent();
       String item =intent.getStringExtra("name");
       String item2=intent.getStringExtra("name2");
        textView.setText(item+" \n"+item2);
    }
}

Topics: Android