0

This is my Parent Activity containing a tab layout and view pager and a button at the bottom:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    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:orientation="vertical"
    tools:context=".module.addcontact.AddContactActivity">

    <com.google.android.material.appbar.AppBarLayout
        android:layout_height="wrap_content"
        android:layout_width="match_parent"
        android:theme="@style/AppTheme.PopupOverlay">

        <com.google.android.material.tabs.TabLayout
            android:id="@+id/tabs"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:tabTextColor="@color/colorDarkBlue"
            app:tabSelectedTextColor="@color/colorDarkBlue"
            android:background="@color/white"/>
    </com.google.android.material.appbar.AppBarLayout>

    <androidx.viewpager.widget.ViewPager
        android:id="@+id/view_pager"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        app:layout_behavior="@string/appbar_scrolling_view_behavior" />

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/save"
        android:text="SAVE"
        android:textSize="16sp"
        android:textStyle="bold"
        android:textColor="@color/white"
        android:layout_margin="10dp"
        android:background="@color/colorDarkBlue"/>

</LinearLayout>

Fragments 1:

<?xml version="1.0" encoding="utf-8"?>
<ScrollView
    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:orientation="vertical"
    android:gravity="center_horizontal"
    android:fillViewport="true"
    android:padding="@dimen/add_contacts_padding"
    tools:context=".module.addcompany.AddCompanyFragment">

    <TableLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:stretchColumns="1">

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/name"
        android:hint="Name"
        android:textSize="24sp"
        android:padding="10dp"
        android:layout_marginBottom="10dp"
        android:background="@drawable/edit_text_border"/>

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/phone"
        android:hint="Phone"
        android:inputType="phone"
        android:textSize="24sp"
        android:padding="10dp"
        android:layout_marginBottom="10dp"
        android:background="@drawable/edit_text_border"/>

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/address"
        android:hint="Address"
        android:textSize="24sp"
        android:padding="10dp"
        android:layout_marginBottom="10dp"
        android:background="@drawable/edit_text_border"/>

    </TableLayout>

</ScrollView>

Fragment 2 is similar to fragment 1 (with different edit texts e.g. designation and email)

When save button in my parent activity gets pressed, I want to get all the data from both of these fragments in parent activity and if some field is missing then i want to set error to that field.

How can i get data from fragments to the parent activity? Or Is there some way that i can get all the edit texts (fields) of the fragments in the parent activity?

Asad Rehman
  • 422
  • 2
  • 11
  • Where are you including the `Fragment`'s layout inside the `Activity`'s layout file? – Stelios Papamichail Sep 20 '19 at 11:39
  • Possible duplicate of [Passing data between a fragment and its container activity](https://stackoverflow.com/questions/9343241/passing-data-between-a-fragment-and-its-container-activity) – Jagar Sep 20 '19 at 11:41
  • 1
    Sir @SteliosPapamichail I am attaching my fragments with the viewpager in java code – Asad Rehman Sep 20 '19 at 11:41
  • 2
    You have already instance of all fragments when activity launched. Now you have to create method in your fragments for accessing data and also make validation method in fragments and call that methods in parent activity using the instance of current selected fragment because you have already instance of fragment. You don't need to create instance of fragment again. – Piyush Sep 20 '19 at 11:42
  • Sir @Piyush i am newbie in android. can you please write the code line to access fragment stance? – Asad Rehman Sep 20 '19 at 11:44
  • @Jagar The link that you provide is giving information of getting access to activity in the fragment but i want the fragment access in the activity – Asad Rehman Sep 20 '19 at 11:47
  • I facing the same issue , can you show me how you solve it exactly! I would really appreciate it – rav Dec 02 '19 at 19:20
  • @Piyush You are saying "using the instance of current selected fragment" But I have 3 tabs as fragments so only one of them will be currently visible or selected but when save button clicked I want to get the data for all the fragments not just the visible one. How to do it? – rav Dec 02 '19 at 19:24

2 Answers2

2

As per your requirement you have to create you have parent activity that means your fragments are loaded using viewpager so you have the instance of each fragment.

Now while you click the button from activity, to check the validation of individual fragment and accessing data you can do this.

First check that which fragment is on which position which will be the position from onPageSelected method of view pager.

Now suppose you have Fragment1 and you want to access data and validate it. Use,

Fragment1 f1= (Fragment1) viewPager
                .getAdapter()
                .instantiateItem(viewPager, position);

Now you need to create validate() method in Fragment1 so you can access that method by,

f1.validate();

Before you call f1.validate(); check that if(f1!=null) && f1.isVisible() and then access data from it and do same for Fragment2.

Piyush
  • 18,895
  • 5
  • 32
  • 63
0

To allow a Fragment to communicate up to its Activity, you can define an interface in the Fragment class and implement it within the Activity.

Here is an example of Fragment to Activity communication:

public class HeadlinesFragment extends ListFragment {
    OnHeadlineSelectedListener callback;

    public void setOnHeadlineSelectedListener(OnHeadlineSelectedListener callback) {
        this.callback = callback;
    }

    // This interface can be implemented by the Activity, parent Fragment,
    // or a separate test implementation.
    public interface OnHeadlineSelectedListener {
        public void onArticleSelected(int position);
    }

    // ...
}

MainActivity

public static class MainActivity extends Activity
        implements HeadlinesFragment.OnHeadlineSelectedListener{


    @Override
    public void onAttachFragment(Fragment fragment) {
        if (fragment instanceof HeadlinesFragment) {
            HeadlinesFragment headlinesFragment = (HeadlinesFragment) fragment;
            headlinesFragment.setOnHeadlineSelectedListener(this);
        }
    }
}

For example, the following method in the fragment is called when the user clicks on a list item. The fragment uses the callback interface to deliver the event to the parent activity.

@Override
public void onListItemClick(ListView l, View v, int position, long id) {
    // Send the event to the host activity
    callback.onArticleSelected(position);
}

Hope it works for you.

Muazzam A.
  • 647
  • 5
  • 17
  • this is one sided bro, activity will get notified because activity is listening to callbacks. but according to question he wants to notify fragment when user click button on activity. – vikas kumar Sep 20 '19 at 11:54
  • @vikaskumar he said in the question "How can i get data from fragments to the parent activity?" and in question title "How to get data from fragments in the parent activity?" – Muazzam A. Sep 20 '19 at 11:57
  • ok, but according to this some one has to push data from fragment but the button is in activity. – vikas kumar Sep 20 '19 at 11:59
  • @vikaskumar I will update the answer for Activity to fragment communication in a while. – Muazzam A. Sep 20 '19 at 12:00
  • The answer above solved my problem but thanks a lot to try to help me out. – Asad Rehman Sep 20 '19 at 12:02