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.
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 aMyFragment
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 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 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 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" 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 |