0

I'm developing an application in which I build a treeView with some data. As the process is quite long I'd like to be able to save my built treeView (a LinearLayout) in some way to restore it when the activity is recalled.

Let's call my activity with the treeview T. I have Home->T->Resource and from Resource I go back Home. I implemented the onSaveInstance in T so there I can save in a bundle the variables I need when from Resource I go back Home and T is destroyed but the problem is that I'm not able to save all the linearLayout as a monolitic information in a bundle, the LinearLayout seems not to be parcelable.

So to summarize my cycle is:

Home-->T-->Resouce-->Home (T is destroyed and onSaveInstance is executed)-->T (I want to avoid the rebuilding of the LinearLayout).

Many thnaks

Luigi Tiburzi
  • 4,265
  • 7
  • 32
  • 43

2 Answers2

4

Don't do this. When you create any View, a layout or otherwise, it uses the inflating Activity's context to get and use system resources and internal app resources. When your Activity is destroyed, this context is no longer active.

If you do manage to save and load the LinearLayout back, you will get a lot of leaked windows, and other crashes, possible including NullPointerExceptions and Dead Objects.

You should always let Android recreate the layout for an Activity if the Activity is destroyed and started up again.

Raghav Sood
  • 81,899
  • 22
  • 187
  • 195
0

Why not save the resource elements of the 'treeView T' in some ordered data structure such as an ArrayList, HashMap etc... Save this data structure to a SharedPreference/Bundle etc... Whilst building the activity view, create the LinearLayout dynamically by reading the elements from the previously saved SharedPreference/Bundle.

/* Posting an example code below */

LinearLayout linLayout =  new LinearLayout(this);

View childView = null; // read this childView in a sequential manner from the sharedPreference/Bundle

linLayout.addView(childView);
Raghav Sood
  • 81,899
  • 22
  • 187
  • 195
Sdr
  • 1,090
  • 9
  • 8
  • I build the treeview in a recursive manner, the fundamental object is a class Resource R. You mean I should save only the "main father" R of the treeview T? If so, why an arrayList for only one element? – Luigi Tiburzi Apr 11 '13 at 07:06
  • The method which I've proposed does not involve the "fundamental R". In fact you would not even require to use 'R' since we will be creating the Activity screen dynamically. Once our main view i.e. linLayout (as mentioned in the above code, which corresponds to the treeView T) is constructed, instead of doing setContentView(R.XXX) all you do is setContentView(linLayout). You can refer to http://stackoverflow.com/questions/4979212/programmatically-creating-a-relativelayout-in-android for further information on creating layouts in android without using 'R' or any compile-time xml files. – Sdr Apr 11 '13 at 16:36