Communication between Fragmentes and Eventbus

Asked

Viewed 158 times

3

In my application I have 1 Activity, and in it using Slidingtablayout and a Tabsadapter, I’m calling 3 Fragments.

By clicking the save button, I want to recover the contents of the 3 Fragments, and I am using Eventbus for this, however:

If I click Save with Tab1 selected, it only returns data from tabs 1 and 2. If I click with tab 2 selected, it saves correctly from all tabs. If I click with Tab3, it only communicates to tab2 and Tab3.

What should I do to make it work on all tabs???

Tabsadapter

public class TabsAdapter extends FragmentStatePagerAdapter {
private Context mContext;
private int codigoEmpresa;
private String[] titles = {"DADOS", "ENDEREÇO", "CONTATOS"};

public TabsAdapter(FragmentManager fm, Context c, int cod) {
    super(fm);

    mContext = c;
    codigoEmpresa = cod;
}

@Override
public Fragment getItem(int position) {
    Fragment frag = null;

    if (position == 0){
        frag  = new DadosEmpresaFrag();
    }
    else if (position == 1) {
        frag = new EnderecoEmpresaFrag();
    }
    else if (position == 2){
        frag = new ContatosEmpresaFrag();
    }

    Bundle b = new Bundle();
    b.putInt("position", position);
    b.putInt("codigo", codigoEmpresa);

    frag.setArguments(b);

    return frag;
}

@Override
public int getCount() {
    return titles.length;
}

@Override
public CharSequence getPageTitle(int position) {
    return (titles[position]);
}
}

My Activity

public class CadastrarAlterarEmpresaActivity extends ActionBarActivity {
int codigoRecebido; 
Button btnSalvar;
BancoDAO bancoDAO;
EmpresaDAO empresaDAO;
Empresa empresa;
private Toolbar mToolbar;
TabsAdapter tabsAdapter;

private SlidingTabLayout mSlidingTabLayout;
private ViewPager mViewPager;

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

    mToolbar = (Toolbar) findViewById(R.id.tb_CadastroEmpresas);
    mToolbar.setTitle("Cadastrar Empresas");
    setSupportActionBar(mToolbar);

    Bundle extras = getIntent().getExtras();
    codigoRecebido = extras.getInt("codigo");

    //TABS
    mViewPager = (ViewPager) findViewById(R.id.vp_tabs);
    tabsAdapter = new TabsAdapter(getSupportFragmentManager(), this, codigoRecebido);
    mViewPager.setAdapter(tabsAdapter);
    mSlidingTabLayout = (SlidingTabLayout) findViewById(R.id.stl_tabs);
    mSlidingTabLayout.setDistributeEvenly(true); //deixa todas as abas com o mesmo tamanho
    mSlidingTabLayout.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
    mSlidingTabLayout.setSelectedIndicatorColors(getResources().getColor(R.color.colorAccent));
    mSlidingTabLayout.setViewPager(mViewPager);

    // EventBus register
    EventBus.getDefault().register(CadastrarAlterarEmpresaActivity.this);

    btnSalvar = (Button) findViewById(R.id.btnSalvarEmpresa);

    btnSalvar.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            empresa = new Empresa();

            chamaEmpresa();

            final int codigo = empresa.getIdEmpresa();
            final String nome = empresa.getNomeRazao();
            final String endereco = empresa.getRua();
            final int telefone1 = empresa.getTelefone1();
            final int telefone2 = empresa.getTelefone2();
            final int celular1 = empresa.getCelular1();
            final String email = empresa.getEmail();

            bancoDAO = new BancoDAO(CadastrarAlterarEmpresaActivity.this);
            empresaDAO = new EmpresaDAO(bancoDAO.Conexao());
            empresa = new Empresa();
            empresa.setNomeRazao(nome);
            empresa.setRua(endereco);
            empresa.setTelefone1(telefone1);

                    try {
                        empresaDAO.inserirEmpresa(empresa);
                        Toast.makeText(CadastrarAlterarEmpresaActivity.this, "Empresa cadastrada!", Toast.LENGTH_SHORT).show();
                    } catch (Exception ex) {
                        Toast.makeText(CadastrarAlterarEmpresaActivity.this, "Erro ao cadastrar a empresa!", Toast.LENGTH_SHORT).show();
                }
                }
            }

        }
    });

}

@Override
public void onDestroy(){
    super.onDestroy();

    // EventBus unregister
    EventBus.getDefault().unregister(CadastrarAlterarEmpresaActivity.this);
}

