private boolean isDatabaseHeaderValid(SQLiteDatabase sqliteDatabase) {

        boolean validHeader = false;
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(sqliteDatabase.getPath());
            byte[] headerBytes = new byte[16];
            if (fis.read(headerBytes) == 16) {
                ByteReader byteReader = new ByteReader(headerBytes);
                String header = byteReader.readString(headerBytes.length);
                String headerPrefix = header.substring(0, GeoPackageConstants.SQLITE_HEADER_PREFIX.length());
                validHeader = headerPrefix.equalsIgnoreCase(GeoPackageConstants.SQLITE_HEADER_PREFIX);
            }
        } catch (Exception e) {
            Log.e(GeoPackageManagerImpl.class.getSimpleName(), "Failed to retrieve database header", e);
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    // eat
                }
            }
        }

        return validHeader;
    }

private
boolean
isDatabaseHeaderValid
(
SQLiteDatabase
sqliteDatabase
)
{
boolean
validHeader
=
false
;
FileInputStream
fis
=
;
try
{
fis
=
new
FileInputStream
(
sqliteDatabase
.
getPath
(
)
)
;
byte
[
]
headerBytes
=
new
byte
[
16
]
;
if
(
fis
.
read
(
headerBytes
)
==
16
)
{
ByteReader
byteReader
=
new
ByteReader
(
headerBytes
)
;
String
header
=
byteReader
.
readString
(
headerBytes
.
length
)
;
String
headerPrefix
=
header
.
substring
(
0
,
GeoPackageConstants
.
SQLITE_HEADER_PREFIX
.
length
(
)
)
;
validHeader
=
headerPrefix
.
equalsIgnoreCase
(
GeoPackageConstants
.
SQLITE_HEADER_PREFIX
)
;
}
}
catch
(
Exception
e
)
{
Log
.
e
(
GeoPackageManagerImpl
.
class
.
getSimpleName
(
)
,
"Failed to retrieve database header"
,
e
)
;
}
finally
{
if
(
fis
!=
)
{
try
{
fis
.
close
(
)
;
}
catch
(
IOException
e
)
{
// eat
}
}
}
return
validHeader
;
}

Determine if the header of the database file is valid

@param sqliteDatabase database
@return true if valid


private void addInternalDatabases(Collection<String> databases) {
        String[] databaseArray = context.databaseList();
        for (String database : databaseArray) {
            if (!isTemporary(database)
                    && !database
                    .equalsIgnoreCase(GeoPackageMetadataDb.DATABASE_NAME)) {
                databases.add(database);
            }
        }
    }

private void addInternalDatabases ( Collection < String > databases ) { String [ ] databaseArray = context . databaseList ( ) ; for ( String database : databaseArray ) { if ( ! isTemporary ( database ) && ! database . equalsIgnoreCase ( GeoPackageMetadataDb . DATABASE_NAME ) ) { databases . add ( database ) ; } } }

Add all internal databases to the collection

@param databases


private void addExternalDatabases(Collection<String> databases) {
        // Get the external GeoPackages, adding those where the file exists and
        // deleting those with missing files
        List<GeoPackageMetadata> externalGeoPackages = getExternalGeoPackages();
        for (GeoPackageMetadata external : externalGeoPackages) {
            if (new File(external.getExternalPath()).exists()) {
                databases.add(external.getName());
            } else {
                delete(external.getName());
            }
        }
    }

Add all external databases to the collection

@param databases


private boolean importGeoPackage(String database, boolean override,
                                     InputStream geoPackageStream, GeoPackageProgress progress) {

        try {

            if (exists(database)) {
                if (override) {
                    if (!delete(database)) {
                        throw new GeoPackageException(
                                "Failed to delete existing database: " + database);
                    }
                } else {
                    throw new GeoPackageException(
                            "GeoPackage database already exists: " + database);
                }
            }

            // Copy the geopackage over as a database
            File newDbFile = context.getDatabasePath(database);
            try {
                SQLiteDatabase db = context.openOrCreateDatabase(database,
                        Context.MODE_PRIVATE, null);
                db.close();
                GeoPackageIOUtils.copyStream(geoPackageStream, newDbFile, progress);
            } catch (IOException e) {
                throw new GeoPackageException(
                        "Failed to import GeoPackage database: " + database, e);
            }

        } finally {
            GeoPackageIOUtils.closeQuietly(geoPackageStream);
        }

        if (progress == null || progress.isActive()) {

            // Verify that the database is valid
            try {
                SQLiteDatabase sqlite = context.openOrCreateDatabase(database,
                        Context.MODE_PRIVATE, null, new DatabaseErrorHandler() {
                            @Override
                            public void onCorruption(SQLiteDatabase dbObj) {
                            }
                        });
                validateDatabaseAndClose(sqlite, importHeaderValidation, importIntegrityValidation);

                GeoPackageMetadataDb metadataDb = new GeoPackageMetadataDb(
                        context);
                metadataDb.open();
                try {
                    GeoPackageMetadataDataSource dataSource = new GeoPackageMetadataDataSource(metadataDb);
                    // Save in metadata
                    GeoPackageMetadata metadata = new GeoPackageMetadata();
                    metadata.setName(database);
                    dataSource.create(metadata);
                } finally {
                    metadataDb.close();
                }
            } catch (Exception e) {
                delete(database);
                throw new GeoPackageException(
                        "Invalid GeoPackage database file", e);
            }

            GeoPackage geoPackage = open(database, false);
            if (geoPackage != null) {
                try {
                    if (!geoPackage.getSpatialReferenceSystemDao()
                            .isTableExists()
                            || !geoPackage.getContentsDao().isTableExists()) {
                        delete(database);
                        throw new GeoPackageException(
                                "Invalid GeoPackage database file. Does not contain required tables: "
                                        + SpatialReferenceSystem.TABLE_NAME
                                        + " & " + Contents.TABLE_NAME
                                        + ", Database: " + database);
                    }
                } catch (SQLException e) {
                    delete(database);
                    throw new GeoPackageException(
                            "Invalid GeoPackage database file. Could not verify existence of required tables: "
                                    + SpatialReferenceSystem.TABLE_NAME
                                    + " & "
                                    + Contents.TABLE_NAME
                                    + ", Database: "
                                    + database);
                } finally {
                    geoPackage.close();
                }
            } else {
                delete(database);
                throw new GeoPackageException(
                        "Unable to open GeoPackage database. Database: "
                                + database);
            }
        }

        return exists(database);
    }

Import the GeoPackage stream

@param database
@param override
@param geoPackageStream
@param progress
@return true if imported successfully


private GeoPackageMetadata getGeoPackageMetadata(String database) {
        GeoPackageMetadata metadata = null;

        GeoPackageMetadataDb metadataDb = new GeoPackageMetadataDb(
                context);
        metadataDb.open();
        try {
            GeoPackageMetadataDataSource dataSource = new GeoPackageMetadataDataSource(metadataDb);
            metadata = dataSource.get(database);
        } finally {
            metadataDb.close();
        }

        return metadata;
    }

private GeoPackageMetadata getGeoPackageMetadata ( String database ) { GeoPackageMetadata metadata = null ; GeoPackageMetadataDb metadataDb = new GeoPackageMetadataDb ( context ) ; metadataDb . open ( ) ; try { GeoPackageMetadataDataSource dataSource = new GeoPackageMetadataDataSource ( metadataDb ) ; metadata = dataSource . get ( database ) ; } finally { metadataDb . close ( ) ; } return metadata ; }

Get the GeoPackage metadata

@param database
@return


private GeoPackageMetadata getGeoPackageMetadataAtExternalPath(String path) {
        GeoPackageMetadata metadata = null;

        GeoPackageMetadataDb metadataDb = new GeoPackageMetadataDb(
                context);
        metadataDb.open();
        try {
            GeoPackageMetadataDataSource dataSource = new GeoPackageMetadataDataSource(metadataDb);
            metadata = dataSource.getExternalAtPath(path);
        } finally {
            metadataDb.close();
        }

        return metadata;
    }

private GeoPackageMetadata getGeoPackageMetadataAtExternalPath ( String path ) { GeoPackageMetadata metadata = null ; GeoPackageMetadataDb metadataDb = new GeoPackageMetadataDb ( context ) ; metadataDb . open ( ) ; try { GeoPackageMetadataDataSource dataSource = new GeoPackageMetadataDataSource ( metadataDb ) ; metadata = dataSource . getExternalAtPath ( path ) ; } finally { metadataDb . close ( ) ; } return metadata ; }

Get the GeoPackage metadata of the database at the external path

@param path external database path
@return metadata or null


public long create(GeometryMetadata metadata) {
        ContentValues values = new ContentValues();
        values.put(GeometryMetadata.COLUMN_GEOPACKAGE_ID, metadata.getGeoPackageId());
        values.put(GeometryMetadata.COLUMN_TABLE_NAME, metadata.getTableName());
        values.put(GeometryMetadata.COLUMN_ID, metadata.getId());
        values.put(GeometryMetadata.COLUMN_MIN_X, metadata.getMinX());
        values.put(GeometryMetadata.COLUMN_MAX_X, metadata.getMaxX());
        values.put(GeometryMetadata.COLUMN_MIN_Y, metadata.getMinY());
        values.put(GeometryMetadata.COLUMN_MAX_Y, metadata.getMaxY());
        values.put(GeometryMetadata.COLUMN_MIN_Z, metadata.getMinZ());
        values.put(GeometryMetadata.COLUMN_MAX_Z, metadata.getMaxZ());
        values.put(GeometryMetadata.COLUMN_MIN_M, metadata.getMinM());
        values.put(GeometryMetadata.COLUMN_MAX_M, metadata.getMaxM());
        long insertId = db.insert(
                GeometryMetadata.TABLE_NAME, null,
                values);
        if (insertId == -1) {
            throw new GeoPackageException(
                    "Failed to insert geometry metadata. GeoPackage Id: "
                            + metadata.getGeoPackageId() + ", Table Name: "
                            + metadata.getTableName() + ", Geometry Id: "
                            + metadata.getId());
        }
        metadata.setId(insertId);
        return insertId;
    }

Create a new geometry metadata

@param metadata geometry metadata
@return id


public GeometryMetadata populate(long geoPackageId, String tableName, long geomId, GeometryEnvelope envelope) {

        GeometryMetadata metadata = new GeometryMetadata();
        metadata.setGeoPackageId(geoPackageId);
        metadata.setTableName(tableName);
        metadata.setId(geomId);
        metadata.setMinX(envelope.getMinX());
        metadata.setMaxX(envelope.getMaxX());
        metadata.setMinY(envelope.getMinY());
        metadata.setMaxY(envelope.getMaxY());
        if (envelope.hasZ()) {
            metadata.setMinZ(envelope.getMinZ());
            metadata.setMaxZ(envelope.getMaxZ());
        }
        if (envelope.hasM()) {
            metadata.setMinM(envelope.getMinM());
            metadata.setMaxM(envelope.getMaxM());
        }
        return metadata;
    }

public GeometryMetadata populate ( long geoPackageId , String tableName , long geomId , GeometryEnvelope envelope ) { GeometryMetadata metadata = new GeometryMetadata ( ) ; metadata . setGeoPackageId ( geoPackageId ) ; metadata . setTableName ( tableName ) ; metadata . setId ( geomId ) ; metadata . setMinX ( envelope . getMinX ( ) ) ; metadata . setMaxX ( envelope . getMaxX ( ) ) ; metadata . setMinY ( envelope . getMinY ( ) ) ; metadata . setMaxY ( envelope . getMaxY ( ) ) ; if ( envelope . hasZ ( ) ) { metadata . setMinZ ( envelope . getMinZ ( ) ) ; metadata . setMaxZ ( envelope . getMaxZ ( ) ) ; } if ( envelope . hasM ( ) ) { metadata . setMinM ( envelope . getMinM ( ) ) ; metadata . setMaxM ( envelope . getMaxM ( ) ) ; } return metadata ; }

Populate a new geometry metadata from an envelope

@param geoPackageId GeoPackage id
@param tableName    table name
@param geomId       geometry id
@param envelope     geometry envelope
@return geometry metadata


public int delete(long geoPackageId) {
        String whereClause = GeometryMetadata.COLUMN_GEOPACKAGE_ID + " = ?";
        String[] whereArgs = new String[]{String.valueOf(geoPackageId)};
        int deleteCount = db.delete(
                GeometryMetadata.TABLE_NAME,
                whereClause, whereArgs);
        return deleteCount;
    }

