How to Pass Data From One Activity to Another in Android

Most android applications, atleast serious ones, comprise more than one activity. Activities in android User interface units. We need a way of then passing data from one activity to another.Thats this lessons aim.

Example 1: Android Data Passing – From TextBox To Second Activity

Android Data Passing – From TextBox To Second Activity tutorial.

Passing data between activities is a common task. This is especially because of what an activity means for android applications.

In fact data passing between entities is something that is not only fundamental to android applications but also to other types of applications.

Given that Java is an Object Oriented Programming language, and activity itself is a class, android beginners at first try to pass data in the usual way via constructors.

However, this cannot work in android since an activity itself is a special class representing screen that users can interact with.

Activities have a Context as well as lifecycle methods, making it a complex entity that has special way of working with.

If you need several pages within your application you may need several activities. Another approach is to have several fragments hosted by the same activity. However that is for another day.

===

In this example we see how to pass data from a EditText in Activity A to a gridview in Activity B.

We first hold the data the user types in a static collection. Then when he clicks a floatingactionbutton we send the data.

Here’s the project structure:

1. Create Android Studio Project

  1. First lets create an empty project in android studio. Fire up your android studio and go to File –> New Project. A dialog pops up.
  2. Type your android application name and choose the company name.
  3. Choose minimum SDK.
  4. You can choose Empty activity or Basic Activity. Both are starter templates provided by android studio.
  5. Click Finish.

This(if you choose empty activity) will generate for us a project with the following files:

No. Name Type Description
1. activity_main.xml XML Layout Will get inflated into MainActivity View.You add your views and widgets here.
2. MainActivity.java Class Our Launcher activity. This is our java file where we define our activity.

Another option is to choose a basic activity instead of empty activity.

Basic activity will have a toolbar and floating action button already added in the layout
Normally two layouts get generated with this option:

No. Name Type Description
1. activity_main.xml XML Layout Will get inflated into MainActivity Layout.Typically contains appbarlayout with toolbar.Also has a floatingactionbutton.
2. content_main.xml XML Layout Will be included into activity_main.xml.You add your views and widgets here.
3. MainActivity.java Class Main Activity.

In this example I used a basic activity.

The activity will automatically be registered in the android_manifest.xml. Android Activities are components and normally need to be registered as an application component.
If you’ve created yours manually then register it inside the <application>...<application> as following, replacing the MainActivity with your activity name:

        <activity android_name=".MainActivity">
            <intent-filter>
                <action android_name="android.intent.action.MAIN" />
                <category android_name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

You can see that one action and category are specified as intent filters. The category makes our MainActivity as launcher activity. Launcher activities get executed first when th android app is run.

2. Modify Build.Gradle

Android projects use the gradle build system.

By default android studio generates two build.gradle files: one in the app folder and another in the project folder.

We need now to come and modify our app level(one in app folder) build.gradle. Only do this if you don’t have the appcompat and design support library added.

    apply plugin: 'com.android.application'
    android {
        compileSdkVersion 24
        buildToolsVersion "25.0.1"
        defaultConfig {
            applicationId "com.tutorials.hp.txttoactivitygrid"
            minSdkVersion 15
            targetSdkVersion 24
            versionCode 1
            versionName "1.0"
        }
        buildTypes {
            release {
                minifyEnabled false
                proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            }
        }
    }
    dependencies {
        compile fileTree(dir: 'libs', include: ['*.jar'])
        testCompile 'junit:junit:4.12'
        compile 'com.android.support:appcompat-v7:24.2.1'
        compile 'com.android.support:design:24.2.1'
    }

You may use newer versions.

3 (a). ActivityMain.xml

Here’s our activity_main.xml layout.

This layout will get inflated to MainActivity. It further includes the content_main.xml.

Here’s our activity_main.xml layout.

    <?xml version="1.0" encoding="utf-8"?>
    <android.support.design.widget.CoordinatorLayout 
        
        
        android_layout_width="match_parent"
        android_layout_height="match_parent"
        android_fitsSystemWindows="true"
        tools_context="com.tutorials.hp.txttoactivitygrid.MainActivity">
        <android.support.design.widget.AppBarLayout
            android_layout_width="match_parent"
            android_layout_height="wrap_content"
            android_theme="@style/AppTheme.AppBarOverlay">
            <android.support.v7.widget.Toolbar
                android_id="@+id/toolbar"
                android_layout_width="match_parent"
                android_layout_height="?attr/actionBarSize"
                android_background="?attr/colorPrimary"
                app_popupTheme="@style/AppTheme.PopupOverlay" />
        </android.support.design.widget.AppBarLayout>
        <include layout="@layout/content_main" />
        <android.support.design.widget.FloatingActionButton
            android_id="@+id/fab"
            android_layout_width="wrap_content"
            android_layout_height="wrap_content"
            android_layout_gravity="bottom|end"
            android_layout_margin="@dimen/fab_margin"
            android_src="@android:drawable/ic_dialog_email" />
    </android.support.design.widget.CoordinatorLayout>

