Example usage for android.database.sqlite SQLiteDatabase execSQL

List of usage examples for android.database.sqlite SQLiteDatabase execSQL

Introduction

In this page you can find the example usage for android.database.sqlite SQLiteDatabase execSQL.

Prototype

public void execSQL(String sql) throws SQLException 

Source Link

Document

Execute a single SQL statement that is NOT a SELECT or any other SQL statement that returns data.

Usage

From source file:com.nextgis.maplib.map.VectorLayer.java

public String createFromGeoJSON(JSONObject geoJSONObject) {
    try {//from  ww w .  jav  a 2s.c  om
        //check crs
        boolean isWGS84 = true; //if no crs tag - WGS84 CRS
        if (geoJSONObject.has(GEOJSON_CRS)) {
            JSONObject crsJSONObject = geoJSONObject.getJSONObject(GEOJSON_CRS);
            //the link is unsupported yet.
            if (!crsJSONObject.getString(GEOJSON_TYPE).equals(GEOJSON_NAME)) {
                return mContext.getString(R.string.error_crs_unsuported);
            }
            JSONObject crsPropertiesJSONObject = crsJSONObject.getJSONObject(GEOJSON_PROPERTIES);
            String crsName = crsPropertiesJSONObject.getString(GEOJSON_NAME);
            if (crsName.equals("urn:ogc:def:crs:OGC:1.3:CRS84")) { // WGS84
                isWGS84 = true;
            } else if (crsName.equals("urn:ogc:def:crs:EPSG::3857") || crsName.equals("EPSG:3857")) { //Web Mercator
                isWGS84 = false;
            } else {
                return mContext.getString(R.string.error_crs_unsuported);
            }
        }

        //load contents to memory and reproject if needed
        JSONArray geoJSONFeatures = geoJSONObject.getJSONArray(GEOJSON_TYPE_FEATURES);
        if (0 == geoJSONFeatures.length()) {
            return mContext.getString(R.string.error_empty_dataset);
        }

        List<Feature> features = new ArrayList<>();
        List<Pair<String, Integer>> fields = new ArrayList<>();

        int geometryType = GTNone;
        for (int i = 0; i < geoJSONFeatures.length(); i++) {
            JSONObject jsonFeature = geoJSONFeatures.getJSONObject(i);
            //get geometry
            JSONObject jsonGeometry = jsonFeature.getJSONObject(GEOJSON_GEOMETRY);
            GeoGeometry geometry = GeoGeometry.fromJson(jsonGeometry);
            if (geometryType == GTNone) {
                geometryType = geometry.getType();
            } else if (!Geo.isGeometryTypeSame(geometryType, geometry.getType())) {
                //skip different geometry type
                continue;
            }

            //reproject if needed
            if (isWGS84) {
                geometry.setCRS(CRS_WGS84);
                geometry.project(CRS_WEB_MERCATOR);
            } else {
                geometry.setCRS(CRS_WEB_MERCATOR);
            }

            int nId = i;
            if (jsonFeature.has(GEOJSON_ID))
                nId = jsonFeature.getInt(GEOJSON_ID);
            Feature feature = new Feature(nId, fields); // ID == i
            feature.setGeometry(geometry);

            //normalize attributes
            JSONObject jsonAttributes = jsonFeature.getJSONObject(GEOJSON_PROPERTIES);
            Iterator<String> iter = jsonAttributes.keys();
            while (iter.hasNext()) {
                String key = iter.next();
                Object value = jsonAttributes.get(key);
                int nType = NOT_FOUND;
                //check type
                if (value instanceof Integer || value instanceof Long) {
                    nType = FTInteger;
                } else if (value instanceof Double || value instanceof Float) {
                    nType = FTReal;
                } else if (value instanceof Date) {
                    nType = FTDateTime;
                } else if (value instanceof String) {
                    nType = FTString;
                } else if (value instanceof JSONObject) {
                    nType = NOT_FOUND;
                    //the some list - need to check it type FTIntegerList, FTRealList, FTStringList
                }

                if (nType != NOT_FOUND) {
                    int fieldIndex = NOT_FOUND;
                    for (int j = 0; j < fields.size(); j++) {
                        if (fields.get(j).first.equals(key)) {
                            fieldIndex = j;
                        }
                    }
                    if (fieldIndex == NOT_FOUND) { //add new field
                        Pair<String, Integer> fieldKey = Pair.create(key, nType);
                        fieldIndex = fields.size();
                        fields.add(fieldKey);
                    }
                    feature.setFieldValue(fieldIndex, value);
                }
            }
            features.add(feature);
        }

        String tableCreate = "CREATE TABLE IF NOT EXISTS " + mPath.getName() + " ( " + //table name is the same as the folder of the layer
                "_ID INTEGER PRIMARY KEY, " + "GEOM BLOB";
        for (int i = 0; i < fields.size(); ++i) {
            Pair<String, Integer> field = fields.get(i);

            tableCreate += ", " + field.first + " ";
            switch (field.second) {
            case FTString:
                tableCreate += "TEXT";
                break;
            case FTInteger:
                tableCreate += "INTEGER";
                break;
            case FTReal:
                tableCreate += "REAL";
                break;
            case FTDateTime:
                tableCreate += "TIMESTAMP";
                break;
            }
        }
        tableCreate += " );";

        GeoEnvelope extents = new GeoEnvelope();
        for (Feature feature : features) {
            //update bbox
            extents.merge(feature.getGeometry().getEnvelope());
        }

        //1. create table and populate with values
        MapContentProviderHelper map = (MapContentProviderHelper) MapBase.getInstance();
        SQLiteDatabase db = map.getDatabase(true);
        db.execSQL(tableCreate);
        for (Feature feature : features) {
            ContentValues values = new ContentValues();
            values.put("_ID", feature.getId());
            try {
                values.put("GEOM", feature.getGeometry().toBlob());
            } catch (IOException e) {
                e.printStackTrace();
            }
            for (int i = 0; i < fields.size(); ++i) {
                if (!feature.isValuePresent(i))
                    continue;
                switch (fields.get(i).second) {
                case FTString:
                    values.put(fields.get(i).first, feature.getFieldValueAsString(i));
                    break;
                case FTInteger:
                    values.put(fields.get(i).first, (int) feature.getFieldValue(i));
                    break;
                case FTReal:
                    values.put(fields.get(i).first, (double) feature.getFieldValue(i));
                    break;
                case FTDateTime:
                    values.put(fields.get(i).first, feature.getFieldValueAsString(i));
                    break;
                }
            }
            db.insert(mPath.getName(), "", values);
        }

        //2. save the layer properties to config.json
        mGeometryType = geometryType;
        mExtents = extents;
        mIsInitialized = true;
        setDefaultRenderer();

        save();

        //3. fill the geometry and labels array
        mVectorCacheItems = new ArrayList<>();
        for (Feature feature : features) {
            mVectorCacheItems.add(new VectorCacheItem(feature.getGeometry(), feature.getId()));
        }

        if (null != mParent) { //notify the load is over
            LayerGroup layerGroup = (LayerGroup) mParent;
            layerGroup.onLayerChanged(this);
        }

        return "";
    } catch (JSONException e) {
        e.printStackTrace();
        return e.getLocalizedMessage();
    }
}

