Óscar Daniel Óscar Daniel - 5 months ago 17
Java Question

Send data between fragments in a pagerAdapter

Hello I am trying to send data between two fragments, (armarFragment to cocinaFragment) but I dont know how do it, because both are in the same Activity (tabsActivity) which implements a pagerAdaptar to show diferents fragments. Here I put my code. Thanks.


  1. tabsActivity.java (inside you can found the class pagerAdapter).

    public class tabsActivity extends AppCompatActivity {

    public MyFragmentPagerAdapter myFragmentPagerAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_tabs);

    android.support.v7.widget.Toolbar toolbar = (android.support.v7.widget.Toolbar) findViewById(R.id.appbar);
    setSupportActionBar(toolbar);
    getSupportActionBar().setTitle("Arma tu pizza");

    myFragmentPagerAdapter = new MyFragmentPagerAdapter(getSupportFragmentManager());

    ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
    viewPager.setAdapter(myFragmentPagerAdapter);

    TabLayout tabLayout = (TabLayout) findViewById(R.id.appbartabs);
    tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
    tabLayout.setupWithViewPager(viewPager);

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_login, menu);
    return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
    return true;
    }

    return super.onOptionsItemSelected(item);
    }/*__________________ NEW CLASS, PAGERADAPTAR ____________________*/


    public class MyFragmentPagerAdapter extends FragmentPagerAdapter {
    final int PAGE_COUNT = 4;
    String tabTitles[] =
    new String[] { "Inicio","Armar pizza","Cocina","Chef"};

    public MyFragmentPagerAdapter(FragmentManager fm) {
    super(fm);
    }

    @Override
    public int getCount() {
    return PAGE_COUNT;
    }

    @Override
    public Fragment getItem(int position) {

    Fragment f = null;

    switch(position) {
    case 0:
    f = inicioFragment.newInstance();
    break;
    case 1:
    f = armarFragment.newInstance();
    break;
    case 2:
    f = cocinaFragment.newInstance();
    break;
    case 3:
    f = chefFragment.newInstance();
    break;
    }
    return f;
    }

    @Override
    public CharSequence getPageTitle(int position) {
    // Generate title based on item position
    return tabTitles[position];
    }
    }}

  2. armarFregment.java (inside you can found a viewHolder but ignore that).

    public class armarFragment extends Fragment implements View.OnClickListener{

    View rootView;

    private RecyclerView recycler;
    private productoAdapter adapter;
    private RecyclerView.LayoutManager lManager;
    private EditText txtNombrePizza;

    private ArrayList<producto> productosSeleccionados;

    Button btnEnviarALaCocina;
    RadioButton pequeña;
    RadioButton mediana;
    RadioButton grande;


    public static armarFragment newInstance() {
    armarFragment fragment = new armarFragment();
    return fragment;
    }

    public armarFragment() {
    productosSeleccionados = new ArrayList<producto>();
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    rootView = inflater.inflate(R.layout.fragment_armar, container, false);

    ArrayList<producto> items = new ArrayList<producto>();

    items.add(new producto(R.drawable.jamon, "Jamón", "¡Pssst!, sabe muy bien en pizzas dulces.", 2000));
    items.add(new producto(R.drawable.pollo, "Pollo","¡Pssst!, combina con TODO.",1500));
    items.add(new producto(R.drawable.queso, "Queso","Delicioso queso mozzarela, ¡Yummy Yummy!",2000));
    items.add(new producto(R.drawable.champinones, "Champiñones","Suculentos champiñones equixitos y suaves.",1500));
    items.add(new producto(R.drawable.peperoni, "Pepperoni","Fresco pepperoni con un toque de picante.",3000));
    items.add(new producto(R.drawable.pina, "Piña","¡Fresca y jugosa piña Colombiana papá!",1500));
    items.add(new producto(R.drawable.pasas, "Ciruelas pasas","Las más negritas y a la vez las más dulces.",1500));
    items.add(new producto(R.drawable.salami, "Salami","Delicioso salami en rodajitas así como el salchichon cervecero.",3000));
    items.add(new producto(R.drawable.chorizo, "Chorizo","¡Choricito santarrosano ome!",3000));
    items.add(new producto(R.drawable.cebolla, "Cebolla","La que ha hecho llorar a mas de uno, fresca y suave al paladar",1000));
    items.add(new producto(R.drawable.carnemolida, "Carne molida","Ideal para los arriesgados; fresca y deliciosa.",2500));
    items.add(new producto(R.drawable.pimenton, "Pimentón","Uno de los más enojados; crujiente y exquisito.",1000));
    items.add(new producto(R.drawable.tomate, "Tomate", "Otro rojo más; cosechados en nuestra tierrita.", 1000));
    items.add(new producto(R.drawable.maiz, "Maíz tierno","Se dice por ahi que el maíz es el más tierno",1000));
    items.add(new producto(R.drawable.jalapeno, "Jalapeño", "Si la cebolla te hace lorar imaginate este.", 2000));
    items.add(new producto(R.drawable.tocineta, "Tocineta","Deiciosa tocineta; ideal en pizzas de sal.",500));
    items.add(new producto(R.drawable.aceituna, "Aceituna", "Suaves y jugosas aceitunas, ideales para pizzas con proteinas.", 1000));
    items.add(new producto(R.drawable.oregano, "Orégano","El toque de sabor que nunca ha de faltar.",300));
    items.add(new producto(R.drawable.salsabbq, "Salsa BBQ", "La salsa ideal para pizzas de sal.", 500));

    recycler = (RecyclerView) rootView.findViewById(R.id.reciclador);
    recycler.setHasFixedSize(true);

    btnEnviarALaCocina = (Button) rootView.findViewById(R.id.btnEnviarALaCocina);
    btnEnviarALaCocina.setOnClickListener(this);

    txtNombrePizza = (EditText) rootView.findViewById(R.id.setNombrePizza);

    pequeña = (RadioButton) rootView.findViewById(R.id.radioPersonal);
    pequeña.setOnClickListener(this);
    mediana = (RadioButton) rootView.findViewById(R.id.radioMediana);
    mediana.setOnClickListener(this);
    grande = (RadioButton) rootView.findViewById(R.id.radioGrande);
    grande.setOnClickListener(this);

    // Usar un administrador para LinearLayout
    lManager = new LinearLayoutManager(getContext());
    recycler.setLayoutManager(lManager);

    // Crear un nuevo adaptador
    adapter = new productoAdapter(items);

    recycler.setAdapter(adapter);

    recycler.setItemAnimator(new DefaultItemAnimator());

    return rootView;
    }

    @Override
    public void onClick(View v) {
    switch (v.getId()) {
    case R.id.btnEnviarALaCocina:

    String nombrePizza = txtNombrePizza.getText().toString();

    productosSeleccionados = adapter.getProductosSeleccionados();

    Log.i("prueba 1", "size: " + productosSeleccionados.size());

    ArrayList<String> nombreProductos = new ArrayList<String>();
    ArrayList<Integer> precioProductos = new ArrayList<Integer>();

    for(producto p: productosSeleccionados){
    nombreProductos.add(p.getNombre());
    precioProductos.add(p.getPrecio());
    }

    if(productosSeleccionados.size() == 0){

    Toast.makeText(getContext(), "Debes seleccionar ingredientes.",
    Toast.LENGTH_LONG).show();

    }else if(nombrePizza.matches("")) {

    Toast.makeText(getContext(), "Debes ponerle un nombre a la pizza.",
    Toast.LENGTH_LONG).show();
    }else if(pequeña.isChecked() == false && mediana.isChecked() == false && grande.isChecked() == false){

    Toast.makeText(getContext(), "Debes selecionar un tamaño.",
    Toast.LENGTH_LONG).show();
    }

    break;
    }
    }

    /*______________________________________________________________________________________________
    NEW CLASS, PRODUCTOVIEWHOLDER
    _______________________________________________________________________________________________*/

    public class productoAdapter extends RecyclerView.Adapter<productoAdapter.productoViewHolder> {

    private ArrayList<producto> productosSeleccionados;
    private ArrayList<producto> productos;

    public class productoViewHolder extends RecyclerView.ViewHolder {

    // Campos respectivos de un item
    public ImageView imgProducto;
    public TextView txtNombre, txtDescripcion, txtPrecio;
    public Button btnAgregar;

    public productoViewHolder(View v) {
    super(v);
    imgProducto = (ImageView) v.findViewById(R.id.imgProducto);
    txtNombre = (TextView) v.findViewById(R.id.txtNombre);
    txtDescripcion = (TextView) v.findViewById(R.id.txtDescripcion);
    txtPrecio = (TextView) v.findViewById(R.id.txtPrecio);
    btnAgregar = (Button) v.findViewById(R.id.btnAgregar);
    }
    }

    public productoAdapter(ArrayList<producto> items) {
    productosSeleccionados = new ArrayList<producto>();
    this.productos = items;
    }


    public ArrayList<producto> getProductosSeleccionados(){
    return productosSeleccionados;
    }

    public int getItemCount() {
    return productos.size();
    }

    public productoViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
    View v = LayoutInflater.from(viewGroup.getContext())
    .inflate(R.layout.card_productos, viewGroup, false);

    return new productoViewHolder(v);
    }

    public void onBindViewHolder(productoViewHolder viewHolder, final int i) {
    viewHolder.imgProducto.setImageResource(productos.get(i).getImagen());
    viewHolder.txtNombre.setText(productos.get(i).getNombre());
    viewHolder.txtDescripcion.setText(productos.get(i).getDescripion());
    viewHolder.txtPrecio.setText("$ " + String.valueOf(productos.get(i).getPrecio()));
    viewHolder.btnAgregar.setOnClickListener(new View.OnClickListener(){

    @Override
    public void onClick(View v) {
    productosSeleccionados.add(productos.get(i));

    }
    });
    }
    }}

  3. cocinaFrgment.java (inside you can found a viewHolder but ignore that).



