Example usage for android.database.sqlite SQLiteDatabase insert

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

Introduction

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

Prototype

public long insert(String table, String nullColumnHack, ContentValues values) 

Source Link

Document

Convenience method for inserting a row into the database.

Usage

From source file:com.spoiledmilk.ibikecph.util.DB.java

public long saveSearchHistory(HistoryData hd, HistoryData from, Context context) {
    SQLiteDatabase db = this.getWritableDatabase();
    if (db == null)
        return -1;

    String[] columns = { KEY_ID, KEY_NAME };
    long id;/*from ww w.  jav  a 2  s.c o  m*/
    Cursor cursor = db.query(TABLE_SEARCH_HISTORY, columns, KEY_NAME + " = ?", new String[] { hd.getName() },
            null, null, null, null);
    if (cursor == null || cursor.isAfterLast()) {
        ContentValues values = new ContentValues();
        values.put(KEY_NAME, hd.getName());
        values.put(KEY_ADDRESS, hd.getAdress());
        values.put(KEY_START_DATE, hd.getStartDate());
        values.put(KEY_END_DATE, hd.getEndDate());
        values.put(KEY_SOURCE, hd.getSource());
        values.put(KEY_SUBSOURCE, hd.getSubSource());
        values.put(KEY_LAT, Double.valueOf(hd.getLatitude()));
        values.put(KEY_LONG, Double.valueOf(hd.getLongitude()));
        id = db.insert(TABLE_SEARCH_HISTORY, null, values);
    } else {
        cursor.moveToFirst();
        id = cursor.getInt(cursor.getColumnIndex(KEY_ID));

    }
    if (cursor != null)
        cursor.close();

    db.close();

    if (context != null && from != null)
        postHistoryItemToServer(hd, from, context);

    return id;
}

From source file:org.kontalk.provider.UsersProvider.java

private int updateUser(ContentValues values, boolean offline, String selection, String[] selectionArgs) {
    SQLiteDatabase db = dbHelper.getWritableDatabase();

    int rc = db.update(offline ? TABLE_USERS_OFFLINE : TABLE_USERS, values, selection, selectionArgs);
    if (rc == 0) {
        ContentValues insertValues = new ContentValues(values);
        // insert new record
        insertValues.put(Users.JID, selectionArgs[0]);
        insertValues.put(Users.NUMBER, selectionArgs[0]);
        /*//www .  ja  v  a  2s.  co m
        if (!values.containsKey(Users.DISPLAY_NAME))
        insertValues.put(Users.DISPLAY_NAME, selectionArgs[0]);
         */
        insertValues.put(Users.REGISTERED, true);

        try {
            db.insert(offline ? TABLE_USERS_OFFLINE : TABLE_USERS, null, insertValues);
            return 1;
        } catch (SQLiteConstraintException e) {
            // nothing was updated but the row exists
            return 0;
        }
    }

    return rc;
}

From source file:edu.cens.loci.provider.LociDbUtils.java

public long insertPlace(String name, int state, int type, int entry, long entryTime, long registerTime) {

    final SQLiteDatabase db = mDbHelper.getWritableDatabase();

    ContentValues args = new ContentValues();
    args.put(Places.PLACE_NAME, name);/*  w ww  . j a v  a2  s. c  o  m*/
    args.put(Places.PLACE_STATE, state);
    args.put(Places.PLACE_TYPE, type);
    args.put(Places.ENTRY, entry);
    args.put(Places.ENTRY_TIME, entryTime);
    args.put(Places.REGISTER_TIME, registerTime);

    return db.insert(Tables.PLACES, null, args);
}

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

