How do you get the type from a cursor?

2019-02-15 05:47发布

问题:

The javadocs indicate that android.database.Cursor has a getType(int) method. However, when I try to call this method, Eclipse gives me an error saying no method exists. What gives?

回答1:

What version of Android are you targeting? The getType() method applies only to v3.0 and later.

EDIT: Assuming you're targeting pre v3.0 versions of Android then a possible 'hack' to discover the type of each column within a table would be to query the sqlite_master table to find the CREATE data.

SELECT sql FROM sqlite_master

It's pretty nasty but if you really need to find the type then you could extend SQLiteCursor and add your own getType(int columnIndex) method.

You could perform a one-off query to the sqlite_master table when the cursor first accesses a table then parse the CREATE statement from the sql column and store the 'types' in an int[].

In the getType(int columnIndex) you would simply return the value of your int[] based on columnindex.

As I said, bit of a hack but it would work.



回答2:

As you can store any type of data in (nearly) every SQLite field. Looking up the data type in sqlite_master and by using the pragma command is not a safe method. You can get the type of the fields using a query like this:

select Field1, typeof(Field1), Field2, typeof(Field2) from MyTable

This statement returns both the value of the fields and their types which might / might not change from record to record.