public
int
delete
(
long
geoPackageId
)
{
String
whereClause
=
GeometryMetadata
.
COLUMN_GEOPACKAGE_ID
+
" = ?"
;
String
[
]
whereArgs
=
new
String
[
]
{
String
.
valueOf
(
geoPackageId
)
}
;
int
deleteCount
=
db
.
delete
(
GeometryMetadata
.
TABLE_NAME
,
whereClause
,
whereArgs
)
;
return
deleteCount
;
}

Delete geometry metadata by database

@param geoPackageId GeoPackage id
@return deleted count


public boolean createOrUpdate(GeometryMetadata metadata) {

        boolean success = false;

        if (exists(metadata)) {
            success = update(metadata);
        } else {
            create(metadata);
            success = true;
        }

        return success;
    }

public boolean createOrUpdate ( GeometryMetadata metadata ) { boolean success = false ; if ( exists ( metadata ) ) { success = update ( metadata ) ; } else { create ( metadata ) ; success = true ; } return success ; }

Create the geometry metadata or update if it already exists

@param metadata geometry metadata
@return created flag


public boolean update(GeometryMetadata metadata) {
        String whereClause = GeometryMetadata.COLUMN_GEOPACKAGE_ID
                + " = ? AND " + GeometryMetadata.COLUMN_TABLE_NAME + " = ? AND "
                + GeometryMetadata.COLUMN_ID + " = ?";
        String[] whereArgs = new String[]{String.valueOf(metadata.getGeoPackageId()), metadata.getTableName(), String.valueOf(metadata.getId())};
        ContentValues values = new ContentValues();
        values.put(GeometryMetadata.COLUMN_MIN_X, metadata.getMinX());
        values.put(GeometryMetadata.COLUMN_MAX_X, metadata.getMaxX());
        values.put(GeometryMetadata.COLUMN_MIN_Y, metadata.getMinY());
        values.put(GeometryMetadata.COLUMN_MAX_Y, metadata.getMaxY());
        values.put(GeometryMetadata.COLUMN_MIN_Z, metadata.getMinZ());
        values.put(GeometryMetadata.COLUMN_MAX_Z, metadata.getMaxZ());
        values.put(GeometryMetadata.COLUMN_MIN_M, metadata.getMinM());
        values.put(GeometryMetadata.COLUMN_MAX_M, metadata.getMaxM());
        int updateCount = db.update(
                GeometryMetadata.TABLE_NAME, values,
                whereClause, whereArgs);
        return updateCount > 0;
    }

public
boolean
update
(
GeometryMetadata
metadata
)
{
String
whereClause
=
GeometryMetadata
.
COLUMN_GEOPACKAGE_ID
+
" = ? AND "
+
GeometryMetadata
.
COLUMN_TABLE_NAME
+
" = ? AND "
+
GeometryMetadata
.
COLUMN_ID
+
" = ?"
;
String
[
]
whereArgs
=
new
String
[
]
{
String
.
valueOf
(
metadata
.
getGeoPackageId
(
)
)
,
metadata
.
getTableName
(
)
,
String
.
valueOf
(
metadata
.
getId
(
)
)
}
;
ContentValues
values
=
new
ContentValues
(
)
;
values
.
put
(
GeometryMetadata
.
COLUMN_MIN_X
,
metadata
.
getMinX
(
)
)
;
values
.
put
(
GeometryMetadata
.
COLUMN_MAX_X
,
metadata
.
getMaxX
(
)
)
;
values
.
put
(
GeometryMetadata
.
COLUMN_MIN_Y
,
metadata
.
getMinY
(
)
)
;
values
.
put
(
GeometryMetadata
.
COLUMN_MAX_Y
,
metadata
.
getMaxY
(
)
)
;
values
.
put
(
GeometryMetadata
.
COLUMN_MIN_Z
,
metadata
.
getMinZ
(
)
)
;
values
.
put
(
GeometryMetadata
.
COLUMN_MAX_Z
,
metadata
.
getMaxZ
(
)
)
;
values
.
put
(
GeometryMetadata
.
COLUMN_MIN_M
,
metadata
.
getMinM
(
)
)
;
values
.
put
(
GeometryMetadata
.
COLUMN_MAX_M
,
metadata
.
getMaxM
(
)
)
;
int
updateCount
=
db
.
update
(
GeometryMetadata
.
TABLE_NAME
,
values
,
whereClause
,
whereArgs
)
;
return
updateCount
>
0
;
}

Update the geometry metadata

@param metadata geometry metadata
@return updated flag


public int count(String geoPackage, String tableName, BoundingBox boundingBox) {
        return count(getGeoPackageId(geoPackage), tableName, boundingBox);
    }

public int count ( String geoPackage , String tableName , BoundingBox boundingBox ) { return count ( getGeoPackageId ( geoPackage ) , tableName , boundingBox ) ; }

Query for all table geometry metadata count matching the bounding box in the same projection

@param geoPackage  GeoPackage name
@param tableName   table name
@param boundingBox bounding box
@return count
@since 1.1.0


public static GeometryMetadata createGeometryMetadata(Cursor cursor) {
        GeometryMetadata metadata = new GeometryMetadata();
        metadata.setGeoPackageId(cursor.getLong(0));
        metadata.setTableName(cursor.getString(1));
        metadata.setId(cursor.getLong(2));
        metadata.setMinX(cursor.getDouble(3));
        metadata.setMaxX(cursor.getDouble(4));
        metadata.setMinY(cursor.getDouble(5));
        metadata.setMaxY(cursor.getDouble(6));
        if (!cursor.isNull(7)) {
            metadata.setMinZ(cursor.getDouble(7));
        }
        if (!cursor.isNull(8)) {
            metadata.setMaxZ(cursor.getDouble(8));
        }
        if (!cursor.isNull(9)) {
            metadata.setMinM(cursor.getDouble(9));
        }
        if (!cursor.isNull(10)) {
            metadata.setMaxM(cursor.getDouble(10));
        }
        return metadata;
    }

public static GeometryMetadata createGeometryMetadata ( Cursor cursor ) { GeometryMetadata metadata = new GeometryMetadata ( ) ; metadata . setGeoPackageId ( cursor . getLong ( 0 ) ) ; metadata . setTableName ( cursor . getString ( 1 ) ) ; metadata . setId ( cursor . getLong ( 2 ) ) ; metadata . setMinX ( cursor . getDouble ( 3 ) ) ; metadata . setMaxX ( cursor . getDouble ( 4 ) ) ; metadata . setMinY ( cursor . getDouble ( 5 ) ) ; metadata . setMaxY ( cursor . getDouble ( 6 ) ) ; if ( ! cursor . isNull ( 7 ) ) { metadata . setMinZ ( cursor . getDouble ( 7 ) ) ; } if ( ! cursor . isNull ( 8 ) ) { metadata . setMaxZ ( cursor . getDouble ( 8 ) ) ; } if ( ! cursor . isNull ( 9 ) ) { metadata . setMinM ( cursor . getDouble ( 9 ) ) ; } if ( ! cursor . isNull ( 10 ) ) { metadata . setMaxM ( cursor . getDouble ( 10 ) ) ; } return metadata ; }

Create a geometry metadata from the current cursor location

@param cursor cursor
@return geometry metadata


public int update(ContentValues values, String whereClause,
                      String[] whereArgs) {
        return db.update(getTableName(), values, whereClause, whereArgs);
    }

public int update ( ContentValues values , String whereClause , String [ ] whereArgs ) { return db . update ( getTableName ( ) , values , whereClause , whereArgs ) ; }

Update all rows matching the where clause with the provided values

@param values      content values
@param whereClause where clause
@param whereArgs   where arguments
@return updated rows


private Bitmap drawTile(int tileWidth, int tileHeight, String text) {

        // Create bitmap and canvas
        Bitmap bitmap = Bitmap.createBitmap(tileWidth,
                tileHeight, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);

        // Draw the tile fill paint
        if (tileFillPaint != null) {
            canvas.drawRect(0, 0, tileWidth, tileHeight, tileFillPaint);
        }

        // Draw the tile border
        if (tileBorderPaint != null) {
            canvas.drawRect(0, 0, tileWidth, tileHeight, tileBorderPaint);
        }

        // Determine the text bounds
        Rect textBounds = new Rect();
        textPaint.getTextBounds(text, 0, text.length(), textBounds);

        // Determine the center of the tile
        int centerX = (int) (bitmap.getWidth() / 2.0f);
        int centerY = (int) (bitmap.getHeight() / 2.0f);

        // Draw the circle
        if (circlePaint != null || circleFillPaint != null) {
            int diameter = Math.max(textBounds.width(), textBounds.height());
            float radius = diameter / 2.0f;
            radius = radius + (diameter * circlePaddingPercentage);

            // Draw the filled circle
            if (circleFillPaint != null) {
                canvas.drawCircle(centerX, centerY, radius, circleFillPaint);
            }

            // Draw the circle
            if (circlePaint != null) {
                canvas.drawCircle(centerX, centerY, radius, circlePaint);
            }

        }

        // Draw the text
        canvas.drawText(text, centerX - textBounds.exactCenterX(), centerY - textBounds.exactCenterY(), textPaint);

        return bitmap;
    }

private
Bitmap
drawTile
(
int
tileWidth
,
int
tileHeight
,
String
text
)
{
// Create bitmap and canvas
Bitmap
bitmap
=
Bitmap
.
createBitmap
(
tileWidth
,
tileHeight
,
Bitmap
.
Config
.
ARGB_8888
)
;
Canvas
canvas
=
new
Canvas
(
bitmap
)
;
// Draw the tile fill paint
if
(
tileFillPaint
!=
)
{
canvas
.
drawRect
(
0
,
0
,
tileWidth
,
tileHeight
,
tileFillPaint
)
;
}
// Draw the tile border
if
(
tileBorderPaint
!=
)
{
canvas
.
drawRect
(
0
,
0
,
tileWidth
,
tileHeight
,
tileBorderPaint
)
;
}
// Determine the text bounds
Rect
textBounds
=
new
Rect
(
)
;
textPaint
.
getTextBounds
(
text
,
0
,
text
.
length
(
)
,
textBounds
)
;
// Determine the center of the tile
int
centerX
=
(
int
)
(
bitmap
.
getWidth
(
)
/
2.0f
)
;
int
centerY
=
(
int
)
(
bitmap
.
getHeight
(
)
/
2.0f
)
;
// Draw the circle
if
(
circlePaint
!=
||
circleFillPaint
!=
)
{
int
diameter
=
Math
.
max
(
textBounds
.
width
(
)
,
textBounds
.
height
(
)
)
;
float
radius
=
diameter
/
2.0f
;
radius
=
radius
+
(
diameter
*
circlePaddingPercentage
)
;
// Draw the filled circle
if
(
circleFillPaint
!=
)
{
canvas
.
drawCircle
(
centerX
,
centerY
,
radius
,
circleFillPaint
)
;
}
// Draw the circle
if
(
circlePaint
!=
)
{
canvas
.
drawCircle
(
centerX
,
centerY
,
radius
,
circlePaint
)
;
}
}
// Draw the text
canvas
.
drawText
(
text
,
centerX
textBounds
.
exactCenterX
(
)
,
centerY
textBounds
.
exactCenterY
(
)
,
textPaint
)
;
return
bitmap
;
}

Draw a tile with the provided text label in the middle

@param tileWidth  tile width
@param tileHeight tile height
@param text       text
@return tile bitmap


public List<SimpleAttributesRow> getRows(List<Long> ids) {
        List<SimpleAttributesRow> simpleAttributesRows = new ArrayList<>();
        for (long id : ids) {
            UserCustomRow userCustomRow = queryForIdRow(id);
            if (userCustomRow != null) {
                simpleAttributesRows.add(getRow(userCustomRow));
            }
        }
        return simpleAttributesRows;
    }

public List < SimpleAttributesRow > getRows ( List < Long > ids ) { List < SimpleAttributesRow > simpleAttributesRows = new ArrayList <> ( ) ; for ( long id : ids ) { UserCustomRow userCustomRow = queryForIdRow ( id ) ; if ( userCustomRow != null ) { simpleAttributesRows . add ( getRow ( userCustomRow ) ) ; } } return simpleAttributesRows ; }

Get the simple attributes rows that exist with the provided ids

@param ids list of ids
@return simple attributes rows