(b). content_main.xml

This is our second MainActivity layout.

We add our input fields right here. In this case a simple button and a TextInputEditText.

    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout 
        
        
        android_layout_width="match_parent"
        android_layout_height="match_parent"
        android_paddingBottom="@dimen/activity_vertical_margin"
        android_paddingLeft="@dimen/activity_horizontal_margin"
        android_paddingRight="@dimen/activity_horizontal_margin"
        android_paddingTop="@dimen/activity_vertical_margin"
        app_layout_behavior="@string/appbar_scrolling_view_behavior"
        tools_context="com.tutorials.hp.txttoactivitygrid.MainActivity"
        tools_showIn="@layout/activity_main">
        <LinearLayout
            android_layout_width="match_parent"
            android_layout_height="wrap_content"
            android_orientation="vertical">
            <android.support.design.widget.TextInputEditText
                android_id="@+id/nameTxt"
                android_layout_width="match_parent"
                android_layout_height="wrap_content"
                android_enabled="true"
                android_focusable="true"
                android_hint="Name"
                android_textSize="25dp"
                android_textStyle="bold" />
            <Button android_id="@+id/addBtn"
                android_layout_width="wrap_content"
                android_layout_height="60dp"
                android_text="Save"
                android_clickable="true"
                android_padding="5dp"
                android_background="#009968"
                android_textColor="@android:color/white"
                android_textStyle="bold"
                android_textSize="20dp" />
        </LinearLayout>
    </RelativeLayout>

(c). ActivitySecond.xml

We now come to the SecondActivity‘s layout.

This layout will get inflated into the SecondActivity,the activity that will be opened when we click our button.

This layout contains a two column gridview that will display our data.

Here’s our layout code:

    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout 
        
        android_layout_width="match_parent"
        android_layout_height="match_parent"
        android_paddingBottom="@dimen/activity_vertical_margin"
        android_paddingLeft="@dimen/activity_horizontal_margin"
        android_paddingRight="@dimen/activity_horizontal_margin"
        android_paddingTop="@dimen/activity_vertical_margin"
        tools_context="com.tutorials.hp.txttoactivitygrid.SecondActivity">
        <GridView
            android_id="@+id/gv"
            android_layout_width="match_parent"
            android_layout_height="wrap_content"
            android_numColumns="2">
        </GridView>
    </RelativeLayout>

4. Java Classes

We are going to have a couple of classes in our application.

As usual android applications get written in java.

(a). DataHolder.java

Our first class is the DataHolder class.

This simple class will contain a static ArrayList that will hold our data.
This ArrayList will act as our data source,.

First we specify our package:

package com.tutorials.hp.txttoactivitygrid;

We’ll have one import:

import java.util.ArrayList;

Then create the class:

public class DataHolder {}

Then add our ArrayList instance as a class member of DataHolder class:

public static ArrayList<String> spacecrafts=new ArrayList<>();

As a class member we won’t need to instantiate our DataHolder class to reference that spacecrafts field.

(b). SecondActivity.java

This is our second activity.

This class or activity has the responsibility of displaying data we receive from the first activity in a GridView.

First specify the package name:

package com.tutorials.hp.txttoactivitygrid;

The we add our imports just below the package declaration. Our imports include AppCompatActivity, Bundle, ArrayAdapter and GridView.

    package com.tutorials.hp.txttoactivitygrid;
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.widget.ArrayAdapter;
    import android.widget.GridView;

Then declare our activity. We make it derive from android.support.v7.app.AppCompatActivity:

public class SecondActivity extends AppCompatActivity {}

Then add a GridView as an instance field:

GridView gv;

Then override our onCreate() method. OnCreate() is a callback method that gets called when an activity is created. It allows us listen to activity creation events.

We need to invoke the onCreate() method of the super class passing in our savedInstanceState which is a bundle object.

@Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            }

Then set its contentview to the activity_second.xml. Inside this setContentView() method we will inflate our R.layout.activity_second.

setContentView(R.layout.activity_second);

Then reference the GridView ans set its adapter. We reference it using findViewById() method passing in the id.

We then set the arrayadapter instance to our GridView’s setAdapter() method.

gv= (GridView) findViewById(R.id.gv);
gv.setAdapter(new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, DataHolder.spacecrafts));

