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:edu.cens.loci.provider.LociDbUtils.java

/**
 * //from w ww.  j  a v a  2 s. c  om
 * @param visit
 * @return
 */
public long insertWifiVisit(LociVisitWifi visit) {
    if (visit.enter == -1 || visit.exit == -1) {
        MyLog.e(LociConfig.D.ERROR, TAG, "[error] addWifiVisit: enter or exit is -1.");
        return -1;
    }

    if (visit.type != Places.TYPE_WIFI) {
        MyLog.e(LociConfig.D.ERROR, TAG, "[error] addWifiVisit: place type is not TYPE_WIFI. " + visit.type);
        return -1;
    }

    final SQLiteDatabase db = mDbHelper.getWritableDatabase();
    ContentValues args = new ContentValues();
    args.put(Visits.ENTER, visit.enter);
    args.put(Visits.EXIT, visit.exit);
    args.put(Visits.PLACE_ID, visit.placeId);
    args.put(Visits.TYPE, visit.type);
    try {
        args.put(Visits.EXTRA1, visit.wifi.toJsonObject().toString());
    } catch (JSONException e) {
        MyLog.e(LociConfig.D.JSON, TAG, "[error] addWifiVisit: json error.");
        e.printStackTrace();
        return -1;
    }
    args.put(Visits.EXTRA2, visit.getRecognitionResults());

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

From source file:net.olejon.mdapp.MedicationActivity.java

private void favorite() {
    SQLiteDatabase sqLiteDatabase = new MedicationsFavoritesSQLiteHelper(mContext).getWritableDatabase();

    String snackbarString;//from  w  w  w.ja va 2 s.com

    if (isFavorite()) {
        sqLiteDatabase.delete(MedicationsFavoritesSQLiteHelper.TABLE,
                MedicationsFavoritesSQLiteHelper.COLUMN_NAME + " = " + mTools.sqe(medicationName) + " AND "
                        + MedicationsFavoritesSQLiteHelper.COLUMN_MANUFACTURER + " = "
                        + mTools.sqe(medicationManufacturer),
                null);

        mFavoriteMenuItem.setIcon(R.drawable.ic_star_outline_white_24dp)
                .setTitle(getString(R.string.medication_menu_add_favorite));

        snackbarString = getString(R.string.medication_favorite_removed);
    } else {
        ContentValues contentValues = new ContentValues();

        contentValues.put(MedicationsFavoritesSQLiteHelper.COLUMN_PRESCRIPTION_GROUP,
                medicationPrescriptionGroup);
        contentValues.put(MedicationsFavoritesSQLiteHelper.COLUMN_NAME, medicationName);
        contentValues.put(MedicationsFavoritesSQLiteHelper.COLUMN_SUBSTANCE, medicationSubstance);
        contentValues.put(MedicationsFavoritesSQLiteHelper.COLUMN_MANUFACTURER, medicationManufacturer);

        sqLiteDatabase.insert(MedicationsFavoritesSQLiteHelper.TABLE, null, contentValues);

        Intent intent = new Intent();
        intent.setAction("update");
        mContext.sendBroadcast(intent);

        mFavoriteMenuItem.setIcon(R.drawable.ic_star_white_24dp)
                .setTitle(getString(R.string.medication_menu_remove_favorite));

        snackbarString = getString(R.string.medication_favorite_saved);
    }

    Snackbar snackbar = Snackbar.make(mRelativeLayout, snackbarString, Snackbar.LENGTH_LONG)
            .setAction(R.string.snackbar_undo, new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    favorite();
                }
            }).setActionTextColor(ContextCompat.getColor(mContext, R.color.orange));

    View snackbarView = snackbar.getView();

    TextView snackbarTextView = (TextView) snackbarView.findViewById(android.support.design.R.id.snackbar_text);

    snackbarTextView.setTextColor(ContextCompat.getColor(mContext, R.color.white));

    snackbar.show();

    mTools.updateWidget();

    sqLiteDatabase.close();
}

From source file:com.openatk.fieldnotebook.MainActivity.java