private Cursor integrityCheck(Cursor cursor) {
        if (cursor.moveToNext()) {
            String value = cursor.getString(0);
            if (value.equals("ok")) {
                cursor.close();
                cursor = null;
            }
        }
        return cursor;
    }

private Cursor integrityCheck ( Cursor cursor ) { if ( cursor . moveToNext ( ) ) { String value = cursor . getString ( 0 ) ; if ( value . equals ( "ok" ) ) { cursor . close ( ) ; cursor = null ; } } return cursor ; }

Check the cursor returned from the integrity check to see if things are "ok"

@param cursor
@return null if ok, else the open cursor

Check the cursor returned from the integrity check to see if things are ok


public UserMappingDao getMappingDao(String tableName) {
        UserMappingDao userMappingDao = new UserMappingDao(getUserDao(tableName));
        userMappingDao.registerCursorWrapper(getGeoPackage());
        return userMappingDao;
    }

public UserMappingDao getMappingDao ( String tableName ) { UserMappingDao userMappingDao = new UserMappingDao ( getUserDao ( tableName ) ) ; userMappingDao . registerCursorWrapper ( getGeoPackage ( ) ) ; return userMappingDao ; }

Get a User Mapping DAO from a table name

@param tableName mapping table name
@return user mapping dao


public SimpleAttributesDao getSimpleAttributesDao(String tableName) {
        SimpleAttributesDao simpleAttributesDao = new SimpleAttributesDao(
                getUserDao(tableName));
        simpleAttributesDao.registerCursorWrapper(getGeoPackage());
        setContents(simpleAttributesDao.getTable());
        return simpleAttributesDao;
    }

public SimpleAttributesDao getSimpleAttributesDao ( String tableName ) { SimpleAttributesDao simpleAttributesDao = new SimpleAttributesDao ( getUserDao ( tableName ) ) ; simpleAttributesDao . registerCursorWrapper ( getGeoPackage ( ) ) ; setContents ( simpleAttributesDao . getTable ( ) ) ; return simpleAttributesDao ; }

Get a related simple attributes table DAO

@param tableName simple attributes table name
@return simple attributes DAO


public List<Long> getMappingsForBase(ExtendedRelation extendedRelation,
                                         long baseId) {
        return getMappingsForBase(extendedRelation.getMappingTableName(),
                baseId);
    }

public List < Long > getMappingsForBase ( ExtendedRelation extendedRelation , long baseId ) { return getMappingsForBase ( extendedRelation . getMappingTableName ( ) , baseId ) ; }

Get the related id mappings for the base id

@param extendedRelation extended relation
@param baseId           base id
@return IDs representing the matching related IDs


public List<Long> getMappingsForRelated(ExtendedRelation extendedRelation,
                                            long relatedId) {
        return getMappingsForRelated(extendedRelation.getMappingTableName(),
                relatedId);
    }

public List < Long > getMappingsForRelated ( ExtendedRelation extendedRelation , long relatedId ) { return getMappingsForRelated ( extendedRelation . getMappingTableName ( ) , relatedId ) ; }

Get the base id mappings for the related id

@param extendedRelation extended relation
@param relatedId        related id
@return IDs representing the matching base IDs


public boolean hasMapping(String tableName, long baseId, long relatedId) {
        boolean has = false;
        UserMappingDao userMappingDao = getMappingDao(tableName);
        UserCustomCursor cursor = userMappingDao.queryByIds(baseId,
                relatedId);
        try {
            has = cursor.getCount() > 0;
        } finally {
            cursor.close();
        }
        return has;
    }

public boolean hasMapping ( String tableName , long baseId , long relatedId ) { boolean has = false ; UserMappingDao userMappingDao = getMappingDao ( tableName ) ; UserCustomCursor cursor = userMappingDao . queryByIds ( baseId , relatedId ) ; try { has = cursor . getCount ( ) > 0 ; } finally { cursor . close ( ) ; } return has ; }

Determine if the base id and related id mapping exists

@param tableName mapping table name
@param baseId    base id
@param relatedId related id
@return true if mapping exists
@since 3.2.0


protected int count(UserCustomCursor cursor) {
        int count = 0;
        try {
            count = cursor.getCount();
        } finally {
            cursor.close();
        }
        return count;
    }

protected int count ( UserCustomCursor cursor ) { int count = 0 ; try { count = cursor . getCount ( ) ; } finally { cursor . close ( ) ; } return count ; }

Get the count of the cursor and close it

@param cursor cursor
@return count


public void registerCursorWrapper(GeoPackage geoPackage) {
        geoPackage.registerCursorWrapper(getTableName(), new GeoPackageCursorWrapper() {
            @Override
            public Cursor wrapCursor(Cursor cursor) {
                return new UserCustomCursor(getTable(), cursor);
            }
        });
    }

public void registerCursorWrapper ( GeoPackage geoPackage ) { geoPackage . registerCursorWrapper ( getTableName ( ) , new GeoPackageCursorWrapper ( ) { @ Override public Cursor wrapCursor ( Cursor cursor ) { return new UserCustomCursor ( getTable ( ) , cursor ) ; } } ) ; }

Register the cursor wrapper into the GeoPackage

@param geoPackage GeoPackage


public static UserCustomDao readTable(GeoPackage geoPackage, String tableName) {

        UserCustomConnection userDb = new UserCustomConnection(geoPackage.getConnection());
        final UserCustomTable userCustomTable = UserCustomTableReader.readTable(
                geoPackage.getConnection(), tableName);
        UserCustomDao dao = new UserCustomDao(geoPackage.getName(), geoPackage.getConnection(), userDb,
                userCustomTable);

        dao.registerCursorWrapper(geoPackage);

        return dao;
    }

public static UserCustomDao readTable ( GeoPackage geoPackage , String tableName ) { UserCustomConnection userDb = new UserCustomConnection ( geoPackage . getConnection ( ) ) ; final UserCustomTable userCustomTable = UserCustomTableReader . readTable ( geoPackage . getConnection ( ) , tableName ) ; UserCustomDao dao = new UserCustomDao ( geoPackage . getName ( ) , geoPackage . getConnection ( ) , userDb , userCustomTable ) ; dao . registerCursorWrapper ( geoPackage ) ; return dao ; }

Read the database table and create a DAO

@param geoPackage GeoPackage
@param tableName  table name
@return user custom DAO


public GeoPackageTile getTile(BoundingBox requestBoundingBox) {

        GeoPackageTile tile = null;

        // Transform to the projection of the tiles
        ProjectionTransform transformRequestToTiles = requestProjection.getTransformation(tilesProjection);
        BoundingBox tilesBoundingBox = requestBoundingBox.transform(transformRequestToTiles);

        List<TileMatrix> tileMatrices = getTileMatrices(tilesBoundingBox);

        for (int i = 0; tile == null && i < tileMatrices.size(); i++) {

            TileMatrix tileMatrix = tileMatrices.get(i);

            TileCursor tileResults = retrieveTileResults(tilesBoundingBox, tileMatrix);
            if (tileResults != null) {

                try {

                    if (tileResults.getCount() > 0) {

                        BoundingBox requestProjectedBoundingBox = requestBoundingBox.transform(transformRequestToTiles);

                        // Determine the requested tile dimensions, or use the dimensions of a single tile matrix tile
                        int requestedTileWidth = width != null ? width : (int) tileMatrix
                                .getTileWidth();
                        int requestedTileHeight = height != null ? height : (int) tileMatrix
                                .getTileHeight();

                        // Determine the size of the tile to initially draw
                        int tileWidth = requestedTileWidth;
                        int tileHeight = requestedTileHeight;
                        if (!sameProjection) {
                            tileWidth = (int) Math.round(
                                    (requestProjectedBoundingBox.getMaxLongitude() - requestProjectedBoundingBox.getMinLongitude())
                                            / tileMatrix.getPixelXSize());
                            tileHeight = (int) Math.round(
                                    (requestProjectedBoundingBox.getMaxLatitude() - requestProjectedBoundingBox.getMinLatitude())
                                            / tileMatrix.getPixelYSize());
                        }

                        // Draw the resulting bitmap with the matching tiles
                        Bitmap tileBitmap = drawTile(tileMatrix, tileResults, requestProjectedBoundingBox, tileWidth, tileHeight);

                        // Create the tile
                        if (tileBitmap != null) {

                            // Project the tile if needed
                            if (!sameProjection) {
                                Bitmap reprojectTile = reprojectTile(tileBitmap, requestedTileWidth, requestedTileHeight, requestBoundingBox, transformRequestToTiles, tilesBoundingBox);
                                tileBitmap.recycle();
                                tileBitmap = reprojectTile;
                            }

                            try {
                                byte[] tileData = BitmapConverter.toBytes(
                                        tileBitmap, COMPRESS_FORMAT);
                                tileBitmap.recycle();
                                tile = new GeoPackageTile(requestedTileWidth, requestedTileHeight, tileData);
                            } catch (IOException e) {
                                Log.e(TileCreator.class.getSimpleName(), "Failed to create tile. min lat: "
                                        + requestBoundingBox.getMinLatitude()
                                        + ", max lat: " + requestBoundingBox.getMaxLatitude()
                                        + ", min lon: " + requestBoundingBox.getMinLongitude() +
                                        ", max lon: " + requestBoundingBox.getMaxLongitude(), e);
                            }
                        }

                    }
                } finally {
                    tileResults.close();
                }
            }
        }

        return tile;
    }

Get the tile from the request bounding box in the request projection

@param requestBoundingBox request bounding box in the request projection
@return tile


private Bitmap drawTile(TileMatrix tileMatrix, TileCursor tileResults, BoundingBox requestProjectedBoundingBox, int tileWidth, int tileHeight) {

        // Draw the resulting bitmap with the matching tiles
        Bitmap tileBitmap = null;
        Canvas canvas = null;
        Paint paint = null;
        while (tileResults.moveToNext()) {

            // Get the next tile
            TileRow tileRow = tileResults.getRow();
            Bitmap tileDataBitmap = tileRow.getTileDataBitmap();

            // Get the bounding box of the tile
            BoundingBox tileBoundingBox = TileBoundingBoxUtils
                    .getBoundingBox(
                            tileSetBoundingBox, tileMatrix,
                            tileRow.getTileColumn(), tileRow.getTileRow());

            // Get the bounding box where the requested image and
            // tile overlap
            BoundingBox overlap = requestProjectedBoundingBox.overlap(
                    tileBoundingBox);

            // If the tile overlaps with the requested box
            if (overlap != null) {

                // Get the rectangle of the tile image to draw
                Rect src = TileBoundingBoxAndroidUtils
                        .getRectangle(tileMatrix.getTileWidth(),
                                tileMatrix.getTileHeight(),
                                tileBoundingBox, overlap);

                // Get the rectangle of where to draw the tile in
                // the resulting image
                RectF dest = TileBoundingBoxAndroidUtils
                        .getRoundedFloatRectangle(tileWidth, tileHeight,
                                requestProjectedBoundingBox, overlap);

                // Create the bitmap first time through
                if (tileBitmap == null) {
                    tileBitmap = Bitmap.createBitmap(tileWidth,
                            tileHeight, Bitmap.Config.ARGB_8888);
                    canvas = new Canvas(tileBitmap);
                    paint = new Paint(Paint.ANTI_ALIAS_FLAG);
                }

                // Draw the tile to the bitmap
                canvas.drawBitmap(tileDataBitmap, src, dest, paint);
            }
        }

        return tileBitmap;
    }

Draw the tile from the tile results

@param tileMatrix
@param tileResults
@param requestProjectedBoundingBox
@param tileWidth
@param tileHeight
@return tile bitmap


