Android Data Passing - From TextBox To Second Activity

android data passing

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.

Pass Data Between Activities

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. New Project Dialog
  3. Choose minimum SDK. Choose minimum SDK
  4. You can choose Empty activity or Basic Activity. Both are starter templates provided by android studio. Choose Empty Activity
  5. Click Finish. 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. Choose Basic 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.

Components tree

Here's our activity_main.xml layout.

    <?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.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 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.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 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.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

Best Regards.

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


Next Post