Hello, Please, I'm in need of 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 from a Spinner that will be used in the other Fragment (SegundaFragment).
For the communication between the two Fragment I have a Communicator interface and a MainActivity that implements Communicator.
My problem is in the onCreateView method of PegaValoresFragment. After choosing the Spinner game the value for a static attribute of the MainActivity class. This static attribute is returned to the SecondFragment through a getCourse () method (this method is in the 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 PegaValoresFragment class
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 SegundaFragment class
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? Thanks