I'm getting a ArrayList
from an Url with AsyncTask
, and inserting into an ListView
on my Fragment
but everytime I change fragments I have to get json data from the Url again so I tried to use onSaveInstanceState()
to save my ArrayList
as a String
and transform to my ArrayList
using JsonObject
and Gson Library
but I can't save the data.
OnSave method
@Override
public void onSaveInstanceState(@NonNull Bundle outState) {
outState.putString("cursos", this.cursosString);
super.onSaveInstanceState(outState);
}
OnCreateView method
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
View view = inflater.inflate(R.layout.fragment_cursos, container, false);
final ListView lvCursos = view.findViewById(R.id.lvCursos);
if(savedInstanceState != null){
Type arrayListCurso = new TypeToken<ArrayList<Curso>>(){}.getType();
ArrayList<Curso> cursos = new Gson().fromJson(savedInstanceState.getString("cursos"), arrayListCurso);
ListaCursosAdapter adapter = new ListaCursosAdapter(cursos, getActivity());
lvCursos.setAdapter(adapter);
} else {
...
Change Fragments method
public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
switch (menuItem.getItemId()){
case R.id.navigation_profile:
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.nav_fragment, perfilFragment)
.commit();
return true;