Android Programming

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