keep data retained of listview when switching between activities

986 Views Asked by At

i am struggling to keep data or items of list view when i leave one activity to another, for my example i created simple app on click will add number increased to a list view so each click create an item like 1 another click add 2 and so on.

the program works fin for main activity but then i would like to see the result on another activity i call it second activity but the problem is when i hit back button on second activity to go back to main activity, i will lose all of items on the list view.

i was looking on google so many information but could not get my head around it, so please advice and please be little more in detail as i am beginner, i think instance state or shared preference will do the job but i do not know any of them

thanks in advance and here is my app code for main activity and second activity and picture for output sorry i add code as images becausethe site keep saying the code need indentation thank you main activity[main out put][2]second activity[second activity out put][4]

2

There are 2 best solutions below

5
Somdip Dey On

You need to save the data of the ListView in some form, either in a file or in a database (local or remote).There is no direct way to store list view, but you can store the data from the list view and then set it in to the ListView later when you switch back to the activity.

You need to keep in mind that switching activity results to invoking of onPause() method in android, and if the data is not saved in the current activity then it will be lost when you move on to another activity.

1
Abdul Rehman On

Add all your values into the array, pass it to the adapter, then after clicking on the list view item, make an intent where you want to switch your activity (means from one activity to second activity), while implemented the intent, pass your array also, using intent.put extra. Then you will get your array in your second activity and coming back to your previous activity, again pass an intent (with your array) and get your array in your previous activity and pass it into the adapter.