private Bitmap reprojectTile(Bitmap tile, int requestedTileWidth, int requestedTileHeight, BoundingBox requestBoundingBox, ProjectionTransform transformRequestToTiles, BoundingBox tilesBoundingBox) {

        final double requestedWidthUnitsPerPixel = (requestBoundingBox.getMaxLongitude() - requestBoundingBox.getMinLongitude()) / requestedTileWidth;
        final double requestedHeightUnitsPerPixel = (requestBoundingBox.getMaxLatitude() - requestBoundingBox.getMinLatitude()) / requestedTileHeight;

        final double tilesDistanceWidth = tilesBoundingBox.getMaxLongitude() - tilesBoundingBox.getMinLongitude();
        final double tilesDistanceHeight = tilesBoundingBox.getMaxLatitude() - tilesBoundingBox.getMinLatitude();

        final int width = tile.getWidth();
        final int height = tile.getHeight();

        // Tile pixels of the tile matrix tiles
        int[] pixels = new int[width * height];
        tile.getPixels(pixels, 0, width, 0, 0, width, height);

        // Projected tile pixels to draw the reprojected tile
        int[] projectedPixels = new int[requestedTileWidth * requestedTileHeight];

        // Retrieve each pixel in the new tile from the unprojected tile
        for (int y = 0; y < requestedTileHeight; y++) {
            for (int x = 0; x < requestedTileWidth; x++) {

                double longitude = requestBoundingBox.getMinLongitude() + (x * requestedWidthUnitsPerPixel);
                double latitude = requestBoundingBox.getMaxLatitude() - (y * requestedHeightUnitsPerPixel);
                ProjCoordinate fromCoord = new ProjCoordinate(longitude, latitude);
                ProjCoordinate toCoord = transformRequestToTiles.transform(fromCoord);
                double projectedLongitude = toCoord.x;
                double projectedLatitude = toCoord.y;

                int xPixel = (int) Math.round(((projectedLongitude - tilesBoundingBox.getMinLongitude()) / tilesDistanceWidth) * width);
                int yPixel = (int) Math.round(((tilesBoundingBox.getMaxLatitude() - projectedLatitude) / tilesDistanceHeight) * height);

                xPixel = Math.max(0, xPixel);
                xPixel = Math.min(width - 1, xPixel);

                yPixel = Math.max(0, yPixel);
                yPixel = Math.min(height - 1, yPixel);

                int color = pixels[(yPixel * width) + xPixel];
                projectedPixels[(y * requestedTileWidth) + x] = color;
            }
        }

        // Draw the new tile bitmap
        Bitmap projectedTileBitmap = Bitmap.createBitmap(requestedTileWidth,
                requestedTileHeight, tile.getConfig());
        projectedTileBitmap.setPixels(projectedPixels, 0, requestedTileWidth, 0, 0, requestedTileWidth, requestedTileHeight);

        return projectedTileBitmap;
    }

Reproject the tile to the requested projection

@param tile                    tile in the tile matrix projection
@param requestedTileWidth      requested tile width
@param requestedTileHeight     requested tile height
@param requestBoundingBox      request bounding box in the request projection
@param transformRequestToTiles transformation from request to tiles
@param tilesBoundingBox        request bounding box in the tile matrix projection
@return projected tile


private TileCursor retrieveTileResults(BoundingBox projectedRequestBoundingBox, TileMatrix tileMatrix) {

        TileCursor tileResults = null;

        if (tileMatrix != null) {

            // Get the tile grid
            TileGrid tileGrid = TileBoundingBoxUtils.getTileGrid(
                    tileSetBoundingBox, tileMatrix.getMatrixWidth(),
                    tileMatrix.getMatrixHeight(), projectedRequestBoundingBox);

            // Query for matching tiles in the tile grid
            tileResults = tileDao.queryByTileGrid(tileGrid,
                    tileMatrix.getZoomLevel());

        }

        return tileResults;
    }

Get the tile row results of tiles needed to draw the requested bounding box tile

@param projectedRequestBoundingBox bounding box projected to the tiles
@param tileMatrix
@return tile cursor results or null


public void calculateDrawOverlap() {

        if (pointIcon != null) {
            heightOverlap = this.density * pointIcon.getHeight();
            widthOverlap = this.density * pointIcon.getWidth();
        } else {
            heightOverlap = this.density * pointRadius;
            widthOverlap = this.density * pointRadius;
        }

        float linePaintHalfStroke = this.density * lineStrokeWidth / 2.0f;
        heightOverlap = Math.max(heightOverlap, linePaintHalfStroke);
        widthOverlap = Math.max(widthOverlap, linePaintHalfStroke);

        float polygonPaintHalfStroke = this.density * polygonStrokeWidth / 2.0f;
        heightOverlap = Math.max(heightOverlap, polygonPaintHalfStroke);
        widthOverlap = Math.max(widthOverlap, polygonPaintHalfStroke);

        if (featureTableStyles != null && featureTableStyles.has()) {

            // Style Rows
            Set<Long> styleRowIds = new HashSet<>();
            List<Long> tableStyleIds = featureTableStyles.getAllTableStyleIds();
            if (tableStyleIds != null) {
                styleRowIds.addAll(tableStyleIds);
            }
            List<Long> styleIds = featureTableStyles.getAllStyleIds();
            if (styleIds != null) {
                styleRowIds.addAll(styleIds);
            }

            StyleDao styleDao = featureTableStyles.getStyleDao();
            for (long styleRowId : styleRowIds) {
                StyleRow styleRow = styleDao.getRow(styleDao.queryForIdRow(styleRowId));
                float styleHalfWidth = this.density * (float) (styleRow.getWidthOrDefault() / 2.0f);
                widthOverlap = Math.max(widthOverlap, styleHalfWidth);
                heightOverlap = Math.max(heightOverlap, styleHalfWidth);
            }

            // Icon Rows
            Set<Long> iconRowIds = new HashSet<>();
            List<Long> tableIconIds = featureTableStyles.getAllTableIconIds();
            if (tableIconIds != null) {
                iconRowIds.addAll(tableIconIds);
            }
            List<Long> iconIds = featureTableStyles.getAllIconIds();
            if (iconIds != null) {
                iconRowIds.addAll(iconIds);
            }

            IconDao iconDao = featureTableStyles.getIconDao();
            for (long iconRowId : iconRowIds) {
                IconRow iconRow = iconDao.getRow(iconDao.queryForIdRow(iconRowId));
                double[] iconDimensions = iconRow.getDerivedDimensions();
                float iconWidth = this.density * (float) Math.ceil(iconDimensions[0]);
                float iconHeight = this.density * (float) Math.ceil(iconDimensions[1]);
                widthOverlap = Math.max(widthOverlap, iconWidth);
                heightOverlap = Math.max(heightOverlap, iconHeight);
            }

        }

    }

public
void
calculateDrawOverlap
(
)
{
if
(
pointIcon
!=
)
{
heightOverlap
=
this
.
density
*
pointIcon
.
getHeight
(
)
;
widthOverlap
=
this
.
density
*
pointIcon
.
getWidth
(
)
;
}
else
{
heightOverlap
=
this
.
density
*
pointRadius
;
widthOverlap
=
this
.
density
*
pointRadius
;
}
float
linePaintHalfStroke
=
this
.
density
*
lineStrokeWidth
/
2.0f
;
heightOverlap
=
Math
.
max
(
heightOverlap
,
linePaintHalfStroke
)
;
widthOverlap
=
Math
.
max
(
widthOverlap
,
linePaintHalfStroke
)
;
float
polygonPaintHalfStroke
=
this
.
density
*
polygonStrokeWidth
/
2.0f
;
heightOverlap
=
Math
.
max
(
heightOverlap
,
polygonPaintHalfStroke
)
;
widthOverlap
=
Math
.
max
(
widthOverlap
,
polygonPaintHalfStroke
)
;
if
(
featureTableStyles
!=
&&
featureTableStyles
.
has
(
)
)
{
// Style Rows
Set
<
Long
>
styleRowIds
=
new
HashSet
<>
(
)
;
List
<
Long
>
tableStyleIds
=
featureTableStyles
.
getAllTableStyleIds
(
)
;
if
(
tableStyleIds
!=
)
{
styleRowIds
.
addAll
(
tableStyleIds
)
;
}
List
<
Long
>
styleIds
=
featureTableStyles
.
getAllStyleIds
(
)
;
if
(
styleIds
!=
)
{
styleRowIds
.
addAll
(
styleIds
)
;
}
StyleDao
styleDao
=
featureTableStyles
.
getStyleDao
(
)
;
for
(
long
styleRowId
:
styleRowIds
)
{
StyleRow
styleRow
=
styleDao
.
getRow
(
styleDao
.
queryForIdRow
(
styleRowId
)
)
;
float
styleHalfWidth
=
this
.
density
*
(
float
)
(
styleRow
.
getWidthOrDefault
(
)
/
2.0f
)
;
widthOverlap
=
Math
.
max
(
widthOverlap
,
styleHalfWidth
)
;
heightOverlap
=
Math
.
max
(
heightOverlap
,
styleHalfWidth
)
;
}
// Icon Rows
Set
<
Long
>
iconRowIds
=
new
HashSet
<>
(
)
;
List
<
Long
>
tableIconIds
=
featureTableStyles
.
getAllTableIconIds
(
)
;
if
(
tableIconIds
!=
)
{
iconRowIds
.
addAll
(
tableIconIds
)
;
}
List
<
Long
>
iconIds
=
featureTableStyles
.
getAllIconIds
(
)
;
if
(
iconIds
!=
)
{
iconRowIds
.
addAll
(
iconIds
)
;
}
IconDao
iconDao
=
featureTableStyles
.
getIconDao
(
)
;
for
(
long
iconRowId
:
iconRowIds
)
{
IconRow
iconRow
=
iconDao
.
getRow
(
iconDao
.
queryForIdRow
(
iconRowId
)
)
;
double
[
]
iconDimensions
=
iconRow
.
getDerivedDimensions
(
)
;
float
iconWidth
=
this
.
density
*
(
float
)
Math
.
ceil
(
iconDimensions
[
0
]
)
;
float
iconHeight
=
this
.
density
*
(
float
)
Math
.
ceil
(
iconDimensions
[
1
]
)
;
widthOverlap
=
Math
.
max
(
widthOverlap
,
iconWidth
)
;
heightOverlap
=
Math
.
max
(
heightOverlap
,
iconHeight
)
;
}
}
}

Call after making changes to the point icon, point radius, or paint stroke widths.
Determines the pixel overlap between tiles

Call after making changes to the point icon point radius or paint stroke widths . Determines the pixel overlap between tiles


public void setDensity(float density) {
        this.density = density;
        linePaint.setStrokeWidth(this.density * lineStrokeWidth);
        polygonPaint.setStrokeWidth(this.density * polygonStrokeWidth);
        featurePaintCache.clear();
    }

public void setDensity ( float density ) { this . density = density ; linePaint . setStrokeWidth ( this . density * lineStrokeWidth ) ; polygonPaint . setStrokeWidth ( this . density * polygonStrokeWidth ) ; featurePaintCache . clear ( ) ; }

Set the density

@param density density
@since 3.2.0


public void setLinePaint(Paint linePaint) {
        if (linePaint == null) {
            throw new AssertionError("Line Paint can not be null");
        }
        this.linePaint = linePaint;
        setLineStrokeWidth(linePaint.getStrokeWidth());
    }

public
void
setLinePaint
(
Paint
linePaint
)
{
if
(
linePaint
==
)
{
throw
new
AssertionError
(
"Line Paint can not be null"
)
;
}
this
.
linePaint
=
linePaint
;
setLineStrokeWidth
(
linePaint
.
getStrokeWidth
(
)
)
;
}

Set the line paint

@param linePaint line paint


public void setPolygonPaint(Paint polygonPaint) {
        if (polygonPaint == null) {
            throw new AssertionError("Polygon Paint can not be null");
        }
        this.polygonPaint = polygonPaint;
        setPolygonStrokeWidth(polygonPaint.getStrokeWidth());
    }

public
void
setPolygonPaint
(
Paint
polygonPaint
)
{
if
(
polygonPaint
==
)
{
throw
new
AssertionError
(
"Polygon Paint can not be null"
)
;
}
this
.
polygonPaint
=
polygonPaint
;
setPolygonStrokeWidth
(
polygonPaint
.
getStrokeWidth
(
)
)
;
}

Set the polygon paint

@param polygonPaint polygon paint


public byte[] drawTileBytes(int x, int y, int zoom) {

        Bitmap bitmap = drawTile(x, y, zoom);

        byte[] tileData = null;

        // Convert the bitmap to bytes
        if (bitmap != null) {
            try {
                tileData = BitmapConverter.toBytes(
                        bitmap, compressFormat);
            } catch (IOException e) {
                Log.e(FeatureTiles.class.getSimpleName(), "Failed to create tile. x: " + x + ", y: "
                        + y + ", zoom: " + zoom, e);
            } finally {
                bitmap.recycle();
            }
        }

        return tileData;
    }