@Override
public void AddFieldDone(String name, Integer acres) {
    // Check if field name is valid and doesn't exist already
    if (name.length() == 0) {
        // Tell them to input a name
        // TODO add this message to R.strings
        Toast.makeText(this, "Field name cannot be blank.", Toast.LENGTH_LONG).show();
    } else {//from  w  ww. j  ava2s  . c om
        // Check if field name already exists in db
        if (FindFieldByName(name) != null && currentField == null) {
            Toast.makeText(this, "A field with this name already exists. Field names must be unique.",
                    Toast.LENGTH_LONG).show();
        } else {
            this.currentPolygon.complete();
            this.currentPolygon.setLabel(name, true);
            this.currentPolygon.setFillColor(Field.FILL_COLOR_NOT_PLANNED);

            List<LatLng> points = this.currentPolygon.getPoints();
            Boolean wasAnEdit = false;
            if (currentField == null) {
                currentField = new Field(points, map);
            } else {
                currentField.setBoundary(points);
                wasAnEdit = true;
            }
            currentField.setName(name);
            currentField.setAcres(acres);

            Log.d("MainActivity", "Acres:" + Integer.toString(acres));
            String strNewBoundary = "";
            if (points != null && points.isEmpty() == false) {
                // Generate boundary
                StringBuilder newBoundary = new StringBuilder(points.size() * 20);
                for (int i = 0; i < points.size(); i++) {
                    newBoundary.append(points.get(i).latitude);
                    newBoundary.append(",");
                    newBoundary.append(points.get(i).longitude);
                    newBoundary.append(",");
                }
                newBoundary.deleteCharAt(newBoundary.length() - 1);
                strNewBoundary = newBoundary.toString();
            }
            // Save this field to the db
            SQLiteDatabase database = dbHelper.getWritableDatabase();

            ContentValues values = new ContentValues();
            values.put(TableFields.COL_NAME, currentField.getName());
            values.put(TableFields.COL_ACRES, currentField.getAcres());
            values.put(TableFields.COL_BOUNDARY, strNewBoundary);

            //TODO only update if something changed
            values.put(TableFields.COL_HAS_CHANGED, 1);
            values.put(TableFields.COL_DATE_CHANGED, DatabaseHelper.dateToStringUTC(new Date()));

            if (wasAnEdit == false) {
                Integer insertId = (int) database.insert(TableFields.TABLE_NAME, null, values);
                currentField.setId(insertId);
            } else {
                database.update(TableFields.TABLE_NAME, values,
                        TableFields.COL_ID + " = " + Integer.toString(currentField.getId()), null);
            }
            dbHelper.close();

            // Add to list so we can catch click events
            currentField.setPolygon(this.currentPolygon);

            if (wasAnEdit == false) {
                FieldsOnMap.add(currentField);
            } else {
                for (int i = 0; i < FieldsOnMap.size(); i++) {
                    if (FieldsOnMap.get(i).getId() == currentField.getId()) {
                        FieldsOnMap.get(i).setName(name);
                        FieldsOnMap.get(i).setPolygon(this.currentPolygon);
                        FieldsOnMap.get(i).setAcres(acres);
                        FieldsOnMap.get(i).setBoundary(points);
                    }
                }
            }

            showSlider(true);

            // add or update in list view
            //if (this.fragmentListView != null) this.fragmentListView.getData();
            //this.trelloController.syncDelayed();
        }
    }
}

From source file:org.emergent.android.weave.syncadapter.SyncCache.java

/**
 * @param queryResult the resulte of querying the meta/global node
 * @return false if caches must be expired
 *///  w  ww.j a v  a  2  s. c  o  m