From source file:tritop.android.naturalselectionnews.DBHelper.java

@Override
public void onUpgrade(SQLiteDatabase db, int arg1, int arg2) {
    if (DEBUG_ON) {
        Log.e(LOGTAG, "On Upgrade ");
    }/*from  w  w  w . j av  a  2s  .c  om*/
    db.execSQL("DROP TABLE IF EXISTS " + WAR_STATS_TABLE_NAME);
    db.execSQL("DROP TABLE IF EXISTS " + KILL_STATS_TABLE_NAME);
    db.execSQL("DROP TABLE IF EXISTS " + NEWS_FEED_TABLE_NAME);
    db.execSQL("DROP TABLE IF EXISTS " + TWITTER_FEED_TABLE_NAME);
    onCreate(db);
}

From source file:net.willwebberley.gowertides.utils.WeatherDatabase.java

public Boolean insertSurfData(String data, SQLiteDatabase db) {
    /* Delete any current versions with the same request timestamps */
    try {/*from  w w w  .  ja v a2 s. c  o m*/
        JSONArray jsonArray = new JSONArray(data);
        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject surf = jsonArray.getJSONObject(i);
            db.execSQL("DELETE FROM surf WHERE timestamp = " + surf.getLong("timestamp"));
        }
    } catch (Exception e) {
        System.err.println("Could not delete data");
    }

    /* Now actually do the inserts! */
    try {
        JSONArray jsonArray = new JSONArray(data);
        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject surf = jsonArray.getJSONObject(i);
            int location = surf.getInt("location");
            long timestamp = surf.getLong("timestamp");
            long localtime = surf.getLong("local_time");
            int year = surf.getInt("year");
            int month = surf.getInt("month");
            int day = surf.getInt("day");
            int hour = surf.getInt("hour");
            int minute = surf.getInt("minute");
            int faded_rating = surf.getInt("faded_rating");
            int solid_rating = surf.getInt("solid_rating");
            double min_surf = surf.getDouble("min_surf_height");
            double abs_min_surf = surf.getDouble("abs_min_surf_height");
            double max_surf = surf.getDouble("max_surf_height");
            double abs_max_surf = surf.getDouble("abs_max_surf_height");
            double swell_height = surf.getDouble("swell_height");
            double swell_period = surf.getDouble("swell_period");
            double swell_angle = surf.getDouble("swell_angle");
            String swell_direction = surf.getString("swell_direction");
            String swell_chart_url = surf.getString("swell_chart");
            String period_chart_url = surf.getString("period_chart");
            String wind_chart_url = surf.getString("wind_chart");
            String pressure_chart_url = surf.getString("pressure_chart");
            String sst_chart_url = surf.getString("sst_chart");

            String inS = "INSERT INTO surf VALUES(" + location + "," + timestamp + "," + localtime + "," + year
                    + "," + month + "," + day + "," + hour + "," + minute + "," + faded_rating + ","
                    + solid_rating + "," + min_surf + "," + abs_min_surf + "," + max_surf + "," + abs_max_surf
                    + "," + swell_height + "," + swell_period + "," + swell_angle + ",'" + swell_direction
                    + "','" + swell_chart_url + "','" + period_chart_url + "','" + wind_chart_url + "','"
                    + pressure_chart_url + "','" + sst_chart_url + "')";
            db.execSQL(inS);
        }
    } catch (Exception e) {
        System.out.println(e);
        return false;
    }
    return true;
}