public
byte
[
]
drawTileBytes
(
int
x
,
int
y
,
int
zoom
)
{
Bitmap
bitmap
=
drawTile
(
x
,
y
,
zoom
)
;
byte
[
]
tileData
=
;
// Convert the bitmap to bytes
if
(
bitmap
!=
)
{
try
{
tileData
=
BitmapConverter
.
toBytes
(
bitmap
,
compressFormat
)
;
}
catch
(
IOException
e
)
{
Log
.
e
(
FeatureTiles
.
class
.
getSimpleName
(
)
,
"Failed to create tile. x: "
+
x
+
", y: "
+
y
+
", zoom: "
+
zoom
,
e
)
;
}
finally
{
bitmap
.
recycle
(
)
;
}
}
return
tileData
;
}

Draw the tile and get the bytes from the x, y, and zoom level

@param x    x coordinate
@param y    y coordinate
@param zoom zoom level
@return tile bytes, or null

Draw the tile and get the bytes from the x y and zoom level


public Bitmap drawTile(int x, int y, int zoom) {
        Bitmap bitmap;
        if (isIndexQuery()) {
            bitmap = drawTileQueryIndex(x, y, zoom);
        } else {
            bitmap = drawTileQueryAll(x, y, zoom);
        }
        return bitmap;
    }

public Bitmap drawTile ( int x , int y , int zoom ) { Bitmap bitmap ; if ( isIndexQuery ( ) ) { bitmap = drawTileQueryIndex ( x , y , zoom ) ; } else { bitmap = drawTileQueryAll ( x , y , zoom ) ; } return bitmap ; }

Draw a tile bitmap from the x, y, and zoom level

@param x    x coordinate
@param y    y coordinate
@param zoom zoom level
@return tile bitmap, or null

Draw a tile bitmap from the x y and zoom level


public Bitmap drawTileQueryIndex(int x, int y, int zoom) {

        // Get the web mercator bounding box
        BoundingBox webMercatorBoundingBox = TileBoundingBoxUtils
                .getWebMercatorBoundingBox(x, y, zoom);

        Bitmap bitmap = null;

        // Query for geometries matching the bounds in the index
        FeatureIndexResults results = queryIndexedFeatures(webMercatorBoundingBox);

        try {

            long tileCount = results.count();

            // Draw if at least one geometry exists
            if (tileCount > 0) {

                if (maxFeaturesPerTile == null || tileCount <= maxFeaturesPerTile.longValue()) {

                    // Draw the tile bitmap
                    bitmap = drawTile(zoom, webMercatorBoundingBox, results);

                } else if (maxFeaturesTileDraw != null) {

                    // Draw the max features tile
                    bitmap = maxFeaturesTileDraw.drawTile(tileWidth, tileHeight, tileCount, results);
                }

            }
        } finally {
            results.close();
        }

        return bitmap;
    }

Draw a tile bitmap from the x, y, and zoom level by querying features in the tile location

@param x    x coordinate
@param y    y coordinate
@param zoom zoom level
@return drawn bitmap, or null

Draw a tile bitmap from the x y and zoom level by querying features in the tile location


public long queryIndexedFeaturesCount(int x, int y, int zoom) {

        // Get the web mercator bounding box
        BoundingBox webMercatorBoundingBox = TileBoundingBoxUtils
                .getWebMercatorBoundingBox(x, y, zoom);

        // Query for the count of geometries matching the bounds in the index
        long count = queryIndexedFeaturesCount(webMercatorBoundingBox);

        return count;
    }

Query for feature result count in the x, y, and zoom

@param x    x coordinate
@param y    y coordinate
@param zoom zoom level
@return feature count
@since 1.1.0

Query for feature result count in the x y and zoom


public long queryIndexedFeaturesCount(BoundingBox webMercatorBoundingBox) {

        // Query for geometries matching the bounds in the index
        FeatureIndexResults results = queryIndexedFeatures(webMercatorBoundingBox);

        long count = 0;

        try {
            count = results.count();
        } finally {
            results.close();
        }

        return count;
    }

Query for feature result count in the bounding box

@param webMercatorBoundingBox web mercator bounding box
@return feature count
@since 3.2.0


public FeatureIndexResults queryIndexedFeatures(int x, int y, int zoom) {

        // Get the web mercator bounding box
        BoundingBox webMercatorBoundingBox = TileBoundingBoxUtils
                .getWebMercatorBoundingBox(x, y, zoom);

        // Query for the geometries matching the bounds in the index
        return queryIndexedFeatures(webMercatorBoundingBox);
    }

Query for feature results in the x, y, and zoom level by querying features in the tile location

@param x    x coordinate
@param y    y coordinate
@param zoom zoom level
@return feature index results
@since 3.2.0

Query for feature results in the x y and zoom level by querying features in the tile location


public FeatureIndexResults queryIndexedFeatures(BoundingBox webMercatorBoundingBox) {

        // Create an expanded bounding box to handle features outside the tile
        // that overlap
        BoundingBox expandedQueryBoundingBox = expandBoundingBox(webMercatorBoundingBox);

        // Query for geometries matching the bounds in the index
        FeatureIndexResults results = indexManager.query(expandedQueryBoundingBox, WEB_MERCATOR_PROJECTION);

        return results;
    }

Query for feature results in the bounding box

@param webMercatorBoundingBox web mercator bounding box
@return feature index results
@since 1.1.0


public Bitmap drawTileQueryAll(int x, int y, int zoom) {

        BoundingBox boundingBox = TileBoundingBoxUtils
                .getWebMercatorBoundingBox(x, y, zoom);

        Bitmap bitmap = null;

        // Query for all features
        FeatureCursor cursor = featureDao.queryForAll();

        try {

            int totalCount = cursor.getCount();

            // Draw if at least one geometry exists
            if (totalCount > 0) {

                if (maxFeaturesPerTile == null || totalCount <= maxFeaturesPerTile) {

                    // Draw the tile bitmap
                    bitmap = drawTile(zoom, boundingBox, cursor);

                } else if (maxFeaturesTileDraw != null) {

                    // Draw the unindexed max features tile
                    bitmap = maxFeaturesTileDraw.drawUnindexedTile(tileWidth, tileHeight, totalCount, cursor);
                }

            }
        } finally {
            cursor.close();
        }

        return bitmap;
    }

public
Bitmap
drawTileQueryAll
(
int
x
,
int
y
,
int
zoom
)
{
BoundingBox
boundingBox
=
TileBoundingBoxUtils
.
getWebMercatorBoundingBox
(
x
,
y
,
zoom
)
;
Bitmap
bitmap
=
;
// Query for all features
FeatureCursor
cursor
=
featureDao
.
queryForAll
(
)
;
try
{
int
totalCount
=
cursor
.
getCount
(
)
;
// Draw if at least one geometry exists
if
(
totalCount
>
0
)
{
if
(
maxFeaturesPerTile
==
||
totalCount
<=
maxFeaturesPerTile
)
{
// Draw the tile bitmap
bitmap
=
drawTile
(
zoom
,
boundingBox
,
cursor
)
;
}
else
if
(
maxFeaturesTileDraw
!=
)
{
// Draw the unindexed max features tile
bitmap
=
maxFeaturesTileDraw
.
drawUnindexedTile
(
tileWidth
,
tileHeight
,
totalCount
,
cursor
)
;
}
}
}
finally
{
cursor
.
close
(
)
;
}
return
bitmap
;
}

Draw a tile bitmap from the x, y, and zoom level by querying all features. This could
be very slow if there are a lot of features

@param x    x coordinate
@param y    y coordinate
@param zoom zoom level
@return drawn bitmap, or null

Draw a tile bitmap from the x y and zoom level by querying all features . This could be very slow if there are a lot of features


protected List<Point> simplifyPoints(double simplifyTolerance,
                                         List<Point> points) {

        List<Point> simplifiedPoints = null;
        if (simplifyGeometries) {

            // Reproject to web mercator if not in meters
            if (projection != null && !projection.isUnit(Units.METRES)) {
                ProjectionTransform toWebMercator = projection
                        .getTransformation(WEB_MERCATOR_PROJECTION);
                points = toWebMercator.transform(points);
            }

            // Simplify the points
            simplifiedPoints = GeometryUtils.simplifyPoints(points,
                    simplifyTolerance);

            // Reproject back to the original projection
            if (projection != null && !projection.isUnit(Units.METRES)) {
                ProjectionTransform fromWebMercator = WEB_MERCATOR_PROJECTION
                        .getTransformation(projection);
                simplifiedPoints = fromWebMercator.transform(simplifiedPoints);
            }
        } else {
            simplifiedPoints = points;
        }

        return simplifiedPoints;
    }

When the simplify tolerance is set, simplify the points to a similar
curve with fewer points.

@param simplifyTolerance simplify tolerance in meters
@param points            ordered points
@return simplified points
@since 2.0.0

When the simplify tolerance is set simplify the points to a similar curve with fewer points .


protected Paint getPointPaint(FeatureStyle featureStyle) {

        Paint paint = getFeatureStylePaint(featureStyle, FeatureDrawType.CIRCLE);

        if (paint == null) {
            paint = pointPaint;
        }

        return paint;
    }

protected Paint getPointPaint ( FeatureStyle featureStyle ) { Paint paint = getFeatureStylePaint ( featureStyle , FeatureDrawType . CIRCLE ) ; if ( paint == null ) { paint = pointPaint ; } return paint ; }

Get the point paint for the feature style, or return the default paint

@param featureStyle feature style
@return paint

Get the point paint for the feature style or return the default paint


protected Paint getLinePaint(FeatureStyle featureStyle) {

        Paint paint = getFeatureStylePaint(featureStyle, FeatureDrawType.STROKE);

        if (paint == null) {
            paint = linePaint;
        }

        return paint;
    }

protected Paint getLinePaint ( FeatureStyle featureStyle ) { Paint paint = getFeatureStylePaint ( featureStyle , FeatureDrawType . STROKE ) ; if ( paint == null ) { paint = linePaint ; } return paint ; }

Get the line paint for the feature style, or return the default paint

@param featureStyle feature style
@return paint

Get the line paint for the feature style or return the default paint


protected Paint getPolygonPaint(FeatureStyle featureStyle) {

        Paint paint = getFeatureStylePaint(featureStyle, FeatureDrawType.STROKE);

        if (paint == null) {
            paint = polygonPaint;
        }

        return paint;
    }

protected Paint getPolygonPaint ( FeatureStyle featureStyle ) { Paint paint = getFeatureStylePaint ( featureStyle , FeatureDrawType . STROKE ) ; if ( paint == null ) { paint = polygonPaint ; } return paint ; }

Get the polygon paint for the feature style, or return the default paint

@param featureStyle feature style
@return paint

Get the polygon paint for the feature style or return the default paint


protected Paint getPolygonFillPaint(FeatureStyle featureStyle) {

        Paint paint = null;

        boolean hasStyleColor = false;

        if (featureStyle != null) {

            StyleRow style = featureStyle.getStyle();

            if (style != null) {

                if (style.hasFillColor()) {
                    paint = getStylePaint(style, FeatureDrawType.FILL);
                } else {
                    hasStyleColor = style.hasColor();
                }

            }

        }

        if (paint == null && !hasStyleColor && fillPolygon) {
            paint = polygonFillPaint;
        }

        return paint;
    }

protected Paint getPolygonFillPaint ( FeatureStyle featureStyle ) { Paint paint = null ; boolean hasStyleColor = false ; if ( featureStyle != null ) { StyleRow style = featureStyle . getStyle ( ) ; if ( style != null ) { if ( style . hasFillColor ( ) ) { paint = getStylePaint ( style , FeatureDrawType . FILL ) ; } else { hasStyleColor = style . hasColor ( ) ; } } } if ( paint == null && ! hasStyleColor && fillPolygon ) { paint = polygonFillPaint ; } return paint ; }

Get the polygon fill paint for the feature style, or return the default paint

@param featureStyle feature style
@return paint

Get the polygon fill paint for the feature style or return the default paint


private Paint getFeatureStylePaint(FeatureStyle featureStyle, FeatureDrawType drawType) {

        Paint paint = null;

        if (featureStyle != null) {

            StyleRow style = featureStyle.getStyle();

            if (style != null && style.hasColor()) {

                paint = getStylePaint(style, drawType);

            }
        }

        return paint;
    }

private Paint getFeatureStylePaint ( FeatureStyle featureStyle , FeatureDrawType drawType ) { Paint paint = null ; if ( featureStyle != null ) { StyleRow style = featureStyle . getStyle ( ) ; if ( style != null && style . hasColor ( ) ) { paint = getStylePaint ( style , drawType ) ; } } return paint ; }

Get the feature style paint from cache, or create and cache it

@param featureStyle feature style
@param drawType     draw type
@return feature style paint

Get the feature style paint from cache or create and cache it


