How to send data from an Activity to a Fragment?

Asked

Viewed 3,678 times

1

As you can see in the code below I can send data from one Fragment to the other and tbm from one Fragment to Activity but I’ve tried everything to send from Activity to Fragment but I’m not getting :(

Mainactivity.java

public class MainActivity extends AppCompatActivity {

String TabFragmentB;
String TabFragmentA;

private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;

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


    toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    viewPager = (ViewPager) findViewById(R.id.viewpager);
    setupViewPager(viewPager);

    tabLayout = (TabLayout) findViewById(R.id.tabs);
    tabLayout.setupWithViewPager(viewPager);

}

private void setupViewPager(ViewPager viewPager) {
    ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
    adapter.addFrag(new OneFragment(), "One");
    adapter.addFrag(new TwoFragment(), "Two");
    viewPager.setAdapter(adapter);
}

class ViewPagerAdapter extends FragmentPagerAdapter {
    private final List<Fragment> mFragmentList = new ArrayList<>();
    private final List<String> mFragmentTitleList = new ArrayList<>();

    public ViewPagerAdapter(FragmentManager manager) {
        super(manager);
    }

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

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

    public void addFrag(Fragment fragment, String title) {
        mFragmentList.add(fragment);
        mFragmentTitleList.add(title);
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return mFragmentTitleList.get(position);
    }
}

////Métodos que se relacionam com os fragments para trasporte de dados////

//Captura a Tag do fragment OneFragment
public void setTabFragmentA(String t){
    TabFragmentA = t;
}

//Retorna a Tag do fragment OneFragment
public String getTabFragmentA(){
    return TabFragmentA;
}


//Captura a Tag do fragment TwoFragment
public void setTabFragmentB(String t){
    TabFragmentB = t;
}

//Retorna a Tag do fragment TwoFragment
public String getTabFragmentB(){
    return TabFragmentB;
}

//Envia dados para o fragment OneFragment
public void msg_fragA(String message){

}

}

Onefragment.java

public class OneFragment extends Fragment {

static TextView statusMessage;
static TextView txt_temporizador;
static TextView txt_limite;
static TextView txt_espera;
static TextView txt_clock;

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

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

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    //Infla o layout do fragment
    View myFragmentView = inflater.inflate(R.layout.fragment_one, container, false);

    String myTag = getTag();//Grava a Tag do fragment
    ((MainActivity) getActivity()).setTabFragmentA(myTag);//Grava a Tag do fragment em uma váriavel da MainActivity

    statusMessage = (TextView) myFragmentView.findViewById(R.id.statusMessage);
    txt_temporizador = (TextView) myFragmentView.findViewById(R.id.txt_temporizador);
    txt_limite = (TextView) myFragmentView.findViewById(R.id.txt_limite);
    txt_espera = (TextView) myFragmentView.findViewById(R.id.txt_espera);
    txt_clock = (TextView) myFragmentView.findViewById(R.id.txt_clock);

    return myFragmentView;
}

public void dados_update(String tp, String tl, String te, String cl) {
    //Esse metódo recebe dados do TwoFragment ao ser apertado o botão envia do mesmo

    txt_temporizador.setText(tp);
    txt_limite.setText(tl);
    txt_espera.setText(te);
    txt_clock.setText(cl);

}


}

Twofragment.java

public class TwoFragment extends Fragment {

Button btn_envia;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    //Infla o layout do fragment
    View myFragmentView = inflater.inflate(R.layout.fragment_two, container, false);

    String myTag = getTag();//Grava a Tag do fragment
    ((MainActivity) getActivity()).setTabFragmentB(myTag);//Grava a Tag do fragment em uma váriavel da MainActivity

    btn_envia = (Button) myFragmentView.findViewById(R.id.button_enviar);
    btn_envia.setOnClickListener(Envia_dados);

    return myFragmentView;
}

//Instruções que serão seguidas quando o botão enviar for clicado
View.OnClickListener Envia_dados
        = new View.OnClickListener() {

    @Override
    public void onClick(View arg0) {

        String TabOfFragmentA = ((MainActivity) getActivity()).getTabFragmentA();//Captura a Tag do fragment OneFragment

        OneFragment fragmentA = (OneFragment) getActivity()
                .getSupportFragmentManager()
                .findFragmentByTag(TabOfFragmentA);

        fragmentA.dados_update("ON", "00:00:01", "00:00:02", "00:00:03");//Envia os dados para o OneFragment

        Toast.makeText(getActivity(),"Dados enviados!",Toast.LENGTH_LONG).show();
    }
};

}

1 answer

5


Much like how you receive data via putExtra in Activity.

First of all you need to refactor the method setupViewPager:

private OneFragment oneFragment;
private TwoFragment twoFragment;

private void setupViewPager(ViewPager viewPager) {
    oneFragment = new OneFragment();
    twoFragment = new TwoFragment();
    ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
    adapter.addFrag(oneFragment, "One");
    adapter.addFrag(twoFragment, "Two");
    viewPager.setAdapter(adapter);
}

And the method moment that sends the data also:

//Envia dados para o fragment OneFragment
public void enviaMensagemParaOFragment(String message, Fragment fragment){
    Bundle bundle = new Bundle();
    bundle.putString("CHAVE_DO_VALOR_PASSADO", message);
    fragment.setArguments(bundle);
}

And in his Activity you call the method enviaMensagemParaOFragment passing as parameter a string that you want to send and the Fragment to which the string:

protected void onCreate(Bundle savedInstanceState) {

    ...

    viewPager = (ViewPager) findViewById(R.id.viewpager);
    setupViewPager(viewPager);
    enviaMensagemParaOFragment("Essa é a mensagem que será enviada", oneFragment);

    ...
}

Already to recover the value, just change the method onCreateView of Fragment:

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

    String message = getArguments().getString("CHAVE_DO_VALOR_PASSADO");
    View myFragmentView = inflater.inflate(R.layout.fragment_two, container, false);

    ...
}

Even if by chance you want to call the Fragment in the event of a click of a button for example, you can create a interface with a method passarInformacao, implement this interface from their Fragment and call this method direct from Activity.

Passadordeinformacao.java

public interface PassadorDeInformacao {
    public void passaInformacao(String informacao);
}

Onefragment.java and Twofragment.java

public class OneFragment extends Fragment implements PassadorDeInformacao {

    @Override
    public void passaInformacao(String informacao) {
        // Faça o que quiser com a informação
        Log.d("OneFragment", "Recebi a informação: " + informacao);
    }

    ...
}

Mainactivity.java

public class MainActivity extends AppCompatActivity {
    ...


    //Envia dados para o fragment OneFragment
    public void enviaMensagemParaOFragment(String message, PassadorDeInformacao fragment){
        fragment.passaInformacao(message);
    }

    private void onButtonClick() {
        enviaMensagemParaOFragment("minha mensagem", oneFragment);
    }

    ...
}

I hope I helped the/

  • I still recommend that you use some of the existing frameworks that do all this work for you. Among them is the Android Annotations and the Butterknife

  • It worked, I spent the whole day breaking my head I can’t believe it was such a simple thing rsrs, Valew ai hehe

  • If it worked for you, you could dial it in. So other people who have had the same problem can see that your question has already been answered :)

  • 1

    Sorry I’m new around here rsrs, ready marked :)

  • Now that I went to scramble the code I was implementing the Passwordinformation, like it passes the correct information and printa in the Log of Fragment, but when I add this information in the textView statusMessage through setText it gives error. You know what it can be? :/

  • 1

    I found out what it was, the data was being passed before onCreateView was started, I’ve arranged here rsrs

Show 1 more comment

Browser other questions tagged

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