(c). MainActivity.java

The MainActivity is typically our launcher activity. This it’s the activity that launches our application.

This class in our case is where we will have our TextInpuEditText. The user will type his data and click save to insert data into our arraylist collection.

Then when he clicks the FloatingActionButton we send the data to the SecondActivity.

First let’s specify the package:

package com.tutorials.hp.txttoactivitygrid;

Then add import just below the package:

    import android.content.Intent;
    import android.os.Bundle;
    import android.support.design.widget.FloatingActionButton;
    import android.support.design.widget.Snackbar;
    import android.support.design.widget.TextInputEditText;
    import android.support.v7.app.AppCompatActivity;
    import android.support.v7.widget.Toolbar;
    import android.view.View;
    import android.view.Menu;
    import android.view.MenuItem;
    import android.widget.Button;

Then create our activity by deriving from AppCompatActivity.

This activity will have two instance fields: a TextInputEditText and a Button.

    public class MainActivity extends AppCompatActivity {
        private TextInputEditText txtName;
        private Button sendBtn;
        }

Then create the method to add data to our collection.

Basically we reference the spacecrafts arraylist from DataHolder and invoke it’s add() method passing in the contents of the EditText as a string.

We reset the EditText by passing in empty string into our setText() method.

        private void send()
        {
            DataHolder.spacecrafts.add(txtName.getText().toString());
            txtName.setText("");
        }

Next we override our onCreate() method, invoke the super.onCreate() method, pass the R.layout.activity_main into our setContentView() method.

Our activity will have a ToolBar which is actually defined inside our activity_main.xml file

 @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
            setSupportActionBar(toolbar);

Then initialize the following widgets inside the onCreate method:

txtName= (TextInputEditText) findViewById(R.id.nameTxt);
 sendBtn= (Button) findViewById(R.id.addBtn);

Then when the FloatingActionButton is clicked we start the SecondActivity. When the sendBtn is clicked we send data to our collection.:

 FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
            fab.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    startActivity(new Intent(MainActivity.this,SecondActivity.class));
                }
            });
            sendBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    send();
                }
            });

And that’s it.

More Resources:

Resource Link
YouTube Video https://youtu.be/Q5RrYweDiqI
GitHub Download Link Download

 

Example 2: Android Data Parsing – String,Integer,Boolean – Activity To Activity

The aim is to see how to pass Strings,Integers and Booleans, primitive data types from one activity to another using Intent.Here’s the thing :

  • Pass integers,booleans and string from one activity to another.
  • The booleans shall be represented in a checkbox,the string in an edittext while the integer also in an edittext.
  • The user enters them in our MainActivity,we pass them via intent, and show them in second activity.
  • We use intents.

Android Pass String Integer and Boolean from Activity to another This is our second android pass data to another activity example.

Create/Download Project

  • Download the project above.
  • You’ll get a zipped file,extract it.
  • Open the Android Studio.
  • Now close, already open project
  • From the Menu bar click on File >New> Import Project
  • Now Choose a Destination Folder, from where you want to import project.
  • Choose an Android Project.
  • Now Click on “OK“.
  • Done, your done importing the project,now edit it.

Our Layouts

ContentMain.xml

  • Our MainActivity’s layout.
  • Add Checkbox to show boolean values and edittexts to show integer and string.
  • User enters these values at runtime.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 
    
    
    android_layout_width="match_parent"
    android_layout_height="match_parent"
    android_paddingBottom="@dimen/activity_vertical_margin"
    android_paddingLeft="@dimen/activity_horizontal_margin"
    android_paddingRight="@dimen/activity_horizontal_margin"
    android_paddingTop="@dimen/activity_vertical_margin"
    app_layout_behavior="@string/appbar_scrolling_view_behavior"
    tools_context="com.tutorials.hp.primitivespassing.MainActivity"
    tools_showIn="@layout/activity_main">

    <LinearLayout
        android_layout_width="match_parent"
        android_layout_height="wrap_content"
        android_orientation="vertical">

        <android.support.design.widget.TextInputEditText
            android_id="@+id/nameTxt"
            android_layout_width="match_parent"
            android_layout_height="wrap_content"
            android_enabled="true"
            android_focusable="true"
            android_hint="Name"
            android_textSize="25dp"
            android_textStyle="bold" />

        <android.support.design.widget.TextInputEditText
            android_id="@+id/txtID"
            android_layout_width="match_parent"
            android_layout_height="wrap_content"
            android_enabled="true"
            android_focusable="true"
            android_hint="ID"
            android_textSize="25dp"
            android_textStyle="bold" />

        <LinearLayout
            android_layout_width="match_parent"
            android_layout_height="wrap_content"
            android_orientation="horizontal"
            android_padding="5dp">

            <TextView
                android_layout_width="250dp"
                android_layout_height="wrap_content"
                android_text="Technology Exists ??"
                android_textSize="25dp"
                android_textStyle="bold" />

            <CheckBox
                android_id="@+id/techExists"
                android_layout_width="wrap_content"
                android_layout_height="wrap_content"
                android_checked="true"
                android_textSize="25dp" />
        </LinearLayout>
        <Button android_id="@+id/sendBtn"
            android_layout_width="wrap_content"
            android_layout_height="60dp"
            android_text="Send"
            android_clickable="true"
            android_padding="5dp"
            android_background="#009968"
            android_textColor="@android:color/white"
            android_textStyle="bold"
            android_textSize="20dp" />
    </LinearLayout>
