Achuthan M
Achuthan M

Reputation: 349

How to pass values between fragments while using a viewpager in android

I am creating a sign up form which has been divided into three fragments.The three fragments are connected by a viewpager.I can traverse throught the fragments with next and previous buttons.I want the data from the first and second fragment to be available in the third fragment.One option is to use sharedpreferences.Is there any other approach.

The main class:

package pl.looksok.viewpagerdemo;

import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;

public class MainActivity extends FragmentActivity {
    ViewPager pager;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        MyPagerAdapter pageAdapter = new MyPagerAdapter(getSupportFragmentManager());
         pager = (ViewPager)findViewById(R.id.myViewPager);
        pager.setAdapter(pageAdapter);



    }
    public void selectFragment(int position){
    pager.setCurrentItem(position, true); 
    // true is to animate the transaction
    }
}

The main xml

<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"
    tools:context=".MainActivity" >

    <pl.looksok.viewpagerdemo.CustomViewPager
        android:id="@+id/myViewPager"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</RelativeLayout>

The first fragment:

package pl.looksok.viewpagerdemo;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;

public class FragmentBlue extends Fragment {
Button btnnext1;
RelativeLayout frag1;

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

        View view = inflater.inflate(R.layout.fragment_blue, container, false);
        btnnext1=(Button) view.findViewById(R.id.btnnext1);
        frag1=(RelativeLayout) view.findViewById(R.id.frag1);

        btnnext1.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View view) {


                ((MainActivity)getActivity()).selectFragment(1);
            }
        });

        return view;
    }
}

The first xml:

<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:background="#4ECDC4"
    android:id="@+id/frag1"
    >

<Button
    android:id="@+id/btnnext1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_centerHorizontal="true"
    android:text="NEXT" />

<EditText
    android:id="@+id/txtfname"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@+id/txtmname"
    android:layout_alignParentTop="true"
    android:ems="10"
    android:hint="FIRST NAME" >

    <requestFocus />
</EditText>

<EditText
    android:id="@+id/txtmname"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/txtfname"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="24dp"
    android:ems="10"
    android:hint="MIDDLE NAME" />

<EditText
    android:id="@+id/txtlname"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@+id/txtmname"
    android:layout_below="@+id/txtmname"
    android:layout_marginTop="23dp"
    android:ems="10"
    android:hint="LAST NAME" />

<EditText
    android:id="@+id/txtdob"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@+id/txtlname"
    android:layout_centerVertical="true"
    android:ems="10"
    android:hint="DOB" />

</RelativeLayout>

The second fragment:

package pl.looksok.viewpagerdemo;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;

public class FragmentGreen extends Fragment {
Button btnnext2,btnprev2;
RelativeLayout frag2;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_green, container, false);
        btnnext2=(Button) view.findViewById(R.id.btnnext2);
        btnprev2=(Button) view.findViewById(R.id.btnprev2);
        frag2=(RelativeLayout) view.findViewById(R.id.frag2);
        btnnext2.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View view) {


                ((MainActivity)getActivity()).selectFragment(2);

            }
        });
        btnprev2.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                ((MainActivity)getActivity()).selectFragment(0);

            }
        });
        return view;
    }
}

The second fragment's xml:

<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:background="#C7F464"
    android:id="@+id/frag2"
    >
<Button
    android:id="@+id/btnnext2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_alignParentRight="true"
    android:layout_marginRight="60dp"
    android:text="NEXT" />

<Button
    android:id="@+id/btnprev2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_marginRight="68dp"
    android:layout_toLeftOf="@+id/btnnext2"
    android:text="PREV" />

<EditText
    android:id="@+id/txtgender"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_alignRight="@+id/btnnext2"
    android:ems="10"
    android:hint="GENDER" />

<EditText
    android:id="@+id/txtmaritalstatus"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@+id/txtgender"
    android:layout_below="@+id/txtgender"
    android:layout_marginTop="24dp"
    android:ems="10"
    android:hint="MARITAL STATUS" >

    <requestFocus />
</EditText>

<EditText
    android:id="@+id/txtoccupation"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@+id/txtmaritalstatus"
    android:layout_below="@+id/txtmaritalstatus"
    android:layout_marginTop="23dp"
    android:ems="10"
    android:hint="OCCUPATION" />

<EditText
    android:id="@+id/txtusername"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@+id/txtoccupation"
    android:layout_centerVertical="true"
    android:ems="10"
    android:hint="USERNAME" />

