sunny
sunny

Reputation: 179

How to get data from two different fragments in tabs to main activity

I want to know how to get data from 2 different fragments inside tab layout.

For example: In this image there two tabs tab1 and tab2 both have different values stored in edit text .

tab1 helloooooo, tab2 hiiiiiii

and i have a button available in main activity which is used for getting the data from both tabs in same time.

Now my Problem is How i can get the data from both tabs at same time when user click on the

get data button

enter image description here

Upvotes: 2

Views: 2659

Answers (7)

frans eilering
frans eilering

Reputation: 499

Each tab has an EditText with an id

in tab1.xml it's edit1

<EditText
        android:id="@+id/edit1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

and it's edit2 in tab2.xml

<EditText
    android:id="@+id/edit2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"/>

tab1.xml and tab2.xml also has a button which can be clicked. It has the same id if you want on tab1 and tab2.

  <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/knop"
        android:onClick="klik"/>

The item that matters is the OnClick. It point to a piece of code which must be implemented in the MainActivity.java code

public void klik(View v){
    alert("Just an alert.");
    String val1 = ((EditText) findViewById(R.id.edit1)).getText().toString(); 
    String val2 = ((EditText) findViewById(R.id.edit2)).getText().toString(); 
    alert(val1);
    alert(val2);
    alert(val1 + val2);
}

At last the alert routine

private void alert(String message){ //mies
    AlertDialog alertDialog = new AlertDialog.Builder(this).create();
    alertDialog.setTitle("Alert");
    alertDialog.setMessage(message);
    alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });
    alertDialog.show();
 }

In fact the fragments can be treated as one page. You can retrieve the information from each field by id from the calling main page, in this case MainActivity.java.

Upvotes: 0

Pavneet_Singh
Pavneet_Singh

Reputation: 37414

1.) Keep a reference of your fragment in your activity.

 public class Activity extends AppCompatActivity  {
      private yourFargment frag1,frag2;
    }

2.) Get the object reference into your reference variables in Adapter's getItem().

@Override
public Fragment getItem(int index) {
    switch (index) {
        case 0:
            frag1 = yourFargment.newInstance(index);
//frag1 =new yourFargment (); can also be used

            return frag1;
        case 1:
            frag2 = yourFargment.newInstance(index);
            return frag2;
    }
    return null;
}

3.) Inside your onClick you can simply get those values from edittext.

onClick(View..){
String val1 = frag1.edittext1.getText().toString(); // Note: make your `edittext` public
String val2 = frag2.edittext2.getText().toString();

or

String val1 = frag1.getData();
String val2 = frag2.getData();
}

where getData is a public method inside your fragment

    public class yourFragment..{
      public String getData(){
       return edittext.getText().toString();
       // Note: with this no need to make your `edittext` public 
    }
}

Upvotes: 3

Kuldeep Kulkarni
Kuldeep Kulkarni

Reputation: 796

You can use like this way:

Bundle bundle = new Bundle();
bundle = getActivity().getIntent().getExtras();
YourFragment fragment = new YourFragment();
bundle.putString("yourKey", yourValue);
fragment.setArguments(bundle);

Then you can get them in your second fragment

in onCreateView

if (getArguments() != null) 
{
  mParam1 = getArguments().getString("yourKey");  
}

Upvotes: 1

topcbl
topcbl

Reputation: 849

Tablayout only contains TabItems not Fragment. So, I believe that you use TabLayout combines with ViewPager, which actually contains 2 different Fragments. I suppose maybe you want to getData() at the Activity from 2 Fragments. At this point, you can easily Fragment callback the Activity and provide data just like getData(). The code will look like

In Fragment

public class BaseFragment extends Fragment {
    protected DataCallback mCallback;

    @Override public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof DataCallback) {
            mCallback = (DataCallback) context;
        }
    }

    //some place fragment affect to data
    private void someFunction() {
        mCallback.updateDataToActivity(data);
    }
}

In Activity

public class MyActivity extends BaseActivity implements DataCallback {

    T data;
    public void updateDataToActivity(T data) {
        this.data = data
    }

    // This is your getData function
    private T getData() {
        return data;
    } 
}

And DataCallback

public interface DataCallback {
    void updateDataToActivity(T data);
}

Upvotes: 1

Rahul Sharma
Rahul Sharma

Reputation: 13633

At the time when you are settings fragment in tabs you have 2 objects of those fragments. By using those objects, you can retrieve the value from your fragments. Write following code into your MainActivity e.g.

if(tab1fragment != null) {
  String text = tab1fragment.getData();
}

and in Fragment, create a method like

public String getData(){
 return edittext.getString().toString();
}

This way you can retrieve the data from fragments.

Upvotes: 1

Priyank Patel
Priyank Patel

Reputation: 12362

Take member object of both Fragment in your activity..

FirstFragment mFirstFragment;
SecondFragment mSecondFragment;

Create instance of both in getItem(int position) method of ViewPagerAdapter.

    @Override
    public Fragment getItem(int position) {
        // instantiate the fragment for the given page.

        switch (position) {
        case 0:
            if (null == mFirstFragment) {
                mFirstFragment = FirstFragment.newInstance(); 
            }
            return mFirstFragment;
        case 1:
            if( null == mSecondFragment ) {
                mSecondFragment = SecondFragment.newInstance();
            }
            return mSecondFragment;         
        }   

        return null;

    }

Call getData method of both Fragment when button clicked from activity.

@Override
public void onClick(View v) {

    switch (v.getId()) {
       case R.id.button1:
             // Get data and use it as you want.
             mFirstFragment.getData();
             mSecondFragment.getData();
        break;
    }
}

Upvotes: 2

Sigma
Sigma

Reputation: 542

You can use data bus library like Otto : http://square.github.io/otto/

Or Rxjava : https://github.com/ReactiveX/RxJava

Both of these libraries are made for propagate data between classes.

Upvotes: 0

Related Questions