Android Data Passing - Fragment To Activity Via Intent

android data passing

Lets continue with our android data passing series we had started earlier on.We had looked at how to pass data from activity to fragment and how to pass both a list/object from activity to activity as well as simple primitive data types.

Today we look at how to pass simple data types from the fragment to activity.We pass data via Intent object.  

Pass Data Demo

What is a Fragment?

A fragment is a subactivity with it's own lifecycle. Fragments get hosted by activities. One activity can host multiple fragments.

Why Pass Data From Fragment To Activity

No. Reason
1. Fragments are subactivities and allow us have different screens without necessarily having to create many activities. Hence we need to know how to pass data from the fragment to an activity.
2. Fragments like Activities are special UI classes representing a window and so we cannot pass data directly like we do with ordinary classes.

Introduction

  • We have two classes : one our MainActivity and another a MyFragment class.
  • When we press the FAB(Floating Action Button) button,we open the MyFragment via Fragment Transaction,attaching it to a FrameLayout we shall define.
  • The Fragment contains an edittext and a spinner.
  • User types the spacecraft name and chooses the launch year in the spinner.
  • We then pass both these data back to MainActivity.
  • Then display the received data in textviews.
  • 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 fragment to an activity.
  • How do I pass data between fragment and activity using intents.
  • How do I perform FragmentTransaction.
  • Override onResume() and receive data in android.
  • How to work with both fragment and activity.

Tools Used

  • IDE : Android Studio
  • OS : Windows 8.1
  • PLATFORM : Android
  • LANGUAGE : Java
  • TOPIC : Intent,Data Passing,Fragment

Let's go.

Lets have a look at the source code.

1. Build.Gradle

  • Here's our app level(Located in the app folder) build.gradle.
  • No external dependencies. You can use later versions of support libraries than us.
dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:25.2.0'
    compile 'com.android.support:design:25.2.0'
    compile 'com.android.support:support-v4:25.2.0'
    compile 'com.android.support:cardview-v7:25.2.0'

}

2. MainActivity.java

  • Our MainActivity,launcher activity.
  • First we reference views here,in this case simple textviews to display our received data.
  • We have a method : receiveData() thats responsible for receiving and unpacking the data we receive from the MyFragment class.
  • We shall be receiving data in the onResume() method.
  • Because the methods gets called not only when we resume from the fragment but also after the activity has been created and started,we will need to identify the caller using a simple Sender string we shall be sending everytime we send data from the fragment.
  • If the sender is MyFragment ,then we go ahead and unpack our data.
package com.tutorials.hp.datafragment_activity;

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.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    private TextView nameTxt,yearTxt;

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

    //REFERENCE VIEWS
        nameTxt= (TextView) findViewById(R.id.nameTxt);
        yearTxt= (TextView) findViewById(R.id.yearTxt);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
              openFragment();
            }
        });
    }
/*
WHEN ACTIVITY RESUMES
*/
    @Override
    protected void onResume() {
        super.onResume();

    //DETERMINE WHO STARTED THIS ACTIVITY
    final String sender=this.getIntent().getExtras().getString("SENDER_KEY");

    //IF ITS THE FRAGMENT THEN RECEIVE DATA
        if(sender != null)
        {
            this.receiveData();
            Toast.makeText(this, "Received", Toast.LENGTH_SHORT).show();

        }
    }

    /*
        OPEN FRAGMENT
         */
    private void openFragment()
    {
        //PASS OVER THE BUNDLE TO OUR FRAGMENT
        MyFragment myFragment = new MyFragment();
        //THEN NOW SHOW OUR FRAGMENT
        getSupportFragmentManager().beginTransaction().replace(R.id.container,myFragment).commit();
    }

    /*
    RECEIVE DATA FROM FRAGMENT
     */
    private void receiveData()
    {
        //RECEIVE DATA VIA INTENT
        Intent i = getIntent();
        String name = i.getStringExtra("NAME_KEY");
        int year = i.getIntExtra("YEAR_KEY",0);

        //SET DATA TO TEXTVIEWS
        nameTxt.setText(name);
        yearTxt.setText(String.valueOf(year));
    }
}

3. MyFragment.java

  • Our Fragment class.
  • We are using support libary Fragment so we Extend android.support.v4.app.Fragment.
  • Here we have an edittext,a button and a spinner.
  • User shall enter the spacecraft name in edittext,select launch year in the spinner and click send button to send that data to MainActivity.
  • We send and pack data in an intent.
  • We also send a variable we call sender to identify the sender of that data as this fragment.
package com.tutorials.hp.datafragment_activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;

/
 * A simple Fragment subclass.
 */
public class MyFragment extends Fragment {