public class cocinaFragment extends Fragment {

View rootView;

private RecyclerView recycler;
private RecyclerView.Adapter adapter;
private RecyclerView.LayoutManager lManager;

ArrayList<pizza> items;

public static cocinaFragment newInstance() {
cocinaFragment fragment = new cocinaFragment();
return fragment;
}

public cocinaFragment() {
items = new ArrayList<pizza>();
}

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_cocina, container, false);


recycler = (RecyclerView) rootView.findViewById(R.id.reciclador);
recycler.setHasFixedSize(true);

// Usar un administrador para LinearLayout
lManager = new LinearLayoutManager(getContext());
recycler.setLayoutManager(lManager);

// Crear un nuevo adaptador
adapter = new pizzaAdapter(items);
recycler.setAdapter(adapter);

return rootView;
}


/*______________________________________________________________________________________________
NEW CLASS, PIZZAVIEWHOLDER
_______________________________________________________________________________________________*/

public class pizzaAdapter extends RecyclerView.Adapter<pizzaAdapter.pizzaViewHolder> implements View
.OnClickListener{
private ArrayList<pizza> pizzas;

private View.OnClickListener listener;

public class pizzaViewHolder extends RecyclerView.ViewHolder {
// Campos respectivos de un item
public TextView txtNombrePizza, txtTamaño, txtIngredientes, txtPrecio;

public pizzaViewHolder(View v) {
super(v);
txtNombrePizza = (TextView) v.findViewById(R.id.txtNombrePizza);
txtTamaño = (TextView) v.findViewById(R.id.txtTamaño);
txtIngredientes = (TextView) v.findViewById(R.id.txtIngredientes);
txtPrecio = (TextView) v.findViewById(R.id.txtPrecio);
}
}

public pizzaAdapter(ArrayList<pizza> items) {
this.pizzas = items;
}


public int getItemCount() {
return pizzas.size();
}


public pizzaViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.card_pizzas, viewGroup, false);