public Date validateMetaGlobal(QueryResult<JSONObject> queryResult, String engineName) {
    long retval = 0;
    SQLiteDatabase db = null;
    try {
        String uriStr = queryResult.getUri().toASCIIString();
        JSONObject jsonObj = queryResult.getValue();
        Properties flattened = convertMetaGlobalToFlatProperties(jsonObj);
        String gVer = flattened.getProperty("storageVersion");
        String gSyncId = flattened.getProperty("syncID");
        String eVer = flattened.getProperty(engineName + ".version");
        String eSyncId = flattened.getProperty(engineName + ".syncID");
        db = m_helper.getWritableDatabase();
        retval = checkCacheDb(db, uriStr, engineName, gVer, gSyncId, eVer, eSyncId);
        if (retval > 0) {
            return new Date(retval);
        } else if (retval == MGD_MISMATCH) {
            clear();
        }

        ContentValues values = new ContentValues();
        values.put(MgColumns.NODE_URI, uriStr);
        values.put(MgColumns.ENGINE_NAME, engineName);
        values.put(MgColumns.LAST_MODIFIED, 0);
        values.put(MgColumns.GLOBAL_SYNCID, gSyncId);

        Integer gVerInt = null;
        try {
            gVerInt = Integer.valueOf(gVer);
        } catch (NumberFormatException ignored) {
        }
        values.put(MgColumns.GLOBAL_VERSION, gVerInt);

        values.put(MgColumns.ENGINE_SYNCID, eSyncId);

        Integer eVerInt = null;
        try {
            eVerInt = Integer.valueOf(eVer);
        } catch (NumberFormatException ignored) {
        }
        values.put(MgColumns.ENGINE_VERSION, eVerInt);
        long uriId = db.insert(META_GLOBAL_TABLE_NAME, null, values);

        return null;
    } finally {
        if (db != null)
            try {
                db.close();
            } catch (Exception ignored) {
            }
    }
}

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

/**
 * //from  w w w  .  ja  v a  2  s.c  om
 * @param time
 * @param loc
 * @return
 */