From source file:project.cs.lisa.database.IODatabase.java

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    Log.d(TAG, "Upgrading database to version " + newVersion);

    db.execSQL("DROP TABLE IF EXISTS " + TABLE_IO);
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_URL);

    onCreate(db);//from w  w w .j ava  2 s.  c  o  m
}

From source file:org.fitchfamily.android.wifi_backend.database.Database.java

@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion, int newVersion) {
    if (oldVersion < 2) { // upgrade to 2
        sqLiteDatabase.execSQL("ALTER TABLE " + TABLE_SAMPLES + " ADD COLUMN " + COL_MOVED_GUARD + " INTEGER;");

        sqLiteDatabase.execSQL("UPDATE " + TABLE_SAMPLES + " SET " + COL_MOVED_GUARD + "=0;");
    }/*from w ww  .j  a  v  a  2  s. c  o m*/

    if (oldVersion < 3) { // upgrade to 3
        sqLiteDatabase.execSQL("ALTER TABLE " + TABLE_SAMPLES + " ADD COLUMN " + COL_RADIUS + " REAL;");

        sqLiteDatabase.execSQL("UPDATE " + TABLE_SAMPLES + " SET " + COL_RADIUS + "=-1.0;");
    }

    if (oldVersion < 4) { // upgrade to 4
        sqLiteDatabase.execSQL("ALTER TABLE " + TABLE_SAMPLES + " ADD COLUMN " + COL_SSID + " TEXT;");
    }

    if (oldVersion < 5) { // upgrade to 5
        // Sqlite3 does not support dropping columns so we create a new table with our
        // current fields and copy the old data into it.
        sqLiteDatabase.execSQL("BEGIN TRANSACTION;");
        sqLiteDatabase.execSQL("ALTER TABLE " + TABLE_SAMPLES + " RENAME TO " + TABLE_SAMPLES + "_old;");
        sqLiteDatabase.execSQL("CREATE TABLE " + TABLE_SAMPLES + "(" + COL_RFID + " STRING PRIMARY KEY, "
                + COL_TYPE + " INTEGER, " + COL_SSID + " TEXT, " + COL_LATITUDE + " REAL, " + COL_LONGITUDE
                + " REAL, " + COL_RADIUS + " REAL, " + COL_MOVED_GUARD + " INTEGER, " + COL_CHANGED
                + " INTEGER, " + COL_LAT1 + " REAL, " + COL_LON1 + " REAL, " + COL_LAT2 + " REAL, " + COL_LON2
                + " REAL, " + COL_LAT3 + " REAL, " + COL_LON3 + " REAL);");

        sqLiteDatabase.execSQL("INSERT INTO " + TABLE_SAMPLES + "(" + COL_RFID + ", " + COL_SSID + ", "
                + COL_LATITUDE + ", " + COL_LONGITUDE + ", " + COL_RADIUS + ", " + COL_MOVED_GUARD + ", "
                + COL_LAT1 + ", " + COL_LON1 + ", " + COL_LAT2 + ", " + COL_LON2 + ", " + COL_LAT3 + ", "
                + COL_LON3 + ") SELECT " + COL_BSSID + ", " + COL_SSID + ", " + COL_LATITUDE + ", "
                + COL_LONGITUDE + ", " + COL_RADIUS + ", " + COL_MOVED_GUARD + ", " + COL_LAT1 + ", " + COL_LON1
                + ", " + COL_LAT2 + ", " + COL_LON2 + ", " + COL_LAT3 + ", " + COL_LON3 + " FROM "
                + TABLE_SAMPLES + "_old;");
        sqLiteDatabase.execSQL("DROP TABLE " + TABLE_SAMPLES + "_old;");
        sqLiteDatabase.execSQL("UPDATE " + TABLE_SAMPLES + " SET " + COL_TYPE + "=" + TYPE_WIFI + ";");
        sqLiteDatabase.execSQL("UPDATE " + TABLE_SAMPLES + " SET " + COL_CHANGED + "="
                + (CHANGED_AP1 + CHANGED_AP2 + CHANGED_AP3) + ";");
        sqLiteDatabase.execSQL("COMMIT;");
    }
}

