Store a list using the persistence/PrefService

Is it possible to store a complete list or dictionary/Map using the PrefService ?
According to the Javadoc it seems possible but I could not get it to work in Jython.

#@ PrefService pref

pref.put(None,"TestList", ['True','False','True'])

new = pref.getList(None, "TestList") # Null pointer exception
print new

And is it only possible with lists of strings ?

I suppose (without having studied the stack trace in more detail) this might be a case where Jython is matching the wrong method, since the Java method is overloaded with two signatures:

  • getList(String, String), and
  • getList(Class, String),

… and in your case it matches the former instead of the latter.

Once again, Groovy works better than Jython here, as this Groovy script works as expected:

#@ PrefService pref
pref.put(null, "TestList", ["1","2","3"])
println pref.getList(null as Class, "TestList") // [1, 2, 3]

A better way would be to use the actual script class to associate your saved preference value with it:

#@ PrefService pref
pref.put(this.class, "TestList", ["1","2","3"])
println pref.getList(this.class, "TestList")

Alternatively, you can use a common class such as ImageJ and use this, which also works in Python:

#@ PrefService pref
#@ ImageJ ij
pref.put(ij.class,"TestList", ['True','False','True'])
new = pref.getList(ij.class, "TestList")
print new

It seems so. In my tests it only worked with strings in both Groovy and Python.

1 Like