0
Hello, Please, I need help. I’m trying to use the Android Studio template to make a simple application that in a Fragment (Pegavaloresfragment) in the onCreateView method takes an option of a Spinner that will be used in the other Fragment (Segundafragment).
For communication between the two Fragment I have a Communicator interface and a Mainactivity that implements Communicator.
My problem is the onCreateView method of Pegavaloresfragment. After Spinner’s choice I play the value for a static attribute of the Mainactivity class. This static attribute is returned to Segundafragment via a getCurso() method (this method is in Interface and implemented in Mainactivity).
The problem is that the value received from Spinner that was placed in the static attribute of the Mainactivity class is lost soon after the end of the onCreateView (Return rootView;) method of Pegavaloresfragment.
The Mainactivity class
public class MainActivity extends AppCompatActivity implements Comunicador {
public static String vCurso;
public String getCurso() {
return(MainActivity.vCurso);
}
...
The Interface
public interface Comunicador{
String getCurso();
}
The class Pegavaloresfragment
public class PegaValoresFragment extends Fragment {
...
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
opcoesCurso = (Spinner) rootView.findViewById(R.id.spinCurso);
ArrayAdapter adapterCurso = ArrayAdapter.createFromResource(getActivity(),R.array.opcoes_cursos,android.R.layout.simple_spinner_item);
opcoesCurso.setAdapter(adapterCurso);
AdapterView.OnItemSelectedListener escolhaCurso = new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
String itemCurso = opcoesCurso.getSelectedItem().toString();
// PegaValoresFragment.setCurso(itemCurso);
//Toast.makeText(getApplicationContext(),"Curso Escolhido foi : "+itemCurso, Toast.LENGTH_SHORT).show();
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
};
MainActivity.vCurso= opcoesCurso.getSelectedItem().toString();
....
return rootView;
}
...
}
The class Segundafragment
public class SegundaFragment extends Fragment {
Comunicador comm;
public String getCurso(){
return(comm.getCurso());
}
...
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.segunda_fragment, container, false);
...
String teste = getCurso();
textView.setText(" Curso getCurso() => "+teste);
...
return rootView;
}
}
Please, could you help me figure out where I’m going wrong? Thank you
One of the ways to solve this would be by creating a class to store this value and you would have access anywhere in your app.
– Reginaldo Rigo