From source file:info.staticfree.android.units.UnitUsageDBHelper.java

@Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL("CREATE TABLE '" + DB_USAGE_TABLE + "' (" + "'" + UsageEntry._ID + "' INTEGER PRIMARY KEY," + "'"
            + UsageEntry._UNIT + "' TEXT UNIQUE ON CONFLICT IGNORE," + "'" + UsageEntry._USE_COUNT
            + "' INTEGER," + "'" + UsageEntry._FACTOR_FPRINT + "' TEXT" + ")");
    db.execSQL("CREATE INDEX '" + DB_USAGE_INDEX + "' ON " + DB_USAGE_TABLE + " (" + UsageEntry._FACTOR_FPRINT
            + ")");

    db.execSQL("CREATE TABLE '" + DB_CLASSIFICATION_TABLE + "' (" + "'" + ClassificationEntry._ID
            + "' INTEGER PRIMARY KEY," + "'" + ClassificationEntry._DESCRIPTION + "' TEXT," + "'"
            + ClassificationEntry._FACTOR_FPRINT + "' TEXT UNIQUE" + ")");
    db.execSQL("CREATE UNIQUE INDEX '" + DB_CLASSIFICATION_INDEX + "' ON " + DB_CLASSIFICATION_TABLE + " ("
            + ClassificationEntry._FACTOR_FPRINT + ")");
}