v.setOnClickListener(this);

return new pizzaViewHolder(v);
}

public void setOnClickListener(View.OnClickListener listener) {
this.listener = listener;
}

@Override
public void onClick(View view) {
if(listener != null)
listener.onClick(view);
}



public void onBindViewHolder(pizzaViewHolder viewHolder, int i) {
viewHolder.txtNombrePizza.setText(pizzas.get(i).getNombre());
viewHolder.txtTamaño.setText(pizzas.get(i).getTamaño());
viewHolder.txtIngredientes.setText(pizzas.get(i).getIngredientes());
viewHolder.txtPrecio.setText("$ " + String.valueOf(pizzas.get(i).getPrecio()));
}
}


}

Answer

Ok, as android guidelines says, you must create an interface in your fragment. For example:

public class armarFragment extends Fragment implements View.OnClickListener{
    ...
    private armarFragmentListener mListener;

    public interface armarFragmentListener {
        void onEnviar ();
    }

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
    try {
        mListener = (armarFragmentListener) activity;
    } catch (ClassCastException e) {
        throw new ClassCastException(activity.toString()
                + " must implement armarFragmentListener ");
    }
}

@Override
public void onClick(View v) {
    switch (v.getId()) {
        case R.id.btnEnviarALaCocina:
            //Do what you want.
            mListener.onEnviar(/*Change interface to pass arguments if you want*/);
        break;
    }
}

Your activity must implements that interface and do what corresponds, for example call the methods of the fragment to get the data. When you have the data you can pass it to the new fragment as arguments or otherwise.

When you create a blank fragment in android studio it put that structure on the class by default. Create a new blank fragment and take a look at it.

Comments