Android Data Passing : ListView to ListView

android data passing

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
First Activity

Activity 2
Second Activity

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 xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        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 xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        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 xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        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.

How do You Feel after reading this?

According to scientists, we humans have 8 primary innate emotions: joy, acceptance, fear, surprise, sadness, disgust, anger, and anticipation. Feel free to tell us how you feel about this article using these emotes or via the comment section. This feedback helps us gauge our progress.

Help me Grow.

I set myself some growth ambitions I desire to achieve by this year's end regarding this website and my youtube channel. Am halfway. Help me reach them by:




Recommendations


What do You Think

Dear readers drop us your comments below. We are building a community of students and learners. Start by dropping us your suggestions below. What tutorials do you want us to do for example? Where can we improve? What are some awesome resources out there? Do you have any code you want to share with us?
By the way that example or snippet you have lying in your computer can really help beginner programmers. We can share it here with other students.

Previous Post Next Post