//listener
public void chamaEmpresa(){
    MessageEB messageEB = new MessageEB();
    messageEB.setClassTester(DadosEmpresaFrag.class + "");

    EventBus.getDefault().post(messageEB);

    MessageEB messageEB2 = new MessageEB();
    messageEB2.setClassTester(EnderecoEmpresaFrag.class + "");

    EventBus.getDefault().post(messageEB2);

    MessageEB messageEB3 = new MessageEB();
    messageEB3.setClassTester(ContatosEmpresaFrag.class + "");

    EventBus.getDefault().post(messageEB3);

}

public void onEvent(MessageEB mMessageEB){
    if(mMessageEB.getClassTester().equalsIgnoreCase(CadastrarAlterarEmpresaActivity.class+"1")) {
        Log.i("Teste", "Retorno fragment 1");
        empresa.setNomeRazao(mMessageEB.getEmpresa().getNomeRazao());
    }

    if(mMessageEB.getClassTester().equalsIgnoreCase(CadastrarAlterarEmpresaActivity.class+"2")) {
        Log.i("Teste", "Retorno fragment 2");
        empresa.setRua(mMessageEB.getEmpresa().getRua());
    }

    if(mMessageEB.getClassTester().equalsIgnoreCase(CadastrarAlterarEmpresaActivity.class+"3")) {
        Log.i("Teste", "Retorno fragment 3");
        empresa.setTelefone1(mMessageEB.getEmpresa().getTelefone1());
    }
}

}

The first Fragment

public class DadosEmpresaFrag extends Fragment {
EditText edtNomeEmpresa, edtApelidoEmpresa;

private static final String ARG_PARAM1 = "param1";
private static final String CODIGO_EMPRESA = "param2";

private String mParam1;
private int mParam2;

public static DadosEmpresaFrag newInstance(String param1, int param2 ) {
    DadosEmpresaFrag fragment = new DadosEmpresaFrag();
    Bundle args = new Bundle();
    args.putString(ARG_PARAM1, param1);
    args.putInt(CODIGO_EMPRESA, param2);
    fragment.setArguments(args);
    return fragment;
}

public DadosEmpresaFrag() {
    // Required empty public constructor
}

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

    if (getArguments() != null) {
        mParam1 = getArguments().getString(ARG_PARAM1);
        mParam2 = getArguments().getInt("codigo");
    }
}

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

    //Register Eventbus
    EventBus.getDefault().register(DadosEmpresaFrag.this);

    // -- inflate the layout for this fragment
    View myInflatedView = inflater.inflate(R.layout.fragment_dados_empresa, container, false);

    edtNomeEmpresa = (EditText) myInflatedView.findViewById(R.id.edtNomeEmpresa);

    BancoDAO bancoDAO = new BancoDAO(getActivity());
    EmpresaDAO empresaDAO = new EmpresaDAO(bancoDAO.Conexao());
    Empresa empresa = empresaDAO.buscarEmpresaId(mParam2);

    if (empresa != null){
        edtNomeEmpresa.setText(empresa.getNomeRazao());
    }

    return myInflatedView;
}

@Override
public void onDestroy() {
    super.onDestroy();

    //Unregister Eventbus
    EventBus.getDefault().unregister(DadosEmpresaFrag.this);
}

public void onEvent(MessageEB mMessageEB) {

    if(mMessageEB.getClassTester().equalsIgnoreCase(DadosEmpresaFrag.class+"")) {
        Log.i("Teste", "Chamando fragment 1");

        Empresa e = new Empresa();
        e.setNomeRazao(edtNomeEmpresa.getText().toString());

        mMessageEB.setEmpresa(e);
        mMessageEB.setClassTester(CadastrarAlterarEmpresaActivity.class + "1");
        EventBus.getDefault().post(mMessageEB);

    }

}

}

The second

