How to insert arraylist or vector into SQLite Database in android?
I am new to Android. I need to store arraylist or vector in a database(SQLite) as a value for one of the column. I have searched regarding storing arraylist or vector. In that they suggested 开发者_开发知识库to convert arraylist into JSON.
Is there any other solution for this problem other than converting arraylist into JSON. Please give a me a solution or article regarding this issue.
Vectors and lists are data structures. SQLite columns only accept atomic values, namely numbers, strings and blobs.
Therefore you need to serialize (convert) the vector/list into a single string or blob - numbers won't do anyway. You will have to use an encoding that is uniquely reversible and will preserve any special properties of your data structure.
Sure, you can re-invent the wheel and use your own encoding. Or you could semi-reinvent the wheel by using the Java Serialization API. Or you could use something like JSON, which is a more tried solution.
If I were you, however, I'd first consider changing the database schema. Lists and vectors are close enough to the relational model that you might be able to store them in the database without serialization techniques.
EDIT:
See also this question and this one.
Firstly if you have a ArrayList or Vector of Strings . Then simply traverse it and store each of its string and manage it by your application logic.
If it is not carrying Strings then simply serialize the ArrayList object over any file. and keep the filename in the database
how can you store a memory object to db? :) you should serialize it to string. no matter what you will use. xml, json, your own toString method. just choose what is easier for you to serialize and deserialize objects. json seems to be a good idea
Depending on your application and the use cases for it I would create a separate table in the database for your ArrayList data (with one-to-many or many-to-many relations), and query for them separately.
Yes, it would most definitely add some complexity to your application but it would be a more robust and fault tolerant solution (not to speak of more elegant ;-)
This is however hard to rectify for a very simple use case where duplicate ArrayList items don't occur...
精彩评论