From source file:uk.org.rivernile.edinburghbustracker.android.SettingsDatabase.java

/**
 * An upgrade of the database, an abstract method in the super class.
 *
 * @param db The database object to interface with.
 * @param oldVersion The version of the old database.
 * @param newVersion The version of the new database.
 *///from w  ww.j a  va 2s  .c o  m
@Override
public void onUpgrade(final SQLiteDatabase db, final int oldVersion, final int newVersion) {
    db.execSQL("CREATE TABLE IF NOT EXISTS " + ALERTS_TABLE + " (" + ALERTS_ID
            + " INTEGER PRIMARY KEY AUTOINCREMENT," + ALERTS_TYPE + " NUMERIC NOT NULL," + ALERTS_TIME_ADDED
            + " INTEGER NOT NULL," + ALERTS_STOPCODE + " TEXT NOT NULL," + ALERTS_DISTANCE_FROM + " INTEGER,"
            + ALERTS_SERVICE_NAMES + " TEXT," + ALERTS_TIME_TRIGGER + " INTEGER);");
}

From source file:com.xengar.android.englishverbs.data.VerbDBHelper.java

/**
 * This is called when the database needs to be upgraded.
 *///w ww. ja  v  a  2 s.c  om
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    String query;
    if (oldVersion > newVersion) {
        // This should not happen, version numbers should increment. Start clean.
        query = "DROP TABLE IF EXISTS " + VerbEntry.VERBS_TBL;
        db.execSQL(query);
        query = "DROP TABLE IF EXISTS " + VerbEntry.FAVORITES_TBL;
        db.execSQL(query);
    }

    // Update version by version using a method for the update. See sample below.
    switch (oldVersion) {
    /* Sample
    case 3:
        switch (oldVersion){
            case 1:
                updateSchemaToVersion2(db);
            case 2:
                updateSchemaToVersion3(db);
                break;
        }
        break*/
    default:
        break;
    }
}

From source file:yong.dealer.shopping.data.ShoppingDbHelper.java

@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion, int newVersion) {
    // This database is only a cache for online data, so its upgrade policy is
    // to simply to discard the data and start over
    // Note that this only fires if you change the version number for your database.
    // It does NOT depend on the version number for your application.
    // If you want to update the schema without wiping data, commenting out the next 2 lines
    // should be your top priority before modifying this method.
    sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + InventoryEntry.TABLE_NAME);
    sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + CategoryEntry.TABLE_NAME);
    onCreate(sqLiteDatabase);//from ww  w .  ja v a  2  s. com
}

From source file:info.staticfree.android.units.UnitUsageDBHelper.java

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL("DROP TABLE IF EXISTS " + DB_USAGE_TABLE);
    db.execSQL("DROP TABLE IF EXISTS " + DB_CLASSIFICATION_TABLE);

    db.execSQL("DROP INDEX IF EXISTS " + DB_USAGE_INDEX);
    db.execSQL("DROP INDEX IF EXISTS " + DB_CLASSIFICATION_INDEX);
    onCreate(db);/*from ww w .  ja v a 2 s  . c o  m*/

}