public String createFromGeoJSON(JSONObject geoJSONObject) {
    try {/*from  w ww . j a  v a2 s  .  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:Main.java

private static void insertClientToWedding(SQLiteDatabase db, String nameClient, boolean weddingType,
        long weddingDate, String weddingPlace, String groomFullName, String groomPhone, String groomSoc,
        String brideFullName, String bridePhone, String brideSoc, int weddingBegin, int weddingEnd,
        String weddingMeet, int visaj, int visArr, int barber, int barberArr, int videoOp, int vidArr,
        int groomArr, String zagsName, int zagsFillTime, String walkDesc, String walkPlace, String banketPlace,
        int banketBegin, String wit1, String wit1Soc, String wit2, String wit2Soc, int photoAuthorCount,
        String photoFormat, String photoBook, int photoBookSize, int pbookTurns, int weddingCost, int garant,
        long dateOfPact, String weddingNote) {
    ContentValues cv = new ContentValues();
    cv.put("NAME", nameClient);
    cv.put("WEDDING_TYPE", weddingType);
    cv.put("WEDDING_DATE", weddingDate);
    cv.put("WEDDING_DATE_STRING",
            new SimpleDateFormat("dd MMM yy E", Locale.getDefault()).format(new Date(weddingDate)));
    cv.put("WEDDING_PLACE", weddingPlace);
    cv.put("WEDDING_GROOM", groomFullName);
    cv.put("WEDDING_GROOM_PHONE", groomPhone);
    cv.put("WEDDING_GROOM_SOC", groomSoc);
    cv.put("WEDDING_BRIDE", brideFullName);
    cv.put("WEDDING_BRIDE_PHONE", bridePhone);
    cv.put("WEDDING_BRIDE_SOC", brideSoc);
    cv.put("WEDDING_BEGIN", weddingBegin);
    cv.put("WEDDING_END", weddingEnd);
    cv.put("WEDDING_MEET", weddingMeet);
    cv.put("WEDDING_VIS", visaj);
    cv.put("WEDDING_VIS_ARR", visArr);
    cv.put("WEDDING_BARBER", barber);
    cv.put("WEDDING_BARBER_ARR", barberArr);
    cv.put("WEDDING_CAMOP", videoOp);
    cv.put("WEDDING_CAMOP_ARR", vidArr);
    cv.put("WEDDING_GROOM_ARR", groomArr);
    cv.put("WEDDING_ZAGS", zagsName);
    cv.put("WEDDING_ZAGS_FILLTIME", zagsFillTime);
    cv.put("WEDDING_WALK", walkDesc);
    cv.put("WEDDING_WALK_PLACE", walkPlace);
    cv.put("WEDDING_BANKET_PLACE", banketPlace);
    cv.put("WEDDING_BANKET_START", banketBegin);
    cv.put("WEDDING_WIT1", wit1);
    cv.put("WEDDING_WIT1_SOC", wit1Soc);
    cv.put("WEDDING_WIT2", wit2);
    cv.put("WEDDING_WIT2_SOC", wit2Soc);
    cv.put("WEDDING_PHOT_AUT", photoAuthorCount);
    cv.put("WEDDING_PHOT_FORMAT", photoFormat);
    cv.put("WEDDING_PHOT_BOOK", photoBook);
    cv.put("WEDDING_PBOOK_SIZE", photoBookSize);
    cv.put("WEDDING_PBOOK_TURNS", pbookTurns);
    cv.put("WEDDING_COST", weddingCost);
    cv.put("WEDDING_GARANT", garant);
    cv.put("WEDDING_PACT_DATE", dateOfPact);
    cv.put("WEDDING_NOTE", weddingNote);
    db.insert("WEDDING", null, cv);

}

From source file:ru.orangesoftware.financisto2.db.DatabaseAdapter.java

private void saveRateInTransaction(SQLiteDatabase db, ExchangeRate r) {
    ContentValues values = r.toValues();
    values.remove("updated_on");
    values.put(CategoryColumns.updated_on.name(), System.currentTimeMillis());
    db.insert(EXCHANGE_RATES_TABLE, null, values);
}

From source file:com.odoo.orm.OModel.java

/**
 * Creates the./*  ww w.  j av  a 2  s.  co m*/
 * 
 * @param values
 *            the values
 * @return the int
 */
public int create(OValues values) {
    if (!values.contains("odoo_name")) {
        values.put("odoo_name", mUser.getAndroidName());
    }
    ContentValues vals = createValues(values);
    SQLiteDatabase db = getWritableDatabase();
    db.insert(getTableName(), null, vals);
    db.close();
    int newId = getCreateId();
    values.put(OColumn.ROW_ID, newId);
    updateRelationColumns(values);
    sendDatasetChangeBroadcast(newId);
    notifyDataChange(newId);
    return newId;
}

From source file:com.fan3cn.fishrecorder.ContentFragment.java

/**
 * ??/* w w w .j a v a 2s .  co m*/
 * @param view
 */
private void handleShipEvent(final View view) {
    Button addButton = (Button) view.findViewById(R.id.button_add);
    addButton.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {

            EditText nameET = (EditText) view.findViewById(R.id.editText_ship_name);
            EditText nationET = (EditText) view.findViewById(R.id.editText_ship_nation);
            EditText registerET = (EditText) view.findViewById(R.id.editText_ship_register);
            EditText emailET = (EditText) view.findViewById(R.id.editText_ship_email);
            EditText ffaET = (EditText) view.findViewById(R.id.editText_ship_ffa);
            EditText wcpfcET = (EditText) view.findViewById(R.id.editText_ship_wcpfc);
            EditText radioET = (EditText) view.findViewById(R.id.editText_ship_radio);
            EditText licenseET = (EditText) view.findViewById(R.id.editText_ship_license);

            CheckBox ckBox = (CheckBox) view.findViewById(R.id.checkBox_is_default);

            int isDefault = ckBox.isChecked() ? 1 : 0;

            String name = nameET.getText().toString();
            String nation = nationET.getText().toString();
            String register = registerET.getText().toString();
            String email = emailET.getText().toString();
            String ffa = ffaET.getText().toString();
            String wcpfc = wcpfcET.getText().toString();
            String radio = radioET.getText().toString();
            String license = licenseET.getText().toString();

            if (name.isEmpty() || nation.isEmpty() || register.isEmpty() || email.isEmpty() || ffa.isEmpty()
                    || wcpfc.isEmpty() || radio.isEmpty() || license.isEmpty()) {
                new AlertDialog.Builder(getActivity()).setTitle("??").setPositiveButton("", null)
                        .setMessage("?").show();
                return;
            }

            SQLiteDatabase db = MainActivity.getDbHelper().getWritableDatabase();

            if (isDefault == 1) {
                Cursor cursor = db.query(Constants.table.get(menuId), null, "is_default=?",
                        new String[] { 1 + "" }, null, null, null);
                if (cursor.getCount() > 0) {
                    //?
                    ContentValues cv1 = new ContentValues();
                    cv1.put("is_default", 0);
                    db.update(Constants.table.get(menuId), cv1, "is_default=?", new String[] { 1 + "" });
                }
            }
            int companyId = 0;
            //?
            Cursor cursor = db.query("company", null, "is_default=?", new String[] { 1 + "" }, null, null,
                    null);
            if (cursor.getCount() > 0) {
                while (cursor.moveToNext()) {
                    companyId = cursor.getInt(cursor.getColumnIndex("id"));
                    break;
                }
            }

            ContentValues cv = new ContentValues();
            cv.put("name", name);
            cv.put("company_id", companyId);
            cv.put("nation", nation);
            cv.put("resgiter_no", register);
            cv.put("email", email);
            cv.put("ffa_no", ffa);
            cv.put("wcpfc_no", wcpfc);
            cv.put("radio_tel", radio);
            cv.put("license", license);
            cv.put("is_default", isDefault);
            db.insert(Constants.table.get(menuId), null, cv);
            //??  
            db.close();

            Toast.makeText(getActivity(), "?!", Toast.LENGTH_SHORT).show();
        }
    });

    Button clearButton = (Button) view.findViewById(R.id.button_clear);

    clearButton.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            EditText nameET = (EditText) view.findViewById(R.id.editText_ship_name);
            EditText nationET = (EditText) view.findViewById(R.id.editText_ship_nation);
            EditText registerET = (EditText) view.findViewById(R.id.editText_ship_register);
            EditText emailET = (EditText) view.findViewById(R.id.editText_ship_email);
            EditText ffaET = (EditText) view.findViewById(R.id.editText_ship_ffa);
            EditText wcpfcET = (EditText) view.findViewById(R.id.editText_ship_wcpfc);
            EditText radioET = (EditText) view.findViewById(R.id.editText_ship_radio);
            EditText licenseET = (EditText) view.findViewById(R.id.editText_ship_license);

            CheckBox ckBox = (CheckBox) view.findViewById(R.id.checkBox_is_default);

            nameET.setText("");
            nationET.setText("");
            registerET.setText("");
            emailET.setText("");
            ffaET.setText("");
            emailET.setText("");
            radioET.setText("");
            wcpfcET.setText("");
            licenseET.setText("");
            ckBox.setChecked(false);
        }
    });

}

