Tuesday, 28 February 2017

Transfer Data Between Activities Using Intent

user interface is displayed through an activity(Screen). Activity is used to represent the data to user and allows user interaction. In an android application, we can have multiple activities and they can interact with each other

Interaction between multiple activities can be done only using Intent. Intents are objects of theandroid.content.Intent type. Your code can send them to the Android system defining the components you are targeting. In Android app development you face situations where you want to send or receive your data between one Activity (Screen) to another. 

Calling one Activity from another in Android

Define an intent that will be sent to Activity2:
Intent launchActivity2 = new Intent(Activity1.this, Activity2.class);

Current activity Activity1 and the one you wish to open - Activity2.


Intent intent = new Intent(HomeActivity.this, EntriesActivity.class);

Button entriesButton = (Button)findViewById(;
entriesButton.setOnClickListener(new View.OnClickListener() {

    @Override    public void onClick(View v) {

        Intent intent = new Intent(HomeActivity.this, EntriesActivity.class);

pass data between activities on Android

In your current Activity, create a new Intent:
Intent i = new Intent(getApplicationContext(), NewActivity.class);

Then in the new Activity, retrieve those values:
Bundle extras = getIntent().getExtras();
if (extras != null) {
    String value = extras.getString("key");
    //The key argument here must match that used in the other activity
Use this technique to pass variables from one Activity to the other.
Current activity
btnGenerate.setOnClickListener(new View.OnClickListener(){
    @Override    public void onClick(View view) {

        Intent myIntent = new Intent(RptsalesreportActivity.this, RptsalesreportdisplayActivity.class);
        myIntent.putExtra("day", "12");
        myIntent.putExtra("month", "2");
        myIntent.putExtra("year", "2017");


New activity
Intent intent = getIntent();
String day = intent.getStringExtra("day");
String month = intent.getStringExtra("month");
String year = intent.getStringExtra("year");
value access by using getIntent() method.

Android Call An Activity class from a java class

Pass string value and Current Activity Context to function menuActions in Genfunctions class.
Java class like this
package com.example.root.calendar;

import android.content.Context;
import android.content.Intent;

public class Genfunctions {

    public void menuActions(String title,Context ct){

        switch (title){
            case "ENTRIES":

                Intent intent = new Intent(ct, RptentrylistActivity.class);

    }//end of functions

Activity Class function call like this
Genfunctions gn = new Genfunctions(); gn.menuActions("ENTRIES",this);

No comments:

Post a Comment