private Paint getStylePaint(StyleRow style, FeatureDrawType drawType) {

        Paint paint = featurePaintCache.getPaint(style, drawType);

        if (paint == null) {

            Color color = null;
            Style paintStyle = null;
            Float strokeWidth = null;

            switch (drawType) {
                case CIRCLE:
                    color = style.getColorOrDefault();
                    paintStyle = Style.FILL;
                    break;
                case STROKE:
                    color = style.getColorOrDefault();
                    paintStyle = Style.STROKE;
                    strokeWidth = this.density * (float) style.getWidthOrDefault();
                    break;
                case FILL:
                    color = style.getFillColor();
                    paintStyle = Style.FILL;
                    strokeWidth = this.density * (float) style.getWidthOrDefault();
                    break;
                default:
                    throw new GeoPackageException("Unsupported Draw Type: " + drawType);
            }

            Paint stylePaint = new Paint();
            stylePaint.setAntiAlias(true);
            stylePaint.setStyle(paintStyle);
            stylePaint.setColor(color.getColorWithAlpha());
            if (strokeWidth != null) {
                stylePaint.setStrokeWidth(strokeWidth);
            }

            synchronized (featurePaintCache) {

                paint = featurePaintCache.getPaint(style, drawType);

                if (paint == null) {
                    featurePaintCache.setPaint(style, drawType, stylePaint);
                    paint = stylePaint;
                }

            }
        }

        return paint;
    }

private
Paint
getStylePaint
(
StyleRow
style
,
FeatureDrawType
drawType
)
{
Paint
paint
=
featurePaintCache
.
getPaint
(
style
,
drawType
)
;
if
(
paint
==
)
{
Color
color
=
;
Style
paintStyle
=
;
Float
strokeWidth
=
;
switch
(
drawType
)
{
case
CIRCLE
:
color
=
style
.
getColorOrDefault
(
)
;
paintStyle
=
Style
.
FILL
;
break
;
case
STROKE
:
color
=
style
.
getColorOrDefault
(
)
;
paintStyle
=
Style
.
STROKE
;
strokeWidth
=
this
.
density
*
(
float
)
style
.
getWidthOrDefault
(
)
;
break
;
case
FILL
:
color
=
style
.
getFillColor
(
)
;
paintStyle
=
Style
.
FILL
;
strokeWidth
=
this
.
density
*
(
float
)
style
.
getWidthOrDefault
(
)
;
break
;
default
:
throw
new
GeoPackageException
(
"Unsupported Draw Type: "
+
drawType
)
;
}
Paint
stylePaint
=
new
Paint
(
)
;
stylePaint
.
setAntiAlias
(
true
)
;
stylePaint
.
setStyle
(
paintStyle
)
;
stylePaint
.
setColor
(
color
.
getColorWithAlpha
(
)
)
;
if
(
strokeWidth
!=
)
{
stylePaint
.
setStrokeWidth
(
strokeWidth
)
;
}
synchronized
(
featurePaintCache
)
{
paint
=
featurePaintCache
.
getPaint
(
style
,
drawType
)
;
if
(
paint
==
)
{
featurePaintCache
.
setPaint
(
style
,
drawType
,
stylePaint
)
;
paint
=
stylePaint
;
}
}
}
return
paint
;
}

Get the style paint from cache, or create and cache it

@param style    style row
@param drawType draw type
@return paint

Get the style paint from cache or create and cache it


public Paint getPaint(StyleRow styleRow, FeatureDrawType type) {
        return getPaint(styleRow.getId(), type);
    }

public Paint getPaint ( StyleRow styleRow , FeatureDrawType type ) { return getPaint ( styleRow . getId ( ) , type ) ; }

Get the paint for the style row and draw type

@param styleRow style row
@param type     feature draw type
@return paint


public Paint getPaint(long styleId, FeatureDrawType type) {
        Paint paint = null;
        FeaturePaint featurePaint = getFeaturePaint(styleId);
        if (featurePaint != null) {
            paint = featurePaint.getPaint(type);
        }
        return paint;
    }

public Paint getPaint ( long styleId , FeatureDrawType type ) { Paint paint = null ; FeaturePaint featurePaint = getFeaturePaint ( styleId ) ; if ( featurePaint != null ) { paint = featurePaint . getPaint ( type ) ; } return paint ; }

Get the paint for the style row id and draw type

@param styleId style row id
@param type    feature draw type
@return paint


public Bitmap put(IconRow iconRow, Bitmap bitmap) {
        return put(iconRow.getId(), bitmap);
    }

public Bitmap put ( IconRow iconRow , Bitmap bitmap ) { return put ( iconRow . getId ( ) , bitmap ) ; }

Cache the icon bitmap for the icon row

@param iconRow icon row
@param bitmap  icon bitmap
@return previous cached icon bitmap or null


public static Bitmap createIcon(IconRow icon, float density, IconCache iconCache) {

        Bitmap iconImage = null;

        if (icon != null) {

            if (iconCache != null) {
                iconImage = iconCache.get(icon.getId());
            }

            if (iconImage == null) {

                BitmapFactory.Options options = icon.getDataBounds();
                int dataWidth = options.outWidth;
                int dataHeight = options.outHeight;

                double styleWidth = dataWidth;
                double styleHeight = dataHeight;

                double widthDensity = DisplayMetrics.DENSITY_DEFAULT;
                double heightDensity = DisplayMetrics.DENSITY_DEFAULT;

                if (icon.getWidth() != null) {
                    styleWidth = icon.getWidth();
                    double widthRatio = dataWidth / styleWidth;
                    widthDensity *= widthRatio;
                    if (icon.getHeight() == null) {
                        heightDensity = widthDensity;
                    }
                }

                if (icon.getHeight() != null) {
                    styleHeight = icon.getHeight();
                    double heightRatio = dataHeight / styleHeight;
                    heightDensity *= heightRatio;
                    if (icon.getWidth() == null) {
                        widthDensity = heightDensity;
                    }
                }

                options = new BitmapFactory.Options();
                options.inDensity = (int) (Math.min(widthDensity, heightDensity) + 0.5f);
                options.inTargetDensity = (int) (DisplayMetrics.DENSITY_DEFAULT * density + 0.5f);

                iconImage = icon.getDataBitmap(options);

                if (widthDensity != heightDensity) {

                    int width = (int) (styleWidth * density + 0.5f);
                    int height = (int) (styleHeight * density + 0.5f);

                    if (width != iconImage.getWidth() || height != iconImage.getHeight()) {
                        Bitmap scaledBitmap = Bitmap.createScaledBitmap(iconImage, width, height, false);
                        iconImage.recycle();
                        iconImage = scaledBitmap;
                    }

                }

                if (iconCache != null) {
                    iconCache.put(icon.getId(), iconImage);
                }
            }

        }

        return iconImage;
    }

public static Bitmap createIcon ( IconRow icon , float density , IconCache iconCache ) { Bitmap iconImage = null ; if ( icon != null ) { if ( iconCache != null ) { iconImage = iconCache . get ( icon . getId ( ) ) ; } if ( iconImage == null ) { BitmapFactory . Options options = icon . getDataBounds ( ) ; int dataWidth = options . outWidth ; int dataHeight = options . outHeight ; double styleWidth = dataWidth ; double styleHeight = dataHeight ; double widthDensity = DisplayMetrics . DENSITY_DEFAULT ; double heightDensity = DisplayMetrics . DENSITY_DEFAULT ; if ( icon . getWidth ( ) != null ) { styleWidth = icon . getWidth ( ) ; double widthRatio = dataWidth / styleWidth ; widthDensity *= widthRatio ; if ( icon . getHeight ( ) == null ) { heightDensity = widthDensity ; } } if ( icon . getHeight ( ) != null ) { styleHeight = icon . getHeight ( ) ; double heightRatio = dataHeight / styleHeight ; heightDensity *= heightRatio ; if ( icon . getWidth ( ) == null ) { widthDensity = heightDensity ; } } options = new BitmapFactory . Options ( ) ; options . inDensity = ( int ) ( Math . min ( widthDensity , heightDensity ) + 0.5f ) ; options . inTargetDensity = ( int ) ( DisplayMetrics . DENSITY_DEFAULT * density + 0.5f ) ; iconImage = icon . getDataBitmap ( options ) ; if ( widthDensity != heightDensity ) { int width = ( int ) ( styleWidth * density + 0.5f ) ; int height = ( int ) ( styleHeight * density + 0.5f ) ; if ( width != iconImage . getWidth ( ) || height != iconImage . getHeight ( ) ) { Bitmap scaledBitmap = Bitmap . createScaledBitmap ( iconImage , width , height , false ) ; iconImage . recycle ( ) ; iconImage = scaledBitmap ; } } if ( iconCache != null ) { iconCache . put ( icon . getId ( ) , iconImage ) ; } } } return iconImage ; }

Create or retrieve from cache an icon bitmap for the icon row