public long insertPosition(long time, Location loc) {

    final SQLiteDatabase db = mDbHelper.getWritableDatabase();
    ContentValues args = new ContentValues();
    args.put(Tracks.TIME, time);
    args.put(Tracks.LATITUDE, loc.getLatitude());
    args.put(Tracks.LONGITUDE, loc.getLongitude());
    args.put(Tracks.ALTITUDE, loc.getAltitude());
    args.put(Tracks.SPEED, loc.getSpeed());
    args.put(Tracks.ACCURACY, loc.getAccuracy());
    args.put(Tracks.BEARING, loc.getBearing());
    args.put(Tracks.SYNC, 0);

    //MyLog.d(LociConfig.Debug.Provder.DB.LOG_EVENT, TAG, "[Db] insertPosition " + String.format("lat=%7.2f, lon=%7.2f, alt=%7.2f, speed=%7.2f, acc=%7.2f", loc.getLatitude(), loc.getLongitude(), loc.getAltitude(), loc.getSpeed(), loc.getAccuracy()));

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

From source file:android.melbournehistorymap.MapsActivity.java

private void updateMap() {

    //Now get the maps central location
    LatLng mapCenter = mMap.getCameraPosition().target;
    //clear markers
    mMap.clear();/*from w  w  w  .jav  a  2s. co  m*/

    //if user tries to zoom to far out of the world, bring them back down to earth...
    if (mMap.getCameraPosition().zoom < ZOOM_RESTRICT_LEVEL) {
        CameraPosition cameraPosition = new CameraPosition.Builder().target(mapCenter) // Sets the center of the map to location user
                .zoom(ZOOM_RESTRICT_LEVEL) // Sets the zoom
                .bearing(0) // Sets the orientation of the camera to east
                .tilt(25) // Sets the tilt of the camera to 30 degrees
                .build(); // Creates a CameraPosition from the builder

        mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
    }

    //rebuild lat/lng variable to be used for Google Places API requests
    double lat = mapCenter.latitude;
    double lng = mapCenter.longitude;
    double zoom = mMap.getCameraPosition().zoom;

    LatLng leftBorder = mMap.getProjection().getVisibleRegion().farLeft;

    //Work out distance between current location and place location
    //Source Library: https://github.com/googlemaps/android-maps-utils

    double radius = SphericalUtil.computeDistanceBetween(mapCenter, leftBorder);

    //Now that we have the new long/latitude of the camera position include zoom level
    //Lets check the database to determine if the user has been here already
    //Set DB helper
    DBHelper myDBHelper = new DBHelper(MapsActivity.this, WikiAPI.DB_NAME, null, WikiAPI.VERSION);
    //Open DB as readable only.
    SQLiteDatabase db = myDBHelper.getWritableDatabase();
    //Prepare DB Search variables
    DecimalFormat dfLat = new DecimalFormat("#.##");
    DecimalFormat dfLng = new DecimalFormat("#.##");
    DecimalFormat dfZoom = new DecimalFormat("#");
    dfLat.setRoundingMode(RoundingMode.CEILING);
    dfLng.setRoundingMode(RoundingMode.CEILING);
    dfZoom.setRoundingMode(RoundingMode.CEILING);
    double dblLat = Double.parseDouble(dfLat.format(lat));
    double dblLng = Double.parseDouble(dfLng.format(lng));
    double dblZoom = Double.parseDouble(dfZoom.format(zoom));
    //Limit by 1 rows
    Cursor cursor = db.query(DBHelper.LOC_TABLE, null,
            "LAT LIKE '" + dblLat + "%' AND LNG LIKE '" + dblLng + "%' AND ZOOM = '" + dblZoom + "'", null,
            null, null, null, "1");

    int count = cursor.getCount();

    if (count == 0) {
        //user has not been to this location/zoom level  before
        //add the new location data, then trigger the google place webservice api
        ContentValues values = new ContentValues();

        values.put("lat", String.valueOf(dblLat));
        values.put("lng", String.valueOf(dblLng));
        values.put("zoom", String.valueOf(dblZoom));
        db.insert(DBHelper.LOC_TABLE, null, values);

        String url;
        url = updateURL(lat, lng, radius);
        List<List<String>> googlePlaces = null; //null on first reference, the list is updated within the method callstack
        db.close();

        GoogleAPI.callMapMethod(mMap, url, MapsActivity.this, googlePlaces, spinner);
    }
    if (count == 1) {
        //user has been here before
        //get place data from DB and not from the API
        //if place data returned hasn't been updated in 30 days - update data using getPlaceByID method
        Cursor placeCursor = db.query(DBHelper.TABLE_NAME, null, "PLACE_TYPES LIKE '%point_of_interest%'", null,
                null, null, null, null);

        List<List<String>> googlePlaces = new ArrayList<List<String>>();

        while (placeCursor.moveToNext()) {
            String place_ID = placeCursor.getString(placeCursor.getColumnIndex("PLACE_ID"));
            String placeName = placeCursor.getString(placeCursor.getColumnIndex("PLACE_NAME"));
            String placeLoc = placeCursor.getString(placeCursor.getColumnIndex("PLACE_LOCATION"));
            String placeLat = placeCursor.getString(placeCursor.getColumnIndex("LAT"));
            String placeLng = placeCursor.getString(placeCursor.getColumnIndex("LNG"));

            //if lat and long from database is in the search bounds, add to the list of data to be shown
            LatLngBounds SEARCH_BOUNDS = mMap.getProjection().getVisibleRegion().latLngBounds;
            LatLng search_loc = new LatLng(Double.parseDouble(placeLat), Double.parseDouble(placeLng));

            if (SEARCH_BOUNDS.contains(search_loc)) {
                //now what data do we want?
                //Initiate a place data array
                List<String> placeData = new ArrayList<String>();

                //add place data to its array
                placeData.add(placeName); //0
                placeData.add(place_ID); //1
                placeData.add(placeLoc); //2
                placeData.add(String.valueOf(placeLat)); //3
                placeData.add(String.valueOf(placeLng)); //4
                placeData.add(""); //5
                placeData.add(""); //6

                //send the place specific data to the google places array list
                googlePlaces.add(placeData);
            }
        }
        db.close();

        //TODO: Get this method off the main UI thread!
        GoogleAPI.filterPlaces(googlePlaces, mMap, this, spinner);
    }
}

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

/**
 * Extract POI data from a {@link JSONArray} of points of interest and add it to the POI table.
 *
 * @param data/*w  w w . j  av a2  s .  com*/
 */
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 < DataStore.getAllCoupons().size(); i++) {
        Coupon coupon = DataStore.getAllCoupons().get(i);
        //Extract POI properties
        final String storeName = coupon.getStoreName();
        String details = coupon.getTitle();
        details = details.replace("<h1>", "").replace("</h1>", "");

        final Double lat = coupon.getLatitude();
        final Double lng = coupon.getLongitude();
        /* 
        /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, storeName);
        cv.put(TourContract.PoiEntry.COLUMN_NAME_TYPE, "LANDMARK");
        cv.put(TourContract.PoiEntry.COLUMN_NAME_DESCRIPTION, details);
        cv.put(TourContract.PoiEntry.COLUMN_NAME_LOCATION_LAT, lat);
        cv.put(TourContract.PoiEntry.COLUMN_NAME_LOCATION_LNG, lng);

        // 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();
    }

}

From source file:me.piebridge.bible.Bible.java

/**
 * save the note for book.chapter.verse/*w w w  .  j  a  v  a  2 s. c om*/
 * @param osis book.chapter
 * @param verse verse, normally number
 * @param content note content
 * @return true if saved, false if not
 */
public boolean saveNote(String osis, String verse, String verses, String content) {
    if (content == null || content.length() == 0) {
        return false;
    }
    Note note = notes.get(verse);
    if (note == null) {
        note = new Note(verse, verses, content);
    } else if (!note.update(verses, content)) {
        return false;
    }
    notes.put(verse, note);
    SQLiteDatabase db = mOpenHelper.getWritableDatabase();
    if (!isDatabaseIntegrityOk(db)) {
        File path = mContext.getDatabasePath(AnnotationsDatabaseHelper.DATABASE_NAME);
        if (path != null && path.delete()) {
            return saveNote(osis, verse, verses, content);
        }
        return false;
    }
    ContentValues values = note.getContentValues();
    values.put(AnnotationsDatabaseHelper.COLUMN_OSIS, osis);
    Long id = note.getId();
    if (id == null) {
        id = db.insert(AnnotationsDatabaseHelper.TABLE_ANNOTATIONS, null, values);
        note.setId(id);
    } else {
        db.update(AnnotationsDatabaseHelper.TABLE_ANNOTATIONS, values,
                AnnotationsDatabaseHelper.COLUMN_ID + " = ?", new String[] { String.valueOf(id) });
    }
    return true;
}

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

public void addAttributes(long categoryId, List<Attribute> attributes) {
    SQLiteDatabase db = db();
    db.delete(CATEGORY_ATTRIBUTE_TABLE, CategoryAttributeColumns.CATEGORY_ID + "=?",
            new String[] { String.valueOf(categoryId) });
    if (attributes != null && attributes.size() > 0) {
        ContentValues values = new ContentValues();
        values.put(CategoryAttributeColumns.CATEGORY_ID, categoryId);
        for (Attribute a : attributes) {
            values.put(CategoryAttributeColumns.ATTRIBUTE_ID, a.id);
            db.insert(CATEGORY_ATTRIBUTE_TABLE, null, values);
        }// w  ww .  j a v  a2 s . co  m
    }
}

From source file:com.openatk.planting.MainActivity.java

private void createOperation(final Callable<Void> myFunc) {
    // get prompts.xml view
    LayoutInflater li = LayoutInflater.from(this);
    View promptsView = li.inflate(R.layout.new_operation_dialog, null);

    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
    alertDialogBuilder.setView(promptsView);

    final EditText userInput = (EditText) promptsView.findViewById(R.id.new_operation_dialog_name);

    // set dialog message
    alertDialogBuilder.setCancelable(false).setPositiveButton("Add", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {
            // Create the operation
            String name = userInput.getText().toString();
            if (name.isEmpty() == false) {
                // Create new operation
                SQLiteDatabase database = dbHelper.getWritableDatabase();
                ContentValues values = new ContentValues();
                values.put(TableOperations.COL_HAS_CHANGED, 1);
                values.put(TableOperations.COL_NAME, name);
                currentOperationId = (int) database.insert(TableOperations.TABLE_NAME, null, values);

                Log.d("MainActivity - createOperation", Integer.toString(currentOperationId));

                dbHelper.close();//  w  w w  .  ja  v  a  2  s.  c  om
                loadOperations();
                // selectCurrentOperationInSpinner();

                // Save this choice in preferences for next
                // open
                SharedPreferences prefs = PreferenceManager
                        .getDefaultSharedPreferences(getApplicationContext());
                SharedPreferences.Editor editor = prefs.edit();
                editor.putInt("currentOperationId", currentOperationId);
                editor.commit();

                // Continue what we were doing with callback
                if (myFunc != null) {
                    try {
                        myFunc.call();
                    } catch (Exception e) {
                        Log.d("MainActivity - createOperation", "Failed to call return method");
                        e.printStackTrace();
                    }
                }
            }
        }
    }).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {
            dialog.cancel();
        }
    });

    // create alert dialog
    AlertDialog alertDialog = alertDialogBuilder.create();

    // show it
    alertDialog.show();
}