</RelativeLayout>

ActivitySecond.xml

  • Our SecondActivity’s layout.
  • Add Checkbox to show boolean values and edittexts to show integer and string.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 
    
    android_layout_width="match_parent"
    android_layout_height="match_parent"
    android_paddingBottom="@dimen/activity_vertical_margin"
    android_paddingLeft="@dimen/activity_horizontal_margin"
    android_paddingRight="@dimen/activity_horizontal_margin"
    android_paddingTop="@dimen/activity_vertical_margin"
    tools_context="com.tutorials.hp.primitivespassing.SecondActivity">

    <LinearLayout
        android_layout_width="match_parent"
        android_layout_height="wrap_content"
        android_orientation="vertical">

        <LinearLayout
            android_layout_width="match_parent"
            android_layout_height="wrap_content"
            android_orientation="horizontal"
            android_padding="5dp">

            <TextView
                android_layout_width="250dp"
                android_layout_height="wrap_content"
                android_text="NAME"
                android_textSize="25dp"
                android_textStyle="bold" />

            <TextView
                android_id="@+id/nameTxtSecond"
                android_layout_width="match_parent"
                android_layout_height="wrap_content"
                android_text="value received"
                android_textSize="25dp" />
        </LinearLayout>

        <LinearLayout
            android_layout_width="match_parent"
            android_layout_height="wrap_content"
            android_orientation="horizontal"
            android_padding="5dp">

            <TextView
                android_layout_width="250dp"
                android_layout_height="wrap_content"
                android_text="ID"
                android_textSize="25dp"
                android_textStyle="bold" />

            <TextView
                android_id="@+id/txtIDSecond"
                android_layout_width="match_parent"
                android_layout_height="wrap_content"
                android_text="value received"
                android_textSize="25dp" />
        </LinearLayout>

        <LinearLayout
            android_layout_width="match_parent"
            android_layout_height="wrap_content"
            android_orientation="horizontal"
            android_padding="5dp">

            <TextView
                android_layout_width="250dp"
                android_layout_height="wrap_content"
                android_text="Technology Exists ??"
                android_textSize="25dp"
                android_textStyle="bold" />

            <CheckBox
                android_id="@+id/techExistsSecond"
                android_layout_width="wrap_content"
                android_layout_height="wrap_content"
                android_checked="true"
                android_textSize="25dp" />
        </LinearLayout>

    </LinearLayout>
</RelativeLayout>

Our Classes

MainActivity class

  • Launcher activity.
  • We pack data into an intent and pass them to Second activity from here.
package com.tutorials.hp.primitivespassing;

import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.TextInputEditText;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;

public class MainActivity extends AppCompatActivity {

    //DECLARE VIEWS
    private TextInputEditText txtName, txtID;
    private CheckBox chkTechnologyExists;
    private Button sendBtn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        this.initializeViews();

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
            }
        });

        //WHEN SEND BTN IS CLICKED,SEND
        sendBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                sendData();
            }
        });
    }

    /*
    REFERENCE VIEWS WE ARE USING
     */
    private void initializeViews() {
        txtName = (TextInputEditText) findViewById(R.id.nameTxt);
        txtID = (TextInputEditText) findViewById(R.id.txtID);
        chkTechnologyExists = (CheckBox) findViewById(R.id.techExists);
        sendBtn = (Button) findViewById(R.id.sendBtn);

    }

    /*
    SEND DATA TO SECOND ACTIVITY
     */
    private void sendData() {
        //GET PRIMITIVE VALUES TO SEND
        String name = txtName.getText().toString();
        int id = Integer.parseInt(txtID.getText().toString());
        Boolean techExists = chkTechnologyExists.isChecked();

        //PACK THEM IN AN INTENT OBJECT
        Intent i = new Intent(this, SecondActivity.class);
        i.putExtra("NAME_KEY", name);
        i.putExtra("ID_KEY", id);
        i.putExtra("TECHEXISTS_KEY", techExists);

        //LETS LEAVE OUR TXTS CLEARED
        txtName.setText("");
        txtID.setText("");

        //START SECOND ACTIVITY
        this.startActivity(i);
    }

}