From source file:net.gaast.giggity.Db.java

private void updateSchedule(SQLiteDatabase db, Seed.Schedule sched, int last_version) {
    if (sched.start.equals(sched.end)) {
        /* If it's one day only, avoid having start == end. Pretend it's from 6:00 'til 18:00 or something. */
        sched.start.setHours(6);/*from  ww w . ja v a2s .  c  om*/
        sched.end.setHours(18);
    } else {
        /* For different days, pretend the even't from noon to noon. In both cases, we'll have exact times
         * once we load the schedule for the first time. */
        sched.start.setHours(12);
        sched.end.setHours(12);
    }
    Cursor q = db.rawQuery("Select sch_id From schedule Where sch_url = ?", new String[] { sched.url });
    Log.d("cursor", "" + q.getCount());
    if (sched.version > last_version && q.getCount() == 0) {
        ContentValues row = new ContentValues();
        if (sched.id != null)
            row.put("sch_id_s", sched.id);
        else
            row.put("sch_id_s", Schedule.hashify(sched.url));
        row.put("sch_url", sched.url);
        row.put("sch_title", sched.title);
        row.put("sch_atime", sched.start.getTime() / 1000);
        row.put("sch_start", sched.start.getTime() / 1000);
        row.put("sch_end", sched.end.getTime() / 1000);
        row.put("sch_metadata", sched.metadata);
        db.insert("schedule", null, row);
    } else if (q.getCount() == 1) {
        q.moveToNext();
        if (oldDbVer < 8) {
            /* We're upgrading from < 8 so we have to backfill the start/end columns. */
            ContentValues row = new ContentValues();
            row.put("sch_start", sched.start.getTime() / 1000);
            row.put("sch_end", sched.end.getTime() / 1000);
            db.update("schedule", row, "sch_id = ?", new String[] { q.getString(0) });
        }

        /* Always refresh the metadata, seedfile is authoritative. */
        if (sched.metadata != "") {
            ContentValues row = new ContentValues();
            row.put("sch_metadata", sched.metadata);
            db.update("schedule", row, "sch_id = ?", new String[] { q.getString(0) });
        }
    }
    q.close();
}

