Saturday, 29 May 2021

Passing Data Between Activity in Android

 Use of the Intent We can Pass the Data between the Activity in the android application below the sample code to set the data in the Intent.


Consider the Below Activity Named Main Activity where the value is set and in another activity called DisplayMessageActivity we are displaying it. Blocked is the code that needs to be set.


1. MainActivity 


package com.example.myfirstapp;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;

import android.os.Bundle;

import android.view.View;

import android.widget.EditText;

import static android.provider.AlarmClock.EXTRA_MESSAGE;

public class MainActivity extends AppCompatActivity {

    public static final String EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE";

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

    }

   /** Called when the user taps the Send button */

    public void sendMessage(View view) {

        Intent intent = new Intent(this, DisplayMessageActivity.class);

        EditText editText = (EditText) findViewById(R.id.editTextTextPersonName);

        String message = editText.getText().toString();

        intent.putExtra(EXTRA_MESSAGE, message);

        startActivity(intent);

    }

}


2. DisplayMessageActivity  


package com.example.myfirstapp;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;

import android.os.Bundle;

import android.widget.TextView;

public class DisplayMessageActivity extends AppCompatActivity {

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_display_message);

        // Get the Intent that started this activity and extract the string

        Intent intent = getIntent();

        String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);

        // Capture the layout's TextView and set the string as its text

        TextView textView = findViewById(R.id.textView);

        textView.setText(message);

    }

}

No comments:
Write comments