public class EnderecoEmpresaFrag extends Fragment {
EditText edtEnderecoEmpresa;

private static final String ARG_PARAM1 = "param1";
private static final String CODIGO_EMPRESA = "param2";

private String mParam1;
private int mParam2;

public static EnderecoEmpresaFrag newInstance(String param1, int param2) {
    EnderecoEmpresaFrag fragment = new EnderecoEmpresaFrag();
    Bundle args = new Bundle();
    args.putString(ARG_PARAM1, param1);
    args.putInt(CODIGO_EMPRESA, param2);
    fragment.setArguments(args);
    return fragment;
}

public EnderecoEmpresaFrag() {
    // Required empty public constructor
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (getArguments() != null) {
        mParam1 = getArguments().getString(ARG_PARAM1);
        mParam2 = getArguments().getInt("codigo");
    }
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    //Register Eventbus
    EventBus.getDefault().register(EnderecoEmpresaFrag.this);

    // -- inflate the layout for this fragment
    View myInflatedView = inflater.inflate(R.layout.fragment_endereco_empresa, container, false);

    edtEnderecoEmpresa = (EditText) myInflatedView.findViewById(R.id.edtEnderecoEmpresa);

    BancoDAO bancoDAO = new BancoDAO(getActivity());
    EmpresaDAO empresaDAO = new EmpresaDAO(bancoDAO.Conexao());
    Empresa empresa = empresaDAO.buscarEmpresaId(mParam2);

    if (empresa != null){
        edtEnderecoEmpresa.setText(empresa.getRua());
    }


    return myInflatedView;
}

@Override
public void onDestroy() {
    super.onDestroy();

    //Unregister Eventbus
    EventBus.getDefault().unregister(EnderecoEmpresaFrag.this);
}

public void onEvent(MessageEB mMessageEB) {

    if(mMessageEB.getClassTester().equalsIgnoreCase(EnderecoEmpresaFrag.class+"")) {
        Log.i("Teste", "Chamando fragment 2");
        Empresa e = new Empresa();
        e.setRua(edtEnderecoEmpresa.getText().toString());

        mMessageEB.setEmpresa(e);
        mMessageEB.setClassTester(CadastrarAlterarEmpresaActivity.class + "2");
        EventBus.getDefault().post(mMessageEB);

    }

}
}

and finally the third:

public class ContatosEmpresaFrag extends Fragment {
EditText edtTelefone1;

private static final String ARG_PARAM1 = "param1";
private static final String CODIGO_EMPRESA = "param2";

private String mParam1;
private int mParam2;

public static ContatosEmpresaFrag newInstance(String param1, int param2 ) {
    ContatosEmpresaFrag fragment = new ContatosEmpresaFrag();
    Bundle args = new Bundle();
    args.putString(ARG_PARAM1, param1);
    args.putInt(CODIGO_EMPRESA, param2);
    fragment.setArguments(args);
    return fragment;
}

public ContatosEmpresaFrag() {
    // Required empty public constructor
}

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

    if (getArguments() != null) {
        mParam1 = getArguments().getString(ARG_PARAM1);
        mParam2 = getArguments().getInt("codigo");
    }
}

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

    //Register Eventbus
    EventBus.getDefault().register(ContatosEmpresaFrag.this);

    // -- inflate the layout for this fragment
    View myInflatedView = inflater.inflate(R.layout.fragment_contatos_empresa, container, false);

    edtTelefone1 = (EditText) myInflatedView.findViewById(R.id.edtTelefone1Empresa);

    //mascaras
    MaskEditTextChangedListener maskTelefone1 = new MaskEditTextChangedListener("(##)#####-####", edtTelefone1);
    edtTelefone1.addTextChangedListener(maskTelefone1);

    BancoDAO bancoDAO = new BancoDAO(getActivity());
    EmpresaDAO empresaDAO = new EmpresaDAO(bancoDAO.Conexao());
    Empresa empresa = empresaDAO.buscarEmpresaId(mParam2);

    if (empresa != null){
        if (empresa.getTelefone1() > 0)
            edtTelefone1.setText(String.valueOf(empresa.getTelefone1()));
        else
            edtTelefone1.setText("");
    }

    return myInflatedView;
}

@Override
public void onDestroy() {
    super.onDestroy();

    //Unregister Eventbus
    EventBus.getDefault().unregister(ContatosEmpresaFrag.this);
}

public void onEvent(MessageEB mMessageEB) {

    if(mMessageEB.getClassTester().equalsIgnoreCase(ContatosEmpresaFrag.class+"")) {
        Log.i("Teste", "Chamando fragment 3");
        Empresa e = new Empresa();
        if (!edtTelefone1.getText().toString().equals(""))
            e.setTelefone1(Integer.valueOf(valorSemMascara(edtTelefone1.getText().toString())));

        mMessageEB.setEmpresa(e);
        mMessageEB.setClassTester(CadastrarAlterarEmpresaActivity.class + "3");
        EventBus.getDefault().post(mMessageEB);
    }

}

private String valorSemMascara(String s) {
    String textoPuro = s.replaceAll("\\([^)]*\\)", "");
    textoPuro = textoPuro.replace("-", "");
    return textoPuro;
}

}

1 answer

1

This behavior is normal of yours FragmentStatePagerAdapter. He will always have the instance of his View visible + previous + next.

In your case, when you are at first, it only possessed in memory the next view:

Primeira aba

Now, when the second tab is visible, it saves the other tabs:

Segunda aba

And finally, the third visible tab it will only have the instance of the previous:

inserir a descrição da imagem aqui

If you have the need to use the Tabs I suggest you save the information in a centralized location (e.g. your Activity, or any Manager), and eliminate this dependency on EventBus to process/save the information.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.