SecondActivity class

  • This activity unpacks the data sent by intent from MainActivity.
  • It then displays them in their respective views.
package com.tutorials.hp.primitivespassing;

import android.support.design.widget.TextInputEditText;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.CheckBox;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class SecondActivity extends AppCompatActivity {

    //DECALRE SECOND ACTIVITY VIEWS
    TextView txtName2;
    TextView txtID2;
    CheckBox chkTechnologyExists2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);

        //INITIALIZE THESE VIEWS
        txtName2 = (TextView) findViewById(R.id.nameTxtSecond);
        txtID2 = (TextView) findViewById(R.id.txtIDSecond);
        chkTechnologyExists2 = (CheckBox) findViewById(R.id.techExistsSecond);

        //RECEIVE DATA FROM MAIN ACTIVITY
        String name = getIntent().getStringExtra("NAME_KEY");
        int id = getIntent().getIntExtra("ID_KEY", 0);
        Boolean techExists = getIntent().getBooleanExtra("TECHEXISTS_KEY", false);

        //SHOW A TOAST
        Toast.makeText(SecondActivity.this, name, Toast.LENGTH_LONG).show();

        //SET THE DATA TO OUR LOCAL VIEWS
        txtName2.setText(name);
        txtID2.setText(String.valueOf(id));
        chkTechnologyExists2.setChecked(techExists);
    }
}

More Resources:

Resource Link
GitHub Browse Browse
GitHub Download Link Download

 

Example 3 : Android Data Passing – One GridView Activity To Another

How to pass an arraylist of data from one GridView in one activity to another GridView in a second activity in java android.We are trying to see how to pass complex data like an arraylist between activities.

Intro

  • We explore how to use Serializable to pass objects between activities.
  • This allows us to pass an arraylist of data between these two activities,from one gridview to another.
  • We pass data via intent object.
  • We’ve used Android Studio as our IDE.
  • The code is well commented for easier understanding.

Common Questions we answer

With this simple example we explore the following :

  • How to pass data from one activity to another.
  • How to pass object from one activity to anothe in android.
  • How to use Serializable interface to pass objects.
  • Passing data from GridView in one activity to another.
  • Sending data via intent in android.
  • Using ArrayAdapter with GridView.
  • How to sort and reverse an Collections in Java.
  • Using Android with GridView.

Tools Used

  • IDE : Android Studio
  • OS : Windows 8.1
  • PLATFORM : Android
  • LANGUAGE : Java
  • TOPIC : Serializable,Intent,GridView

Let’s go.

1. Build.Gradle(App)

  • Here’s our app level build.gradle.
  • No external dependencies.
dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:24.2.1'
    compile 'com.android.support:design:24.2.1'
}

2. SpacecraftCollection class

  • This class shall implement serializable.
  • Given that it has an arraylist of data that we want to send to second activity,we serialize the class and deserialize it later on in the second activity to access that arraylist.
package com.tutorials.hp.gridviewdataparsing;

import java.io.Serializable;
import java.util.ArrayList;

/**
 * CLASS IMPLEMENTS SERIALIZABLE
 */
public class SpacecraftsCollection implements Serializable {

    private ArrayList<String> spacecrafts;

    public ArrayList<String> getSpacecrafts() {
        return spacecrafts;
    }

    public void setSpacecrafts(ArrayList<String> spacecrafts) {
        this.spacecrafts = spacecrafts;
    }
}

3. MainActivity Class

  • Our MainActivity,launcher activity.
  • First we reference views here including GridView.
  • We get our data and bind it to the GridView in our MainActivity.
  • We instantiate an Intent object through which we will start our second activity and send our arraylist to second activity.
  • We’ll actually be passing a serialized class.
package com.tutorials.hp.gridviewdataparsing;

