How to convert TinyDB List object to ArrayList

270 views
Skip to first unread message

Steve Marcus

unread,
Aug 9, 2013, 8:18:46 AM8/9/13
to alternate-java-bridg...@googlegroups.com
Say I have an empty list saved in a TinyDB.

ArrayList<Integer> myList = new ArrayList<Integer>();
tinyDB.StoreValue("MyList", myList);

On another screen, I want to get this TinyDB object and turn it back into an ArrayList, but I am having trouble converting it.

ArrayList<Integer> listFromScreen1 = new ArrayList<Integer>(tinyDB.GetValue("MyList"));

This throws the error The constructor ArrayList<Integer>(Object) is undefined.

ArrayList<Integer> listFromScreen1 = new ArrayList<Integer>(Convert.IntegerArrayList(tinyDB.GetValue("MyList")));

This throws the error The method IntegerArrayList(ArrayList<String>) in the type Convert is not applicable for the arguments (Object).

ArrayList<Integer> listFromScreen1 = new ArrayList<Integer>(Convert.IntegerArrayList((ArrayList<String>) tinyDB.GetValue("MyList")));

This works but warns me Type safety: Unchecked cast from Object to ArrayList<String>

So I wondered, what is the best/proper way to convert a TinyDB Object which is a list, back into a list when it has been got.

Thanks,


S

Imp Inc

unread,
Aug 9, 2013, 11:44:47 AM8/9/13
to alternate-java-bridg...@googlegroups.com
Just cast it like so:

ArrayList<Integer> listFromScreen1 = (ArrayList<Integer>) tinyDB.GetValue("MyList");

- Ryan

Imp Inc

unread,
Aug 9, 2013, 11:58:57 AM8/9/13
to alternate-java-bridg...@googlegroups.com
I should put more about this. Casting isn't always very safe. If the list is there, then you're ok. But if it's not, you'll get an exception. I would suggest using the methods which allow you to set a default.

ArrayList<Integer> listFromScreen1 = (ArrayList<Integer>) tinyDB.GetValue("MyList", new ArrayList<Integer>());

The above line is safe because if there's any error reading the MyList tag (it's not there), it will return a new ArrayList<Integer>.

There's also the TagExists(String tag, boolean sdCard) method, which will just return if data has been stored with that tag.

- Ryan

Steve Marcus

unread,
Aug 9, 2013, 7:03:31 PM8/9/13
to alternate-java-bridg...@googlegroups.com
Thanks Ryan,

Yes I've had that happen in testing, and in Eclipse it shows the warnings saying it's not safe.

But it's good to know the proper way.


ArrayList<Integer> listFromScreen1 = (ArrayList<Integer>) tinyDB.GetValue("MyList", new ArrayList<Integer>());

That is a good trick - I never would have thought of that. 

There's also the TagExists(String tag, boolean sdCard) method, which will just return if data has been stored with that tag.

Didn't know that either. I've been using:

  if (tinyDB.getAbsoluteFilePath("MyList") != "") { }

to test if something is in a tag or not.
Reply all
Reply to author
Forward
0 new messages