    private EditText nameFragTxt;
    private Spinner launchYearSpinner;
    private Button sendBtn;

    public MyFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        // Inflate the layout for this fragment
        View rootView=inflater.inflate(R.layout.fragment_my, container, false);

        //INITIALIZE VIEWS
        nameFragTxt = (EditText)rootView.findViewById(R.id.nameEditTxt);
        launchYearSpinner = (Spinner)rootView.findViewById(R.id.sp);
        sendBtn = (Button) rootView.findViewById(R.id.sendBtn);

        fillYears();

        sendBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                sendData();
            }
        });

        return rootView;
    }
    /*
    FILL YEARS IN OUR SPINNER
    */
    private void fillYears() {
        ArrayAdapter adapter = new ArrayAdapter(getActivity(), android.R.layout.simple_list_item_1);
        adapter.add("2017");
        adapter.add("2018");
        adapter.add("2019");
        adapter.add("2020");
        adapter.add("2021");
        adapter.add("2022");

        //SET ADAPTER INSTANCE TO OUR SPINNER
        launchYearSpinner.setAdapter(adapter);

    }

    private void sendData()
    {
        //INTENT OBJ
        Intent i = new Intent(getActivity().getBaseContext(),
                MainActivity.class);

        //PACK DATA
    i.putExtra("SENDER_KEY", "MyFragment");
        i.putExtra("NAME_KEY", nameFragTxt.getText().toString());
        i.putExtra("YEAR_KEY", Integer.valueOf(launchYearSpinner.getSelectedItem().toString()));

        //RESET WIDGETS
        nameFragTxt.setText("");
        launchYearSpinner.setSelection(0);

        //START ACTIVITY
        getActivity().startActivity(i);
    }
}

4. Create User Interfaces

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

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.
  • This layout shall get inflated into our MainActivity interface.
  • Is the contentmain.xml layout in our project.
<?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.datafragment_activity.MainActivity"
    tools:showIn="@layout/activity_main">

    <LinearLayout
        android:layout_width="match_parent"
        android:orientation="vertical"
        android:layout_height="match_parent">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="Received Data"
        android:id="@+id/activityTitle"
        android:textStyle="bold"
        android:textColor="@color/colorAccent"
        android:layout_gravity="center_horizontal"
        android:padding="5dp"
        />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="Name"
        android:id="@+id/nameTxt"
        android:padding="5dp"
        />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="Year"
        android:id="@+id/yearTxt"
        android:padding="5dp"
        />

    <FrameLayout
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

    </FrameLayout>

    </LinearLayout>
</RelativeLayout>

(c). MyFragment Layout

  • Layout for our Fragment class.
  • Contains a CardView with an edittext and a spinner.
  • Is the fragment_my.xml layout in our project

 

<FrameLayout 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"
    tools:context="com.tutorials.hp.datafragment_activity.MyFragment">
    <android.support.v7.widget.CardView
        android:orientation="horizontal"
        android:layout_width="match_parent"
        xmlns:card_view="http://schemas.android.com/apk/res-auto"
        android:layout_margin="5dp"
        card_view:cardCornerRadius="10dp"
        card_view:cardElevation="5dp"
        android:layout_height="300dp">

        <LinearLayout
            android:orientation="vertical"
            android:layout_width="match_parent"
            android:layout_height="match_parent">
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textAppearance="?android:attr/textAppearanceLarge"
                android:text="FRAGMENT ONE"
                android:id="@+id/fragTitle"
                android:textStyle="bold"
                android:textColor="@color/colorAccent"
                android:layout_gravity="center_horizontal"
                android:padding="5dp"
                />

            <android.support.design.widget.TextInputLayout
                android:id="@+id/nameLayout"
                android:layout_width="match_parent"
                android:layout_height="wrap_content">

                <EditText
                    android:id="@+id/nameEditTxt"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:singleLine="true"
                    android:hint= "Name" />
            </android.support.design.widget.TextInputLayout>

            <LinearLayout
                android:layout_width="match_parent"
                android:orientation="horizontal"
                android:layout_height="wrap_content">
                <TextView
                    android:text="LAUNCH YEAR : "
                    android:textColor="@color/colorAccent"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content" />
                <Spinner
                    android:id="@+id/sp"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    />
            </LinearLayout>

            <Button
                android:id="@+id/sendBtn"
        android:text="Send"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"             />
        </LinearLayout>
    </android.support.v7.widget.CardView>
</FrameLayout>

How To Run

  • Download the project above.
  • You'll get a zipped file,extract it.
  • Open the Android Studio.
  • Now close, any already opened 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

Best Regards, Oclemy.

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


Previous Post Next Post