import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.GridView;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {
    GridView gv;
    ArrayList spacecrafts=new ArrayList();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        gv= (GridView) findViewById(R.id.firstGV);
        populateData();
        gv.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,spacecrafts));

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                gv.setAdapter(new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_list_item_1,new ArrayList<String>()));
               sendData();
            }
        });
    }

  //POPULATE ARRAYLIST WITH DATA
    private void populateData()
    {
        spacecrafts.add("Casini");
        spacecrafts.add("Enterprise");
        spacecrafts.add("Spitzer");
        spacecrafts.add("Huygens");
        spacecrafts.add("WMAP");
        spacecrafts.add("Juno");
        spacecrafts.add("Kepler");
        spacecrafts.add("Apollo 15");
        spacecrafts.add("Challenger");
        spacecrafts.add("Discovery");
    }

    /*
    FILL DATA
     */
    private SpacecraftsCollection getData()
    {

        SpacecraftsCollection spacecraftsCollection=new SpacecraftsCollection();
        spacecraftsCollection.setSpacecrafts(spacecrafts);

        return spacecraftsCollection;
    }

    /*
    SEND DATA TO SECOND ACTIVITY
     */
    private void sendData()
    {
        Intent i=new Intent(this,SecondActivity.class);
        i.putExtra("SPACECRAFTS",this.getData());
        startActivity(i);
    }

}

4. SecondActivity

  • Our second activity.
  • Shall contain a GridView as well.
  • We receive the sent SpaceshipCollection object right here.
  • It was serialized and sent,so we deseialize it and get the arraylist of data we want and bind to GridView.
package com.tutorials.hp.gridviewdataparsing;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.ArrayAdapter;
import android.widget.GridView;

public class SecondActivity extends AppCompatActivity {

    GridView gv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);

        gv= (GridView) findViewById(R.id.secondGV);

        receiveData();
    }

    /*
    RECEIVE DATA FROM FIRST ACTIVITY
     */
    private void receiveData()
    {
        Intent i=this.getIntent();
        SpacecraftsCollection spacecraftsCollection= (SpacecraftsCollection) i.getSerializableExtra("SPACECRAFTS");

        gv.setAdapter(new ArrayAdapter<>(this,android.R.layout.simple_list_item_1,spacecraftsCollection.getSpacecrafts()));
    }
}

5. Create User Interface

User interfaces are typically created in android using XML layouts as opposed by direct java coding.

This is an example fo declarative programming.

Advantages of Using XML over Java
No. Advantage
1. Declarative creation of widgets and views allows us to use a declarative language XML which makes is easier.
2. It’s easily maintanable as the user interface is decoupled from your Java logic.
3. It’s easier to share or download code and safely test them before runtime.
4. You can use XML generated tools to generate XML

Here are our layouts for this project:

(a). activity_main.xml

  • This layout gets inflated to MainActivity user interface.
  • It includes the content_main.xml.

Here are some of the widgets, views and viewgroups that get employed”

No. View/ViewGroup Package Role
1. CordinatorLayout android.support.design.widget Super-powered framelayout that provides our application’s top level decoration and is also specifies interactions and behavioros of all it’s children.
2. AppBarLayout android.support.design.widget A LinearLayout child that arranges its children vertically and provides material design app bar concepts like scrolling gestures.
3. ToolBar <android.support.v7.widget A ViewGroup that can provide actionbar features yet still be used within application layouts.
4. FloatingActionButton android.support.design.widget An circular imageview floating above the UI that we can use as buttons.

(b). content_main.xml

This layout gets included in your activity_main.xml.
We define our UI widgets here.

  • Main Layout.
  • We specify Views and widgets xml code here.
  • Contains first GridView.
  • This layout shall get inflated into our MainActivity interface.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 
    
    
    android_layout_width="match_parent"
    android_layout_height="match_parent"
    android_paddingBottom="@dimen/activity_vertical_margin"
    android_paddingLeft="@dimen/activity_horizontal_margin"
    android_paddingRight="@dimen/activity_horizontal_margin"
    android_paddingTop="@dimen/activity_vertical_margin"
    app_layout_behavior="@string/appbar_scrolling_view_behavior"
    tools_context="com.tutorials.hp.gridviewdataparsing.MainActivity"
    tools_showIn="@layout/activity_main">

    <GridView
        android_id="@+id/firstGV"
        android_layout_width="match_parent"
        android_layout_height="wrap_content"
        android_numColumns="2"
        />
</RelativeLayout>

(c). SecondActivity Layout

  • Second Activity Layout.
  • We specify Views and widgets xml code here.
  • Contains second gridview.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 
    
    android_layout_width="match_parent"
    android_layout_height="match_parent"
    android_paddingBottom="@dimen/activity_vertical_margin"
    android_paddingLeft="@dimen/activity_horizontal_margin"
    android_paddingRight="@dimen/activity_horizontal_margin"
    android_paddingTop="@dimen/activity_vertical_margin"
    tools_context="com.tutorials.hp.gridviewdataparsing.SecondActivity">

    <GridView
        android_id="@+id/secondGV"
        android_layout_width="match_parent"
        android_layout_height="wrap_content"
        android_numColumns="2"
        />