From source file:com.example.google.touroflondon.data.TourDbHelper.java

/**
 * Extract POI data from a {@link JSONArray} of points of interest and add
 * it to the POI table./* w  w  w  .j  a v a2 s. co  m*/
 * 
 * @param data
 */
public void loadPois(JSONArray data) throws JSONException {

    SQLiteDatabase db = this.getWritableDatabase();

    // empty the POI table to remove all existing data
    db.delete(TourContract.PoiEntry.TABLE_NAME, null, null);

    // need to complete transaction first to clear data
    db.close();

    // begin the insert transaction
    db = this.getWritableDatabase();
    db.beginTransaction();

    // Loop over each point of interest in array
    for (int i = 0; i < data.length(); i++) {
        JSONObject poi = data.getJSONObject(i);

        // Extract POI properties
        final String title = poi.getString("title");
        final String type = poi.getString("type");
        final String description = poi.getString("description");
        final String pictureUrl = poi.getString("pictureUrl");
        final String pictureAttr = poi.getString("pictureAttr");

        // Location
        JSONObject location = poi.getJSONObject("location");
        final double lat = location.getDouble("lat");
        final double lng = location.getDouble("lng");

        // Create content values object for insert
        ContentValues cv = new ContentValues();
        cv.put(TourContract.PoiEntry.COLUMN_NAME_TITLE, title);
        cv.put(TourContract.PoiEntry.COLUMN_NAME_TYPE, type);
        cv.put(TourContract.PoiEntry.COLUMN_NAME_DESCRIPTION, description);
        cv.put(TourContract.PoiEntry.COLUMN_NAME_PICTURE_URL, pictureUrl);
        cv.put(TourContract.PoiEntry.COLUMN_NAME_LOCATION_LAT, lat);
        cv.put(TourContract.PoiEntry.COLUMN_NAME_LOCATION_LNG, lng);
        cv.put(TourContract.PoiEntry.COLUMN_NAME_PICTURE_ATTR, pictureAttr);

        // Insert data
        db.insert(TourContract.PoiEntry.TABLE_NAME, null, cv);
    }

    // All insert statement have been submitted, mark transaction as
    // successful
    db.setTransactionSuccessful();

    if (db != null) {
        db.endTransaction();
    }

}