Monday, October 24, 2022

How to pass multiple value from one activity to another in Android?

 MainActivity.java

package com.example.myapplication;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends AppCompatActivity {
   EditText etName, etAge;
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      etName = findViewById(R.id.etName);
      etAge = findViewById(R.id.etAge);
      Button button = findViewById(R.id.button);
      button.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            String name = etName.getText().toString().trim();
            String age = etAge.getText().toString().trim();
            Bundle bundle = new Bundle();
            bundle.putString("name", name);
            bundle.putString("age", age);
            Intent intent = new Intent(MainActivity.this, SecondActivity.class);
            intent.putExtras(bundle);
            startActivity(intent);
         }
      });
   }
}

SecondActivity.java


package com.example.myapplication;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;

public class SecondActivity extends AppCompatActivity {
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_second);
      Bundle bundle = getIntent().getExtras();
      if (bundle ! = null) {
         String name = bundle.getString("name");
         String age = bundle.getString("age");
         TextView tvName = findViewById(R.id.tvName);
         TextView tvAge = findViewById(R.id.tvAge);
         tvName.setText(name);
         tvAge.setText(age);
      }
   }
}


No comments:

Post a Comment