</RelativeLayout>

How To Run

  • Download the project above.
  • You’ll get a zipped file,extract it.
  • Open the Android Studio.
  • Now close, already open project
  • From the Menu bar click on File >New> Import Project
  • Now Choose a Destination Folder, from where you want to import project.
  • Choose an Android Project.
  • Now Click on “OK“.
  • Done, your done importing the project,now edit it.

More Resources

Resource Link
GitHub Browse Browse
GitHub Download Link Download

Oclemy,Cheers.

 

Share

1 Example

  1. Android Data Passing : ListView to ListView

    Sometimes you may want to pass data from one listview in Activity A to ListView in say Activity B. Well that’s the purpose of this tutorial.

    We’ll have two Activities, each with a ListView. We click a button and pass data from the first activity to the second activity, the first litsview to the second listview.

    Activity 1

    Activity 2

    Gradle Scripts

    Let’s modify our build.gradle file app level.

    1. Build.gradle

    • We specify dependencies under the dependencies closure.
        apply plugin: 'com.android.application'
    
        android {
            compileSdkVersion 25
            buildToolsVersion "25.0.2"
            defaultConfig {
                applicationId "com.tutorials.hp.listviewdatapassing"
                minSdkVersion 15
                targetSdkVersion 25
                versionCode 1
                versionName "1.0"
                testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
            }
            buildTypes {
                release {
                    minifyEnabled false
                    proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
                }
            }
        }
    
        dependencies {
            compile fileTree(dir: 'libs', include: ['*.jar'])
            compile 'com.android.support:appcompat-v7:25.2.0'
            compile 'com.android.support:design:25.2.0'
            testCompile 'junit:junit:4.12'
        }

    LAYOUTS

    We’ll have three layouts:

    1. activity_main.xml

    • This layout will get inflated into the UI for our mainactivity.
    • It will hold the content_main.xml layout.
    • It contains our appbar and toolbar definitions.
        <?xml version="1.0" encoding="utf-8"?>
        <android.support.design.widget.CoordinatorLayout 
            
            
            android_layout_width="match_parent"
            android_layout_height="match_parent"
            android_fitsSystemWindows="true"
            tools_context="com.tutorials.hp.listviewdatapassing.MainActivity">
    
            <android.support.design.widget.AppBarLayout
                android_layout_width="match_parent"
                android_layout_height="wrap_content"
                android_theme="@style/AppTheme.AppBarOverlay">
    
                <android.support.v7.widget.Toolbar
                    android_id="@+id/toolbar"
                    android_layout_width="match_parent"
                    android_layout_height="?attr/actionBarSize"
                    android_background="?attr/colorPrimary"
                    app_popupTheme="@style/AppTheme.PopupOverlay" />
    
            </android.support.design.widget.AppBarLayout>
    
            <include layout="@layout/content_main" />
    
            <android.support.design.widget.FloatingActionButton
                android_id="@+id/fab"
                android_layout_width="wrap_content"
                android_layout_height="wrap_content"
                android_layout_gravity="bottom|end"
                android_layout_margin="@dimen/fab_margin"
                app_srcCompat="@android:drawable/ic_dialog_email" />
    
        </android.support.design.widget.CoordinatorLayout>

    2. content_main.xml

    • This will contain our First ListView.
    • This layout gets included inside the activity_main.xml.
        <?xml version="1.0" encoding="utf-8"?>
        <RelativeLayout 
            
            
            android_id="@+id/content_main"
            android_layout_width="match_parent"
            android_layout_height="match_parent"
            android_paddingBottom="@dimen/activity_vertical_margin"
            android_paddingLeft="@dimen/activity_horizontal_margin"
            android_paddingRight="@dimen/activity_horizontal_margin"
            android_paddingTop="@dimen/activity_vertical_margin"
            app_layout_behavior="@string/appbar_scrolling_view_behavior"
            tools_context="com.tutorials.hp.listviewdatapassing.MainActivity"
            tools_showIn="@layout/activity_main">
    
            <ListView
                android_id="@+id/firstLV"
                android_layout_width="match_parent"
                android_layout_height="wrap_content" />
        </RelativeLayout>

    3. activity_second.xml

    • This layout will be inflated into the UI for our second activity.
    • It will hold the second activity.
        <?xml version="1.0" encoding="utf-8"?>
        <RelativeLayout 
            
            android_id="@+id/activity_second"
            android_layout_width="match_parent"
            android_layout_height="match_parent"
            android_paddingBottom="@dimen/activity_vertical_margin"
            android_paddingLeft="@dimen/activity_horizontal_margin"
            android_paddingRight="@dimen/activity_horizontal_margin"
            android_paddingTop="@dimen/activity_vertical_margin"
            tools_context="com.tutorials.hp.listviewdatapassing.SecondActivity">
            <ListView
                android_id="@+id/secondLV"
                android_layout_width="match_parent"
                android_layout_height="wrap_content"
                />
        </RelativeLayout>

    JAVA CLASSES

    Here are our java classes:

    1. SpacecraftsCollection

    • This is class that will help us in transfering our ArrayList from the first to the second activity. This class will be serialized, transfered then deserialized in the second activity
        package com.tutorials.hp.listviewdatapassing;
    
        import java.io.Serializable;
        import java.util.ArrayList;
    
        public class SpacecraftsCollection implements Serializable {
    
            private ArrayList<String> spacecrafts;
    
            public ArrayList<String> getSpacecrafts() {
                return spacecrafts;
            }
    
            public void setSpacecrafts(ArrayList<String> spacecrafts) {
                this.spacecrafts = spacecrafts;
            }
        }

    2. SecondActivity.java

    • This is our second activity class.
    • It will receive a serialized arraylist containing our spacecrafts and deserialize it and display in the second listview.
        package com.tutorials.hp.listviewdatapassing;
    
        import android.content.Intent;
        import android.support.v7.app.AppCompatActivity;
        import android.os.Bundle;
        import android.widget.ArrayAdapter;
        import android.widget.ListView;
    
        public class SecondActivity extends AppCompatActivity {
    
            //SECOND LISTVIEW
            ListView lv;
    
            @Override
            protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_second);
    
                lv= (ListView) findViewById(R.id.secondLV);
    
                receiveData();
            }
    
            /*
            RECEIVE DATA FROM FIRST ACTIVITY
             */
            private void receiveData()
            {
                Intent i=this.getIntent();
                SpacecraftsCollection spacecraftsCollection= (SpacecraftsCollection) i.getSerializableExtra("SPACECRAFTS");
    
                lv.setAdapter(new ArrayAdapter<>(this,android.R.layout.simple_list_item_1,spacecraftsCollection.getSpacecrafts()));
            }
        }

    3. MainActivity.java

    • Our MainActivity class.
    • Our arraylist data will be transfered from here to the second activity when the floating action button is clicked.
        package com.tutorials.hp.listviewdatapassing;
    
        import android.content.Intent;
        import android.os.Bundle;
        import android.support.design.widget.FloatingActionButton;
        import android.support.design.widget.Snackbar;
        import android.support.v7.app.AppCompatActivity;
        import android.support.v7.widget.Toolbar;
        import android.view.View;
        import android.view.Menu;
        import android.view.MenuItem;
        import android.widget.ArrayAdapter;
        import android.widget.ListView;
    
        import java.util.ArrayList;
    
        public class MainActivity extends AppCompatActivity {
    
            //FIRST LISTVIEW
            ListView lv;
            ArrayList spacecrafts=new ArrayList();
    
            @Override
            protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_main);
                Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
                setSupportActionBar(toolbar);
    
                lv= (ListView) findViewById(R.id.firstLV);
                populateData();
                lv.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,spacecrafts));
    
                FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
                fab.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        lv.setAdapter(new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_list_item_1,new ArrayList<String>()));
                        sendData();
                    }
                });
            }
    
            //POPULATE SPACECRAFTS ARRAYLIST
            private void populateData()
            {
                spacecrafts.add("Casini");
                spacecrafts.add("Enterprise");
                spacecrafts.add("Spitzer");
                spacecrafts.add("Huygens");
                spacecrafts.add("WMAP");
                spacecrafts.add("Juno");
                spacecrafts.add("Kepler");
                spacecrafts.add("Apollo 15");
                spacecrafts.add("Challenger");
                spacecrafts.add("Discovery");
            }
    
            /*
            SET ARRAYLIST TO SPACECRAFTS COLLECTION CLASS
             */
            private SpacecraftsCollection getData()
            {
                SpacecraftsCollection spacecraftsCollection=new SpacecraftsCollection();
                spacecraftsCollection.setSpacecrafts(spacecrafts);
    
                return spacecraftsCollection;
            }
    
            /*
            SEND DATA TO SECOND ACTIVITY
             */
            private void sendData()
            {
                Intent i=new Intent(this,SecondActivity.class);
                i.putExtra("SPACECRAFTS",this.getData());
                startActivity(i);
            }
        }

    Download code here.




Share an Example

Share an Example

Browse
What is the capital of Egypt? ( Cairo )