I have a ton of Google searches on static objects in Java, and I think I understand how they work in Android. GC'ed static objects when the application process terminates, and not when the Activity object declaring the static object is destroyed (correct me if I am wrong). I have an application with Tabhost that uses fragments. The fragment declaring the object is to the right (there are three fragments) of the ViewPager. The tab on the right has a ListView that displays user data, and I would like this data to be saved when the user views all the tabs or moves away from the application. This data does not need to be stored, it just needs to remain in memory during normal use of the application. The fix that gives me the result I want is to set a static prefix for my array adapter. My question is: is this considered good practice? I know that improper use of static objects can lead to memory problems, however I did not get FC with widespread use (landscape for portrait again and again, quickly scrolling through tabs, adding a lot of data to ListView, etc.). Here is the code I'm using
static ArrayAdapter<String> arrayAdapter; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment, container, false); if (personList == null) { personList = new ArrayList<String>(); } if (arrayAdapter == null) { arrayAdapter = new ArrayAdapter<String> (getActivity().getApplicationContext(), android.R.layout.simple_list_item_1, personList); }
EDIT:
This is how I implement this idea. I have this code in my main activity (the one that gave birth to the tab fragments. I put this code in the onDestroy () method for the operation to try to recover some memory.
@Override protected void onDestroy() { super.onDestroy(); if (arrayAdapter != null) { arrayAdapter.clear(); arrayAdapter = null; Log.i("Activity", "Adapter nulled!"); } Log.i("Activity", "Activityhas been destroyed"); } public ArrayAdapter<String> getArrayAdapter(ArrayList<String> personList) { arrayAdapter = new ArrayAdapter<String> (getBaseContext(), android.R.layout.simple_list_item_1, personList); Log.i("Activity", "Adapter Created"); return arrayAdapter; }
With this code in my snippet
if (personList == null) { personList = new ArrayList<String>(); } if (arrayAdapter == null) { arrayAdapter = ((ActivityMainScreen)getActivity()).getArrayAdapter(personList); }
source share