@param icon      icon row
@param density   display density: {@link android.util.DisplayMetrics#density}
@param iconCache icon cache
@return icon bitmap


public static ContentValues quoteWrap(ContentValues values) {
        ContentValues quoteValues = null;
        if (values != null) {

            Map<String, Object> quoteMap = new HashMap<>();
            for (Map.Entry<String, Object> value : values.valueSet()) {
                quoteMap.put(CoreSQLUtils.quoteWrap(value.getKey()), value.getValue());
            }

            Parcel parcel = Parcel.obtain();
            parcel.writeMap(quoteMap);
            parcel.setDataPosition(0);
            quoteValues = ContentValues.CREATOR.createFromParcel(parcel);
            parcel.recycle();
        }

        return quoteValues;
    }

public static ContentValues quoteWrap ( ContentValues values ) { ContentValues quoteValues = null ; if ( values != null ) { Map < String , Object > quoteMap = new HashMap <> ( ) ; for ( Map . Entry < String , Object > value : values . valueSet ( ) ) { quoteMap . put ( CoreSQLUtils . quoteWrap ( value . getKey ( ) ) , value . getValue ( ) ) ; } Parcel parcel = Parcel . obtain ( ) ; parcel . writeMap ( quoteMap ) ; parcel . setDataPosition ( 0 ) ; quoteValues = ContentValues . CREATOR . createFromParcel ( parcel ) ; parcel . recycle ( ) ; } return quoteValues ; }

Wrap the content values names in quotes

@param values content values
@return quoted content values


public Bitmap createBitmap() {

        Bitmap bitmap = null;
        Canvas canvas = null;

        for (int layer = 0; layer < 4; layer++) {

            Bitmap layerBitmap = layeredBitmap[layer];

            if (layerBitmap != null) {

                if (bitmap == null) {
                    bitmap = layerBitmap;
                    canvas = layeredCanvas[layer];
                } else {
                    canvas.drawBitmap(layerBitmap, new Matrix(), null);
                    layerBitmap.recycle();
                }

                layeredBitmap[layer] = null;
                layeredCanvas[layer] = null;
            }
        }

        return bitmap;
    }

public Bitmap createBitmap ( ) { Bitmap bitmap = null ; Canvas canvas = null ; for ( int layer = 0 ; layer < 4 ; layer ++ ) { Bitmap layerBitmap = layeredBitmap [ layer ] ; if ( layerBitmap != null ) { if ( bitmap == null ) { bitmap = layerBitmap ; canvas = layeredCanvas [ layer ] ; } else { canvas . drawBitmap ( layerBitmap , new Matrix ( ) , null ) ; layerBitmap . recycle ( ) ; } layeredBitmap [ layer ] = null ; layeredCanvas [ layer ] = null ; } } return bitmap ; }

Create the final bitmap from the layers, resets the layers

@return bitmap

Create the final bitmap from the layers resets the layers


public void recycle() {
        for (int layer = 0; layer < 4; layer++) {
            Bitmap bitmap = layeredBitmap[layer];
            if (bitmap != null) {
                bitmap.recycle();
                layeredBitmap[layer] = null;
                layeredCanvas[layer] = null;
            }
        }
    }

public void recycle ( ) { for ( int layer = 0 ; layer < 4 ; layer ++ ) { Bitmap bitmap = layeredBitmap [ layer ] ; if ( bitmap != null ) { bitmap . recycle ( ) ; layeredBitmap [ layer ] = null ; layeredCanvas [ layer ] = null ; } } }


private Bitmap getBitmap(int layer) {
        Bitmap bitmap = layeredBitmap[layer];
        if (bitmap == null) {
            createBitmapAndCanvas(layer);
            bitmap = layeredBitmap[layer];
        }
        return bitmap;
    }

private Bitmap getBitmap ( int layer ) { Bitmap bitmap = layeredBitmap [ layer ] ; if ( bitmap == null ) { createBitmapAndCanvas ( layer ) ; bitmap = layeredBitmap [ layer ] ; } return bitmap ; }

Get the bitmap for the layer index

@param layer layer index
@return bitmap


private Canvas getCanvas(int layer) {
        Canvas canvas = layeredCanvas[layer];
        if (canvas == null) {
            createBitmapAndCanvas(layer);
            canvas = layeredCanvas[layer];
        }
        return canvas;
    }

private Canvas getCanvas ( int layer ) { Canvas canvas = layeredCanvas [ layer ] ; if ( canvas == null ) { createBitmapAndCanvas ( layer ) ; canvas = layeredCanvas [ layer ] ; } return canvas ; }

Get the canvas for the layer index

@param layer layer index
@return canvas


private void createBitmapAndCanvas(int layer) {
        layeredBitmap[layer] = Bitmap.createBitmap(tileWidth,
                tileHeight, Bitmap.Config.ARGB_8888);
        layeredCanvas[layer] = new Canvas(layeredBitmap[layer]);
    }

private void createBitmapAndCanvas ( int layer ) { layeredBitmap [ layer ] = Bitmap . createBitmap ( tileWidth , tileHeight , Bitmap . Config . ARGB_8888 ) ; layeredCanvas [ layer ] = new Canvas ( layeredBitmap [ layer ] ) ; }

Create a new empty Bitmap and Canvas

@param layer layer index


private StyleMappingDao getMappingDao(String tablePrefix,
                                          String featureTable) {
        String tableName = tablePrefix + featureTable;
        StyleMappingDao dao = null;
        if (geoPackage.isTable(tableName)) {
            dao = new StyleMappingDao(relatedTables.getUserDao(tableName));
        }
        return dao;
    }

private StyleMappingDao getMappingDao ( String tablePrefix , String featureTable ) { String tableName = tablePrefix + featureTable ; StyleMappingDao dao = null ; if ( geoPackage . isTable ( tableName ) ) { dao = new StyleMappingDao ( relatedTables . getUserDao ( tableName ) ) ; } return dao ; }

Get a Style Mapping DAO from a table name

@param tablePrefix  table name prefix
@param featureTable feature table
@return style mapping dao


public StyleDao getStyleDao() {
        StyleDao styleDao = null;
        if (geoPackage.isTable(StyleTable.TABLE_NAME)) {
            AttributesDao attributesDao = getGeoPackage().getAttributesDao(
                    StyleTable.TABLE_NAME);
            styleDao = new StyleDao(attributesDao);
            relatedTables.setContents(styleDao.getTable());
        }
        return styleDao;
    }

public StyleDao getStyleDao ( ) { StyleDao styleDao = null ; if ( geoPackage . isTable ( StyleTable . TABLE_NAME ) ) { AttributesDao attributesDao = getGeoPackage ( ) . getAttributesDao ( StyleTable . TABLE_NAME ) ; styleDao = new StyleDao ( attributesDao ) ; relatedTables . setContents ( styleDao . getTable ( ) ) ; } return styleDao ; }


public IconDao getIconDao() {
        IconDao iconDao = null;
        if (geoPackage.isTable(IconTable.TABLE_NAME)) {
            iconDao = new IconDao(
                    relatedTables.getUserDao(IconTable.TABLE_NAME));
            relatedTables.setContents(iconDao.getTable());
        }
        return iconDao;
    }

public IconDao getIconDao ( ) { IconDao iconDao = null ; if ( geoPackage . isTable ( IconTable . TABLE_NAME ) ) { iconDao = new IconDao ( relatedTables . getUserDao ( IconTable . TABLE_NAME ) ) ; relatedTables . setContents ( iconDao . getTable ( ) ) ; } return iconDao ; }


public FeatureStyles getTableFeatureStyles(String featureTable) {

        FeatureStyles featureStyles = null;

        Long id = contentsId.getId(featureTable);
        if (id != null) {

            Styles styles = getTableStyles(featureTable, id);
            Icons icons = getTableIcons(featureTable, id);

            if (styles != null || icons != null) {
                featureStyles = new FeatureStyles(styles, icons);
            }

        }

        return featureStyles;
    }

public FeatureStyles getTableFeatureStyles ( String featureTable ) { FeatureStyles featureStyles = null ; Long id = contentsId . getId ( featureTable ) ; if ( id != null ) { Styles styles = getTableStyles ( featureTable , id ) ; Icons icons = getTableIcons ( featureTable , id ) ; if ( styles != null || icons != null ) { featureStyles = new FeatureStyles ( styles , icons ) ; } } return featureStyles ; }

Get the feature table default feature styles

@param featureTable feature table
@return table feature styles or null


public Styles getTableStyles(String featureTable) {
        Styles styles = null;
        Long id = contentsId.getId(featureTable);
        if (id != null) {
            styles = getTableStyles(featureTable, id);
        }
        return styles;
    }

public Styles getTableStyles ( String featureTable ) { Styles styles = null ; Long id = contentsId . getId ( featureTable ) ; if ( id != null ) { styles = getTableStyles ( featureTable , id ) ; } return styles ; }

Get the feature table default styles

@param featureTable feature table
@return table styles or null


public StyleRow getTableStyle(String featureTable, GeometryType geometryType) {
        StyleRow styleRow = null;
        Styles tableStyles = getTableStyles(featureTable);
        if (tableStyles != null) {
            styleRow = tableStyles.getStyle(geometryType);
        }
        return styleRow;
    }

public StyleRow getTableStyle ( String featureTable , GeometryType geometryType ) { StyleRow styleRow = null ; Styles tableStyles = getTableStyles ( featureTable ) ; if ( tableStyles != null ) { styleRow = tableStyles . getStyle ( geometryType ) ; } return styleRow ; }

Get the style of the feature table and geometry type

@param featureTable feature table
@param geometryType geometry type
@return style row


public Icons getTableIcons(String featureTable) {
        Icons icons = null;
        Long id = contentsId.getId(featureTable);
        if (id != null) {
            icons = getTableIcons(featureTable, id);
        }
        return icons;
    }

public Icons getTableIcons ( String featureTable ) { Icons icons = null ; Long id = contentsId . getId ( featureTable ) ; if ( id != null ) { icons = getTableIcons ( featureTable , id ) ; } return icons ; }

Get the feature table default icons

@param featureTable feature table
@return table icons or null


public IconRow getTableIcon(String featureTable, GeometryType geometryType) {
        IconRow iconRow = null;
        Icons tableIcons = getTableIcons(featureTable);
        if (tableIcons != null) {
            iconRow = tableIcons.getIcon(geometryType);
        }
        return iconRow;
    }

public IconRow getTableIcon ( String featureTable , GeometryType geometryType ) { IconRow iconRow = null ; Icons tableIcons = getTableIcons ( featureTable ) ; if ( tableIcons != null ) { iconRow = tableIcons . getIcon ( geometryType ) ; } return iconRow ; }

Get the icon of the feature table and geometry type

@param featureTable feature table
@param geometryType geometry type
@return icon row


public FeatureStyles getFeatureStyles(FeatureRow featureRow) {
        return getFeatureStyles(featureRow.getTable().getTableName(),
                featureRow.getId());
    }

public FeatureStyles getFeatureStyles ( FeatureRow featureRow ) { return getFeatureStyles ( featureRow . getTable ( ) . getTableName ( ) , featureRow . getId ( ) ) ; }

Get the feature styles for the feature row

@param featureRow feature row
@return feature styles or null


public FeatureStyles getFeatureStyles(String featureTable, long featureId) {

        Styles styles = getStyles(featureTable, featureId);
        Icons icons = getIcons(featureTable, featureId);

        FeatureStyles featureStyles = null;
        if (styles != null || icons != null) {
            featureStyles = new FeatureStyles(styles, icons);
        }

        return featureStyles;
    }

public FeatureStyles getFeatureStyles ( String featureTable , long featureId ) { Styles styles = getStyles ( featureTable , featureId ) ; Icons icons = getIcons ( featureTable , featureId ) ; FeatureStyles featureStyles = null ; if ( styles != null || icons != null ) { featureStyles = new FeatureStyles ( styles , icons ) ; } return featureStyles ; }

Get the feature styles for the feature table and feature id

@param featureTable feature table
@param featureId    feature id
@return feature styles or null


public Styles getStyles(FeatureRow featureRow) {
        return getStyles(featureRow.getTable().getTableName(),
                featureRow.getId());
    }

public Styles getStyles ( FeatureRow featureRow ) { return getStyles ( featureRow . getTable ( ) . getTableName ( ) , featureRow . getId ( ) ) ; }

Get the styles for the feature row

@param featureRow feature row
@return styles or null


public Icons getIcons(FeatureRow featureRow) {
        return getIcons(featureRow.getTable().getTableName(),
                featureRow.getId());
    }

public Icons getIcons ( FeatureRow featureRow ) { return getIcons ( featureRow . getTable ( ) . getTableName ( ) , featureRow . getId ( ) ) ; }

Get the icons for the feature row

@param featureRow feature row
@return icons or null


private Styles getStyles(long featureId, StyleMappingDao mappingDao) {

        Styles styles = null;

        if (mappingDao != null) {

            StyleDao styleDao = getStyleDao();

            if (styleDao != null) {

                List<StyleMappingRow> styleMappingRows = mappingDao
                        .queryByBaseFeatureId(featureId);
                if (!styleMappingRows.isEmpty()) {

                    for (StyleMappingRow styleMappingRow : styleMappingRows) {

                        StyleRow styleRow = styleDao
                                .queryForRow(styleMappingRow);
                        if (styleRow != null) {
                            if (styles == null) {
                                styles = new Styles();
                            }
                            styles.setStyle(styleRow,
                                    styleMappingRow.getGeometryType());
                        }
                    }
                }
            }
        }

        return styles;
    }

private Styles getStyles ( long featureId , StyleMappingDao mappingDao ) { Styles styles = null ; if ( mappingDao != null ) { StyleDao styleDao = getStyleDao ( ) ; if ( styleDao != null ) { List < StyleMappingRow > styleMappingRows = mappingDao . queryByBaseFeatureId ( featureId ) ; if ( ! styleMappingRows . isEmpty ( ) ) { for ( StyleMappingRow styleMappingRow : styleMappingRows ) { StyleRow styleRow = styleDao . queryForRow ( styleMappingRow ) ; if ( styleRow != null ) { if ( styles == null ) { styles = new Styles ( ) ; } styles . setStyle ( styleRow , styleMappingRow . getGeometryType ( ) ) ; } } } } } return styles ; }

Get the styles for feature id from the style mapping dao

@param featureId  geometry feature id or feature table id
@param mappingDao style mapping dao
@return styles


private Icons getIcons(long featureId, StyleMappingDao mappingDao) {

        Icons icons = null;

        if (mappingDao != null) {

            IconDao iconDao = getIconDao();
            if (iconDao != null) {

                List<StyleMappingRow> styleMappingRows = mappingDao
                        .queryByBaseFeatureId(featureId);
                if (!styleMappingRows.isEmpty()) {

                    for (StyleMappingRow styleMappingRow : styleMappingRows) {

                        IconRow iconRow = iconDao.queryForRow(styleMappingRow);
                        if (iconRow != null) {
                            if (icons == null) {
                                icons = new Icons();
                            }
                            icons.setIcon(iconRow,
                                    styleMappingRow.getGeometryType());
                        }
                    }
                }
            }
        }

        return icons;
    }

private Icons getIcons ( long featureId , StyleMappingDao mappingDao ) { Icons icons = null ; if ( mappingDao != null ) { IconDao iconDao = getIconDao ( ) ; if ( iconDao != null ) { List < StyleMappingRow > styleMappingRows = mappingDao . queryByBaseFeatureId ( featureId ) ; if ( ! styleMappingRows . isEmpty ( ) ) { for ( StyleMappingRow styleMappingRow : styleMappingRows ) { IconRow iconRow = iconDao . queryForRow ( styleMappingRow ) ; if ( iconRow != null ) { if ( icons == null ) { icons = new Icons ( ) ; } icons . setIcon ( iconRow , styleMappingRow . getGeometryType ( ) ) ; } } } } } return icons ; }

Get the icons for feature id from the icon mapping dao

@param featureId  geometry feature id or feature table id
@param mappingDao icon mapping dao
@return icons


public void setTableFeatureStyles(String featureTable,
                                      FeatureStyles featureStyles) {
        if (featureStyles != null) {
            setTableStyles(featureTable, featureStyles.getStyles());
            setTableIcons(featureTable, featureStyles.getIcons());
        } else {
            deleteTableFeatureStyles(featureTable);
        }
    }

public void setTableFeatureStyles ( String featureTable , FeatureStyles featureStyles ) { if ( featureStyles != null ) { setTableStyles ( featureTable , featureStyles . getStyles ( ) ) ; setTableIcons ( featureTable , featureStyles . getIcons ( ) ) ; } else { deleteTableFeatureStyles ( featureTable ) ; } }

Set the feature table default feature styles

@param featureTable  feature table
@param featureStyles default feature styles


public void setTableStyles(String featureTable, Styles styles) {

        deleteTableStyles(featureTable);

        if (styles != null) {

            if (styles.getDefault() != null) {
                setTableStyleDefault(featureTable, styles.getDefault());
            }

            for (Entry<GeometryType, StyleRow> style : styles.getStyles()
                    .entrySet()) {
                setTableStyle(featureTable, style.getKey(), style.getValue());
            }

        }
    }

public void setTableStyles ( String featureTable , Styles styles ) { deleteTableStyles ( featureTable ) ; if ( styles != null ) { if ( styles . getDefault ( ) != null ) { setTableStyleDefault ( featureTable , styles . getDefault ( ) ) ; } for ( Entry < GeometryType , StyleRow > style : styles . getStyles ( ) . entrySet ( ) ) { setTableStyle ( featureTable , style . getKey ( ) , style . getValue ( ) ) ; } } }

Set the feature table default styles

@param featureTable feature table
@param styles       default styles


public void setTableIcons(String featureTable, Icons icons) {

        deleteTableIcons(featureTable);

        if (icons != null) {

            if (icons.getDefault() != null) {
                setTableIconDefault(featureTable, icons.getDefault());
            }

            for (Entry<GeometryType, IconRow> icon : icons.getIcons()
                    .entrySet()) {
                setTableIcon(featureTable, icon.getKey(), icon.getValue());
            }

        }

    }

public void setTableIcons ( String featureTable , Icons icons ) { deleteTableIcons ( featureTable ) ; if ( icons != null ) { if ( icons . getDefault ( ) != null ) { setTableIconDefault ( featureTable , icons . getDefault ( ) ) ; } for ( Entry < GeometryType , IconRow > icon : icons . getIcons ( ) . entrySet ( ) ) { setTableIcon ( featureTable , icon . getKey ( ) , icon . getValue ( ) ) ; } } }

Set the feature table default icons

@param featureTable feature table
@param icons        default icons


public void setFeatureStyles(FeatureRow featureRow,
                                 FeatureStyles featureStyles) {
        setFeatureStyles(featureRow.getTable().getTableName(),
                featureRow.getId(), featureStyles);
    }

public void setFeatureStyles ( FeatureRow featureRow , FeatureStyles featureStyles ) { setFeatureStyles ( featureRow . getTable ( ) . getTableName ( ) , featureRow . getId ( ) , featureStyles ) ; }

Set the feature styles for the feature row

@param featureRow    feature row
@param featureStyles feature styles


public void setFeatureStyles(String featureTable, long featureId,
                                 FeatureStyles featureStyles) {
        if (featureStyles != null) {
            setStyles(featureTable, featureId, featureStyles.getStyles());
            setIcons(featureTable, featureId, featureStyles.getIcons());
        } else {
            deleteStyles(featureTable, featureId);
            deleteIcons(featureTable, featureId);
        }
    }

public void setFeatureStyles ( String featureTable , long featureId , FeatureStyles featureStyles ) { if ( featureStyles != null ) { setStyles ( featureTable , featureId , featureStyles . getStyles ( ) ) ; setIcons ( featureTable , featureId , featureStyles . getIcons ( ) ) ; } else { deleteStyles ( featureTable , featureId ) ; deleteIcons ( featureTable , featureId ) ; } }

Set the feature styles for the feature table and feature id

@param featureTable  feature table
@param featureId     feature id
@param featureStyles feature styles


public void setStyles(FeatureRow featureRow, Styles styles) {
        setStyles(featureRow.getTable().getTableName(), featureRow.getId(),
                styles);
    }

public void setStyles ( FeatureRow featureRow , Styles styles ) { setStyles ( featureRow . getTable ( ) . getTableName ( ) , featureRow . getId ( ) , styles ) ; }

Set the styles for the feature row

@param featureRow feature row
@param styles     styles


public void setStyles(String featureTable, long featureId, Styles styles) {
        deleteStyles(featureTable, featureId);

        if (styles != null) {

            if (styles.getDefault() != null) {
                setStyleDefault(featureTable, featureId, styles.getDefault());
            }

            for (Entry<GeometryType, StyleRow> style : styles.getStyles()
                    .entrySet()) {
                setStyle(featureTable, featureId, style.getKey(),
                        style.getValue());
            }

        }
    }

public void setStyles ( String featureTable , long featureId , Styles styles ) { deleteStyles ( featureTable , featureId ) ; if ( styles != null ) { if ( styles . getDefault ( ) != null ) { setStyleDefault ( featureTable , featureId , styles . getDefault ( ) ) ; } for ( Entry < GeometryType , StyleRow > style : styles . getStyles ( ) . entrySet ( ) ) { setStyle ( featureTable , featureId , style . getKey ( ) , style . getValue ( ) ) ; } } }

Set the styles for the feature table and feature id

@param featureTable feature table
@param featureId    feature id
@param styles       styles


public void setStyle(FeatureRow featureRow, StyleRow style) {
        setStyle(featureRow, featureRow.getGeometryType(), style);
    }

public void setStyle ( FeatureRow featureRow , StyleRow style ) { setStyle ( featureRow , featureRow . getGeometryType ( ) , style ) ; }

Set the style of the feature row

@param featureRow feature row
@param style      style row


public void setStyleDefault(FeatureRow featureRow, StyleRow style) {
        setStyle(featureRow.getTable().getTableName(), featureRow.getId(),
                null, style);
    }

public void setStyleDefault ( FeatureRow featureRow , StyleRow style ) { setStyle ( featureRow . getTable ( ) . getTableName ( ) , featureRow . getId ( ) , null , style ) ; }

Set the default style of the feature row

@param featureRow feature row
@param style      style row


public void setStyleDefault(String featureTable, long featureId,
                                StyleRow style) {
        setStyle(featureTable, featureId, null, style);
    }

public void setStyleDefault ( String featureTable , long featureId , StyleRow style ) { setStyle ( featureTable , featureId , null , style ) ; }

Set the default style of the feature

@param featureTable feature table
@param featureId    feature id
@param style        style row


public void setIcons(FeatureRow featureRow, Icons icons) {
        setIcons(featureRow.getTable().getTableName(), featureRow.getId(),
                icons);
    }

public void setIcons ( FeatureRow featureRow , Icons icons ) { setIcons ( featureRow . getTable ( ) . getTableName ( ) , featureRow . getId ( ) , icons ) ; }

Set the icons for the feature row

@param featureRow feature row
@param icons      icons


public void setIcons(String featureTable, long featureId, Icons icons) {
        deleteIcons(featureTable, featureId);

        if (icons != null) {

            if (icons.getDefault() != null) {
                setIconDefault(featureTable, featureId, icons.getDefault());
            }

            for (Entry<GeometryType, IconRow> icon : icons.getIcons()
                    .entrySet()) {
                setIcon(featureTable, featureId, icon.getKey(), icon.getValue());
            }

        }
    }

public void setIcons ( String featureTable , long featureId , Icons icons ) { deleteIcons ( featureTable , featureId ) ; if ( icons != null ) { if ( icons . getDefault ( ) != null ) { setIconDefault ( featureTable , featureId , icons . getDefault ( ) ) ; } for ( Entry < GeometryType , IconRow > icon : icons . getIcons ( ) . entrySet ( ) ) { setIcon ( featureTable , featureId , icon . getKey ( ) , icon . getValue ( ) ) ; } } }

Set the icons for the feature table and feature id

@param featureTable feature table
@param featureId    feature id
@param icons        icons


public void setIcon(FeatureRow featureRow, IconRow icon) {
        setIcon(featureRow, featureRow.getGeometryType(), icon);
    }

public void setIcon ( FeatureRow featureRow , IconRow icon ) { setIcon ( featureRow , featureRow . getGeometryType ( ) , icon ) ; }

Set the icon of the feature row

@param featureRow feature row
@param icon       icon row


public void setIconDefault(FeatureRow featureRow, IconRow icon) {
        setIcon(featureRow.getTable().getTableName(), featureRow.getId(), null,
                icon);
    }

public void setIconDefault ( FeatureRow featureRow , IconRow icon ) { setIcon ( featureRow . getTable ( ) . getTableName ( ) , featureRow . getId ( ) , null , icon ) ; }

Set the default icon of the feature row

@param featureRow feature row
@param icon       icon row


public void setIconDefault(String featureTable, long featureId, IconRow icon) {
        setIcon(featureTable, featureId, null, icon);
    }

public void setIconDefault ( String featureTable , long featureId , IconRow icon ) { setIcon ( featureTable , featureId , null , icon ) ; }

Set the default icon of the feature

@param featureTable feature table
@param featureId    feature id
@param icon         icon row


private long getOrInsertStyle(StyleRow style) {
        long styleId;
        if (style.hasId()) {
            styleId = style.getId();
        } else {
            StyleDao styleDao = getStyleDao();
            styleId = styleDao.create(style);
        }
        return styleId;
    }

private long getOrInsertStyle ( StyleRow style ) { long styleId ; if ( style . hasId ( ) ) { styleId = style . getId ( ) ; } else { StyleDao styleDao = getStyleDao ( ) ; styleId = styleDao . create ( style ) ; } return styleId ; }

Get the style id, either from the existing style or by inserting a new
one

@param style style row
@return style id

Get the style id either from the existing style or by inserting a new one


private long getOrInsertIcon(IconRow icon) {
        long iconId;
        if (icon.hasId()) {
            iconId = icon.getId();
        } else {
            IconDao iconDao = getIconDao();
            iconId = iconDao.create(icon);
        }
        return iconId;
    }

private long getOrInsertIcon ( IconRow icon ) { long iconId ; if ( icon . hasId ( ) ) { iconId = icon . getId ( ) ; } else { IconDao iconDao = getIconDao ( ) ; iconId = iconDao . create ( icon ) ; } return iconId ; }

Get the icon id, either from the existing icon or by inserting a new one

@param icon icon row
@return icon id

Get the icon id either from the existing icon or by inserting a new one


private void insertStyleMapping(StyleMappingDao mappingDao, long baseId,
                                    long relatedId, GeometryType geometryType) {

        StyleMappingRow row = mappingDao.newRow();

        row.setBaseId(baseId);
        row.setRelatedId(relatedId);
        row.setGeometryType(geometryType);

        mappingDao.insert(row);
    }

private void insertStyleMapping ( StyleMappingDao mappingDao , long baseId , long relatedId , GeometryType geometryType ) { StyleMappingRow row = mappingDao . newRow ( ) ; row . setBaseId ( baseId ) ; row . setRelatedId ( relatedId ) ; row . setGeometryType ( geometryType ) ; mappingDao . insert ( row ) ; }

Insert a style mapping row

@param mappingDao   mapping dao
@param baseId       base id, either contents id or feature id
@param relatedId    related id, either style or icon id
@param geometryType geometry type or null


public void deleteTableStyle(String featureTable, GeometryType geometryType) {
        deleteTableMapping(getTableStyleMappingDao(featureTable), featureTable,
                geometryType);
    }

public void deleteTableStyle ( String featureTable , GeometryType geometryType ) { deleteTableMapping ( getTableStyleMappingDao ( featureTable ) , featureTable , geometryType ) ; }

Delete the feature table style for the geometry type

@param featureTable feature table
@param geometryType geometry type


public void deleteTableIcon(String featureTable, GeometryType geometryType) {
        deleteTableMapping(getTableIconMappingDao(featureTable), featureTable,
                geometryType);
    }

public void deleteTableIcon ( String featureTable , GeometryType geometryType ) { deleteTableMapping ( getTableIconMappingDao ( featureTable ) , featureTable , geometryType ) ; }

Delete the feature table icon for the geometry type

@param featureTable feature table
@param geometryType geometry type