<EditText
    android:id="@+id/txtpassword"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/txtusername"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="40dp"
    android:ems="10"
    android:hint="PASSWORD"
    android:inputType="textPassword" />

</RelativeLayout>

The third fragment:

package pl.looksok.viewpagerdemo;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.support.v4.app.Fragment;

public class FragmentPink extends Fragment {
Button btnnext3,btnprev3;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_pink, container, false);
        btnnext3=(Button) view.findViewById(R.id.btnnext3);
        btnprev3=(Button) view.findViewById(R.id.btnprev3);
        btnnext3.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {


            }
        });
        btnprev3.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                ((MainActivity)getActivity()).selectFragment(1);

            }
        });
        return view;
    }
}

The third fragment's xml:

<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:background="#FF6B6B">

<Button
    android:id="@+id/btnnext3"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_centerHorizontal="true"
    android:text="NEXT" />
<Button
    android:id="@+id/btnprev3"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_centerHorizontal="true"
    android:text="PREV" />

<EditText
    android:id="@+id/txtaddress"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:ems="10"
    android:hint="ADDRESS" >

    <requestFocus />
</EditText>

<EditText
    android:id="@+id/txtdistrict"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@+id/txtaddress"
    android:layout_below="@+id/txtaddress"
    android:layout_marginTop="30dp"
    android:ems="10"
    android:hint="DISTRICT" />

<EditText
    android:id="@+id/txtstate"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/txtdistrict"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="41dp"
    android:ems="10"
    android:hint="STATE" />

<EditText
    android:id="@+id/txtpincode"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/txtstate"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="50dp"
    android:ems="10"
    android:hint="PINCODE" />

</RelativeLayout>

The adapter:

package pl.looksok.viewpagerdemo;

import java.util.ArrayList;
import java.util.List;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;

public class MyPagerAdapter extends FragmentPagerAdapter {

    private List<Fragment> fragments;

    public MyPagerAdapter(FragmentManager fm) {
        super(fm);
        this.fragments = new ArrayList<Fragment>();
        fragments.add(new FragmentBlue());
        fragments.add(new FragmentGreen());
        fragments.add(new FragmentPink());
    }

    @Override
    public Fragment getItem(int position) {
        return fragments.get(position);
    }

    @Override
    public int getCount() {
        return fragments.size();
    }
}

I also created a class which has string values.I was wondering if i could create an object and set the fields as properties for that object

The class with the fields:

package pl.looksok.viewpagerdemo;

import java.io.Serializable;

public class RegistrationValues implements Serializable {

    String fname;
    String mname;
    String lname;
    String dob;
    String gender;
    String marital_status;
    String occupation;
    String username;
    String password;
    String address;
    String district;
    String state;
    String pincode;
    String nationality;
    String email;
    String phno;
    String bank_acno;
    String bank_branch;
    String bank_ifsc;
    String bank_swift;

}

So the question is how to pass the values in the first and second fragment to the last fragment without using Sharedpreferences.

Upvotes: 1

Views: 882

Answers (3)

Sparky
Sparky

Reputation: 8477

A very common pattern is for the fragments to provide an interface by which values may be passed to them, and to use the containing activity as a hub. To see an example of this, use Eclipse or Android Studio to instantiate a new Master/Detail Flow activity and look at the code for the ListActivity.

But I would argue that in this case, you probably don't want to do that. Your data record looks like something you want to maintain in your persistence layer (Model), maybe mutate through a service (Controller) and pull up as needed into the fragment (View). Separate UI from business logic, and use an Adapter to keep the data in sync.

Upvotes: 0

xoxol_89
xoxol_89

Reputation: 1252

i think that for values passing between fragments you can use listener and dispatcher patterns and singleton pattern, which will manage listeners and dispatchers, because fragments are not Activities and you can't pass values via Intents.

Upvotes: 0

Sherif elKhatib
Sherif elKhatib

Reputation: 45942

The easy approach would be to let the RegistrationValues instance reside in your MainActivity instance:

public class MainActivity extends FragmentActivity {
    ViewPager pager;
    RegistrationValues values; //add this
    public RegistrationValues getValues() { //add this
        return values; //add this
    }; //add this

In your fragments, use ((MainActivity) getActivity()).getValues() to update the values and to actually get the values in the third fragment or so.

Note: You should probably save the values instance in your MainActivity's onSaveInstance and restore it in your MainActivity's onCreate.

Upvotes: 1

Related Questions