2

I'm new to android and I know similar questions like this have been asked before, I've looked at their answers and none of them seem to solve my problem

I have a listview in a fragment in my activity that retrieves information from a URL and displays it using a custom adapter and clicking on a row will display more information about the row clicked in a new activity, like a news with more details.

The problem I have is each time I go back from the activity with more details, the previous activity has to make the connection again to retrieve the information from the URL to display in the listview, so the listview becomes empty and the whole process starts from beginning

I'm looking for the best and/or easiest way to save the state of the fragment in the previous activity or the activity itself, so that when the user goes back to it he sees it as he left and it won't make the connection every time.

samieaji
  • 46
  • 5

1 Answers1

0

In such cases I do the follwoing:

  1. Make a pojo class and an arraylist that stores data needed for the listview. You can also store the interactions. Also a static field to indicate the firstVisibleItem of listview is helpful.
  2. I create a public static arraylist object in another class.
  3. Inflate the layout in oncreate view
  4. In onstart first i check if the static arraylist defined in another class length is 0. If it is empty I load it from internet. If not I setAdapter to the listview
  5. On onpause method of fragment you can set the static field firstVisibleItem of listview to your listview's first visible item.
  6. On second load of fragment I simply set the adapter to the listview and if the firstVisibleItem has a valid value(not -1) then I do listview.setSelectionFromTop(). It might seem like a lot of code but its fairly simple. Ask if you have any comments.
Illegal Argument
  • 10,090
  • 2
  • 44
  • 61