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:io.vit.vitio.Managers.ConnectDatabase.java

public void saveCourses(List<Course> courses) {
    try {/*from  w  ww . ja v  a 2 s . co m*/
        SQLiteDatabase db = this.getWritableDatabase();

        for (int i = 0; i < courses.size(); i++) {
            Course course = courses.get(i);

            ContentValues values = new ContentValues();

            values.put(COLUMNS[0], course.getCLASS_NUMBER());
            values.put(COLUMNS[1], course.getCOURSE_TITLE());
            values.put(COLUMNS[2], course.getCOURSE_SLOT());
            values.put(COLUMNS[3], course.getCOURSE_TYPE());
            values.put(COLUMNS[4], course.getCOURSE_TYPE_SHORT());
            Log.d("type", course.getCOURSE_TYPE_SHORT());
            values.put(COLUMNS[5], course.getCOURSE_LTPC().toString());
            values.put(COLUMNS[6], course.getCOURSE_CODE());
            values.put(COLUMNS[7], course.getCOURSE_MODE());
            values.put(COLUMNS[8], course.getCOURSE_OPTION());
            values.put(COLUMNS[9], course.getCOURSE_VENUE());
            values.put(COLUMNS[10], course.getCOURSE_FACULTY().toString());
            values.put(COLUMNS[11], course.getCOURSE_REGISTRATIONSTATUS());
            values.put(COLUMNS[12], course.getCOURSE_BILL_DATE());
            values.put(COLUMNS[13], course.getCOURSE_BILL_NUMBER());
            values.put(COLUMNS[14], course.getCOURSE_PROJECT_TITLE());
            values.put(COLUMNS[15], course.getCOURSE_JSON().toString());
            values.put(COLUMNS[16], course.getCOURSE_ATTENDANCE().getJson().toString());
            values.put(COLUMNS[17], course.getCOURSE_JSON().getJSONArray("timings").toString());
            values.put(COLUMNS[18], course.getCOURSE_JSON().getJSONObject("marks").toString());
            //db.insertWithOnConflict(TABLE_COURSES, null, values, SQLiteDatabase.CONFLICT_REPLACE);
            if (check()) {
                Log.d("update", "check()");
                //onUpgrade(db,db.getVersion(),192564);
                db.replace(TABLE_COURSES, null, values);
                //db.update(TABLE_COURSES, values, null, null);
            } else {
                Log.d("insert", "check()");
                db.insert(TABLE_COURSES, null, values);
            }
        }
        db.close();
    } catch (Exception e) {
        e.printStackTrace();
        SQLiteDatabase _db = this.getWritableDatabase();
        if (_db != null && _db.isOpen()) {
            _db.close();
        }
    }

}

From source file:com.wheelermarine.publicAccessSites.Updater.java

private void readDBaseFile(ZipInputStream zin, SQLiteDatabase database) throws IOException {

    // Begin parsing the DBase data.
    DBaseReader reader = new DBaseReader(zin);
    final int recordCount = reader.size();
    activity.runOnUiThread(new Runnable() {
        @Override/*from w  w w . ja v a 2  s. c  o m*/
        public void run() {
            progress.setIndeterminate(false);
            progress.setMax(recordCount);
        }
    });
    Log.v(TAG, "DBase version: " + reader.getHeader().getSignature());
    Log.v(TAG, "Last Update: " + reader.getHeader().getLastUpdate());
    Log.v(TAG, "Record Count: " + reader.size());

    // Insert the records into the local database.
    int progress = 0;
    for (Record access : reader) {
        String lake = (String) access.getValue("LAKENAME");
        if (lake == null || lake.isEmpty())
            lake = (String) access.getValue("LAKE_NAME");
        if (lake == null || lake.isEmpty())
            lake = (String) access.getValue("ALT_NAME");
        if (lake == null || lake.isEmpty())
            lake = String.valueOf(progress);

        ContentValues values = new ContentValues();
        values.put(DatabaseHelper.PublicAccessEntry.COLUMN_NAME_NAME, (String) access.getValue("FAC_NAME"));
        values.put(DatabaseHelper.PublicAccessEntry.COLUMN_NAME_LAUNCH, (String) access.getValue("LAUNCHTYPE"));
        values.put(DatabaseHelper.PublicAccessEntry.COLUMN_NAME_RAMP, (String) access.getValue("RAMPTYPE"));
        values.put(DatabaseHelper.PublicAccessEntry.COLUMN_NAME_RAMPS, (Double) access.getValue("NUMRAMPS"));
        values.put(DatabaseHelper.PublicAccessEntry.COLUMN_NAME_DOCKS, (Double) access.getValue("NUMDOCKS"));
        values.put(DatabaseHelper.PublicAccessEntry.COLUMN_NAME_DIRECTIONS,
                (String) access.getValue("DIRECTIONS"));
        values.put(DatabaseHelper.PublicAccessEntry.COLUMN_NAME_LAKE, lake);
        values.put(DatabaseHelper.PublicAccessEntry.COLUMN_NAME_COUNTY, (String) access.getValue("COUNTYNAME"));
        values.put(DatabaseHelper.PublicAccessEntry.COLUMN_NAME_RECORD_NUMBER, progress + 1);
        database.insert(DatabaseHelper.PublicAccessEntry.TABLE_NAME, null, values);
        publishProgress(++progress);
    }
}

From source file:org.frc836.database.DBSyncService.java

private void processPits(JSONArray pits) {
    // TODO could be abstracted further
    try {/*  ww  w .j  av a2s.c  o  m*/
        for (int i = 0; i < pits.length(); i++) {
            JSONObject row = pits.getJSONObject(i);
            Action action = Action.UPDATE;
            if (row.getInt(PitStats.COLUMN_NAME_INVALID) != 0) {
                action = Action.DELETE;
            }
            ContentValues vals = PitStats.getNewPitStats().jsonToCV(row);

            // check if this entry exists already
            String[] projection = { PitStats.COLUMN_NAME_ID, PitStats.COLUMN_NAME_INVALID };
            String[] where = { vals.getAsString(PitStats.COLUMN_NAME_TEAM_ID) };

            synchronized (ScoutingDBHelper.lock) {

                SQLiteDatabase db = ScoutingDBHelper.getInstance().getWritableDatabase();

                Cursor c = db.query(PitStats.TABLE_NAME, projection, // select
                        PitStats.COLUMN_NAME_TEAM_ID + "=?", where, null, // don't
                        // group
                        null, // don't filter
                        null, // don't order
                        "0,1"); // limit to 1
                try {
                    if (!c.moveToFirst()) {
                        if (action == Action.UPDATE)
                            action = Action.INSERT;
                        else if (action == Action.DELETE)
                            action = Action.NOTHING;
                    } else {
                        int invalid = c.getInt(c.getColumnIndexOrThrow(PitStats.COLUMN_NAME_INVALID));
                        if (invalid > 0) // Current entry has not been sent
                                         // to server, don't overwrite
                            action = Action.NOTHING;
                    }

                    switch (action) {
                    case UPDATE:
                        db.update(PitStats.TABLE_NAME, vals, PitStats.COLUMN_NAME_TEAM_ID + " = ?", where);
                        break;
                    case INSERT:
                        db.insert(PitStats.TABLE_NAME, null, vals);
                        break;
                    case DELETE:
                        db.delete(PitStats.TABLE_NAME, PitStats.COLUMN_NAME_TEAM_ID + " = ?", where);
                        break;
                    default:
                    }
                } finally {
                    if (c != null)
                        c.close();
                    ScoutingDBHelper.getInstance().close();
                }
            }
        }
    } catch (JSONException e) {
        // TODO handle error
    }
}

From source file:com.openatk.planting.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 {// ww  w  . j  a  v  a 2  s.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);
            if (currentJob == null) {
                this.currentPolygon.setFillColor(Field.FILL_COLOR_NOT_PLANNED);
            } else {
                if (currentJob.getStatus() == Job.STATUS_NOT_PLANNED) {
                    this.currentPolygon.setFillColor(Field.FILL_COLOR_NOT_PLANNED);
                } else if (currentJob.getStatus() == Job.STATUS_PLANNED) {
                    this.currentPolygon.setFillColor(Field.FILL_COLOR_PLANNED);
                } else if (currentJob.getStatus() == Job.STATUS_STARTED) {
                    this.currentPolygon.setFillColor(Field.FILL_COLOR_STARTED);
                } else if (currentJob.getStatus() == Job.STATUS_DONE) {
                    this.currentPolygon.setFillColor(Field.FILL_COLOR_DONE);
                }
            }

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

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

            // Check to see if we have any operations
            if (operationsList.isEmpty() == false) {
                // Check if any operation selected
                if (currentOperationId != 0) {
                    showEdit(true);
                } else {
                    // Make them select an operation
                    // TODO popup list??
                }
            } else {
                // Add an operation
                createOperation(new Callable<Void>() {
                    public Void call() {
                        return showEdit(true);
                    }
                });
            }
            this.trelloController.syncDelayed();
        }
    }
}

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

/**
 * Manage many to many records.//from   w  w  w .  j  a v a2  s.c o m
 * 
 * @param db
 *            the db
 * @param rel_model
 *            the rel_model
 * @param ids
 *            the ids
 * @param base_id
 *            the base_id
 * @param command
 *            the command
 */
public void manageManyToManyRecords(SQLiteDatabase db, OModel rel_model, List<Integer> ids, Integer base_id,
        Command command) {
    String table = getTableName() + "_" + rel_model.getTableName() + "_rel";
    String base_column = getTableName() + "_id";
    String rel_column = rel_model.getTableName() + "_id";

    switch (command) {
    case Add:
        // Adding records to relation model
        if (ids.size() > 0) {
            for (int id : ids) {
                ContentValues values = new ContentValues();
                values.put(base_column, base_id);
                values.put(rel_column, id);
                values.put("odoo_name", mUser.getAndroidName());
                values.put("local_write_date", ODate.getDate());
                db.insert(table, null, values);
            }
        }
        break;
    case Update:
        break;
    case Delete:
        // Deleting records to relation model
        if (ids.size() > 0) {
            for (int id : ids) {
                db.delete(table, base_column + " = ? AND  " + rel_column + " = ?",
                        new String[] { base_id + "", id + "" });
            }
        }
        break;
    case Replace:
        // Removing old entries
        String where = base_column + " = ? ";
        String[] args = new String[] { base_id + "" };
        db.delete(table, getWhereClause(where), getWhereArgs(where, args));
        // Creating new entries
        manageManyToManyRecords(db, rel_model, ids, base_id, Command.Add);
        break;
    }
}

From source file:com.geecko.QuickLyric.tasks.WriteToDatabaseTask.java

@Override
public Boolean doInBackground(Object... params) {
    lyricsArray = new Lyrics[params.length - 2];
    SQLiteDatabase database;
    if (params[0] instanceof Fragment) {
        fragment = (Fragment) params[0];
        mContext = fragment.getActivity();
        if (mContext == null || !(mContext instanceof MainActivity))
            cancel(true);/*  w  w  w .  j a v  a  2s  .c om*/
        database = DatabaseHelper.getInstance(mContext).getWritableDatabase();
    } else
        database = (SQLiteDatabase) params[0];
    item = (MenuItem) params[1];
    if (params[2] instanceof Lyrics[])
        lyricsArray = (Lyrics[]) params[2];
    else
        for (int i = 0; i < lyricsArray.length; i++) {
            lyricsArray[i] = (Lyrics) params[i + 2];
        }
    boolean result = true;
    String[] columns = DatabaseHelper.columns;
    if (database != null && database.isOpen()) {
        database.beginTransaction();
        try {
            for (Lyrics lyrics : lyricsArray) {
                Lyrics storedLyrics = DatabaseHelper.getInstance(mContext)
                        .get(new String[] { lyrics.getArtist(), lyrics.getTitle(), lyrics.getOriginalArtist(),
                                lyrics.getOriginalTrack() });
                if ((storedLyrics == null || (!storedLyrics.isLRC() && lyrics.isLRC()))
                        && !"Storage".equals(lyrics.getSource())) {
                    ContentValues values = new ContentValues(2);
                    values.put(columns[0], lyrics.getArtist());
                    values.put(columns[1], lyrics.getTitle());
                    values.put(columns[2], lyrics.getText());
                    values.put(columns[3], lyrics.getURL());
                    values.put(columns[4], lyrics.getSource());
                    if (lyrics.getCoverURL() != null && lyrics.getCoverURL().startsWith("http://"))
                        values.put(columns[5], lyrics.getCoverURL());
                    values.put(columns[6], lyrics.getOriginalArtist());
                    values.put(columns[7], lyrics.getOriginalTrack());
                    values.put(columns[8], lyrics.isLRC() ? 1 : 0);
                    values.put(columns[9], lyrics.getWriter());
                    values.put(columns[10], lyrics.getCopyright());
                    database.delete(DatabaseHelper.TABLE_NAME,
                            String.format("%s=? AND %s=?", columns[0], columns[1]),
                            new String[] { lyrics.getArtist(), lyrics.getTitle() });
                    database.insert(DatabaseHelper.TABLE_NAME, null, values);
                    if (fragment instanceof LyricsViewFragment)
                        ((LyricsViewFragment) fragment).lyricsPresentInDB = true;
                    result = true;
                } else if (mContext != null) { // if called from activity, not service
                    database.delete(DatabaseHelper.TABLE_NAME,
                            String.format("%s=? AND %s=?", columns[0], columns[1]),
                            new String[] { lyrics.getArtist(), lyrics.getTitle() });
                    if (fragment instanceof LyricsViewFragment)
                        ((LyricsViewFragment) fragment).lyricsPresentInDB = false;
                    result = false;
                }
                database.yieldIfContendedSafely();
            }
            database.setTransactionSuccessful();
        } finally {
            database.endTransaction();
        }
    }
    return result;
}

From source file:com.cryart.sabbathschool.util.SSCore.java

public boolean downloadIfNeeded() {
    if (quarterlyForLanguageExists()) {
        return true;
    }/*from  w ww.  j a v  a  2  s. c o m*/

    InputStream is;
    String json;
    Cursor c;

    SQLiteDatabase db = this.getReadableDatabase();

    try {
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet("https://s3-us-west-2.amazonaws.com/com.cryart.sabbathschool/latest_"
                + LANGUAGE + ".json?" + String.valueOf(System.currentTimeMillis()));
        HttpResponse httpResponse = httpClient.execute(httpGet);
        HttpEntity httpEntity = httpResponse.getEntity();
        is = httpEntity.getContent();
    } catch (UnsupportedEncodingException e) {
        return false;
    } catch (ClientProtocolException e) {
        return false;
    } catch (IOException e) {
        return false;
    }

    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "n");
        }
        is.close();
        json = sb.toString();
    } catch (Exception e) {
        return false;
    }

    try {
        JSONObject ss_quarterly = new JSONObject(json);
        String ss_quarter_id = ss_quarterly.getString("quarter_id");
        String ss_quarter_name = ss_quarterly.getString("quarter_name");
        String ss_quarter_image = "";
        String ss_quarter_lang = ss_quarterly.getString("quarter_lang");
        JSONArray ss_lessons = ss_quarterly.getJSONArray("quarter_lessons");

        if (ss_quarterly.has("quarter_image")) {
            ss_quarter_image = ss_quarterly.getString("quarter_image");
        }

        c = db.rawQuery("SELECT COUNT(1) FROM ss_quarters " + "WHERE quarter_id = ? AND quarter_lang = ?",
                new String[] { ss_quarter_id, LANGUAGE });
        c.moveToFirst();
        int quarter_count = c.getInt(0);
        c.close();
        if (quarter_count > 0) {
            return true;
        }

        db = this.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put("quarter_id", ss_quarter_id);
        values.put("quarter_name", ss_quarter_name);
        values.put("quarter_image", ss_quarter_image);
        values.put("quarter_lang", ss_quarter_lang);

        long ss_quarter_serial = db.insert("ss_quarters", null, values);

        for (int i = 0; i < ss_lessons.length(); i++) {
            JSONObject ss_lesson = ss_lessons.getJSONObject(i);
            String ss_lesson_name = ss_lesson.getString("lesson_name");
            String ss_lesson_image = ss_lesson.getString("lesson_image");
            String ss_lesson_date_text = ss_lesson.getString("lesson_date_text");
            JSONArray ss_days = ss_lesson.getJSONArray("lesson_days");

            values = new ContentValues();
            values.put("lesson_name", ss_lesson_name);
            values.put("lesson_image", ss_lesson_image);
            values.put("lesson_date_text", ss_lesson_date_text);
            values.put("lesson_quarter_serial", ss_quarter_serial);

            long ss_lesson_serial = db.insert("ss_lessons", null, values);

            for (int j = 0; j < ss_days.length(); j++) {
                JSONObject ss_day = ss_days.getJSONObject(j);
                String ss_day_date = ss_day.getString("day_date");
                String ss_day_name = ss_day.getString("day_name");
                String ss_day_text = ss_day.getString("day_text");
                String ss_day_comments = "";
                String ss_day_highlights = "";
                String ss_day_date_text = ss_day.getString("day_date_text");
                String ss_day_verses = ss_day.getString("day_verses");

                values = new ContentValues();
                values.put("day_date", ss_day_date);
                values.put("day_name", ss_day_name);
                values.put("day_text", ss_day_text);
                values.put("day_comments", ss_day_comments);
                values.put("day_highlights", ss_day_highlights);
                values.put("day_date_text", ss_day_date_text);
                values.put("day_verses", ss_day_verses);
                values.put("day_lesson_serial", ss_lesson_serial);

                db.insert("ss_days", null, values);
            }
        }

        return true;
    } catch (JSONException e) {
        return false;
    }
}

From source file:org.y20k.transistor.core.Station.java

public static void AddStationItemToDb(Station stationItem, Activity mActivity) {
    //db test//from w ww. j a  v  a  2 s .  com
    StationsDbHelper mDbHelper = new StationsDbHelper(mActivity);
    // Gets the data repository in write mode
    SQLiteDatabase db = mDbHelper.getWritableDatabase();

    // Filter results WHERE "title" = 'My Title'
    String selection = StationsDbContract.StationEntry.COLUMN_UNIQUE_ID + " = ?";
    String[] selectionArgs = { stationItem.UNIQUE_ID };

    String[] projection = { StationsDbContract.StationEntry._ID,
            StationsDbContract.StationEntry.COLUMN_UNIQUE_ID };
    String sortOrder = StationsDbContract.StationEntry.COLUMN_UNIQUE_ID + " DESC";
    Cursor cursor = db.query(StationsDbContract.StationEntry.TABLE_NAME, // The table to query
            projection, // The columns to return
            selection, // The columns for the WHERE clause
            selectionArgs, // The values for the WHERE clause
            null, // don't group the rows
            null, // don't filter by row groups
            sortOrder);
    if (cursor.getCount() == 0) {
        //record not found
        // Create a new map of values, where column names are the keys
        ContentValues values = new ContentValues();
        values.put(StationsDbContract.StationEntry.COLUMN_NAME_TITLE, stationItem.TITLE);
        values.put(StationsDbContract.StationEntry.COLUMN_UNIQUE_ID, stationItem.UNIQUE_ID);
        values.put(StationsDbContract.StationEntry.COLUMN_NAME_SUBTITLE, stationItem.SUBTITLE);
        values.put(StationsDbContract.StationEntry.COLUMN_DESCRIPTION, stationItem.DESCRIPTION);
        values.put(StationsDbContract.StationEntry.COLUMN_IMAGE_PATH, stationItem.IMAGE_PATH);
        values.put(StationsDbContract.StationEntry.COLUMN_IMAGE_FILE_NAME, stationItem.IMAGE_FILE_NAME);
        values.put(StationsDbContract.StationEntry.COLUMN_SMALL_IMAGE_FILE_NAME,
                stationItem.SMALL_IMAGE_FILE_NAME);
        values.put(StationsDbContract.StationEntry.COLUMN_URI, stationItem.StreamURI);
        values.put(StationsDbContract.StationEntry.COLUMN_CONTENT_TYPE, stationItem.CONTENT_TYPE);
        values.put(StationsDbContract.StationEntry.COLUMN_RATING, stationItem.RATING);
        values.put(StationsDbContract.StationEntry.COLUMN_IS_FAVOURITE, 0); //default
        values.put(StationsDbContract.StationEntry.COLUMN_COMMA_SEPARATED_TAGS,
                stationItem.COMMA_SEPARATED_TAGS);
        values.put(StationsDbContract.StationEntry.COLUMN_CATEGORY, stationItem.CATEGORY);
        values.put(StationsDbContract.StationEntry.COLUMN_MARKDOWN_DESCRIPTION,
                stationItem.MarkdownDescription);
        values.put(StationsDbContract.StationEntry.COLUMN_SMALL_IMAGE_URL, stationItem.SMALL_IMAGE_PATH);

        // Insert the new row, returning the primary key value of the new row
        long newRowId = db.insert(StationsDbContract.StationEntry.TABLE_NAME, null, values);
        stationItem._ID = newRowId;
    } //todo: , else then update the existing with new data

    db.close();

}

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

public void loadInitialUnitUsage() {
    final SQLiteDatabase db = getWritableDatabase();
    // load the initial table in
    final ContentValues cv = new ContentValues();

    Log.d(TAG, "init all weights hash");
    final HashMap<String, Integer> allUnitWeights = new HashMap<String, Integer>(Unit.table.keySet().size());
    Log.d(TAG, "adding all known weights...");
    for (final String unitName : Unit.table.keySet()) {
        // don't add all uppercase names
        if (!unitName.toUpperCase().equals(unitName)) {
            allUnitWeights.put(unitName, 0);
        }/*  www.j a va 2s.  c  o  m*/
    }
    Log.d(TAG, "adding all known functions...");
    for (final String functionName : BuiltInFunction.table.keySet()) {
        allUnitWeights.put(functionName + "(", 0);
    }
    //      for (final String functionName: TabularFunction.table.keySet()){
    //         allUnitWeights.put(functionName + "(", 0);
    //      }
    //      for (final String functionName: ComputedFunction.table.keySet()){
    //         allUnitWeights.put(functionName + "(", 0);
    //      }
    for (final String functionName : DefinedFunction.table.keySet()) {
        allUnitWeights.put(functionName + "(", 0);
    }
    Log.d(TAG, "adding common weights");
    addAll(loadInitialWeights(R.raw.common_weights), allUnitWeights);
    Log.d(TAG, "adding regional weights");
    addAll(loadInitialWeights(R.raw.regional_weights), allUnitWeights);

    // This is so that things of common weight end up in non-random order
    // without having to do an SQL order-by.
    final ArrayList<String> sortedUnits = new ArrayList<String>(allUnitWeights.keySet());
    Log.d(TAG, "Sorting units...");
    Collections.sort(sortedUnits);
    Log.d(TAG, "Adding all sorted units...");

    final HashMap<String, String> fingerprints = loadFingerprints();

    db.beginTransaction();
    for (final String unitName : sortedUnits) {
        cv.put(UsageEntry._UNIT, unitName);
        cv.put(UsageEntry._USE_COUNT, allUnitWeights.get(unitName));

        final String fpr = fingerprints.containsKey(unitName) ? fingerprints.get(unitName)
                : getFingerprint(unitName);

        fingerprints.put(unitName, fpr);
        cv.put(UsageEntry._FACTOR_FPRINT, fpr);
        db.insert(DB_USAGE_TABLE, null, cv);
    }
    db.setTransactionSuccessful();
    db.endTransaction();
    db.close();

    context.getContentResolver().notifyChange(UsageEntry.CONTENT_URI, null);

    // If we have the right permissons, save the fingerprints file to a JSON file
    // which can then be imported into the app to speed up initial fingerpint loading.
    if (context.checkCallingOrSelfPermission(
            Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
        final File externalStorage = Environment.getExternalStorageDirectory();
        final File fprintsOutput = new File(externalStorage, "units_fingerprints.json");
        final JSONObject jo = new JSONObject(fingerprints);
        try {
            final FileWriter fw = new FileWriter(fprintsOutput);
            fw.write(jo.toString(1));
            fw.close();
            Log.i(TAG, "fingerprints written to: " + fprintsOutput.getCanonicalPath());

        } catch (final Exception e) {
            e.printStackTrace();
        }
    }
    Log.d(TAG, "done!");
}

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

@Override
public void EditJobSave(Job job, Boolean changeState, Boolean unselect) {
    currentJob = job;//from   w w  w .ja  va  2  s . c om

    if (unselect && this.currentPolygon != null) {
        this.currentPolygon.unselect();
    }
    if (job != null && job.getStatus() != Job.STATUS_NOT_PLANNED) {
        // Save new job in db
        SQLiteDatabase database = dbHelper.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(TableJobs.COL_WORKER_NAME, job.getWorkerName());
        values.put(TableJobs.COL_SEED_NAME, job.getSeedName());
        if (currentField == null) {
            values.put(TableJobs.COL_FIELD_NAME, currentJob.getFieldName());
        } else {
            values.put(TableJobs.COL_FIELD_NAME, currentField.getName());
        }
        values.put(TableJobs.COL_STATUS, job.getStatus());
        values.put(TableJobs.COL_COMMENTS, job.getComments());
        values.put(TableJobs.COL_SEEDNOTES, job.getSeednotes());
        values.put(TableJobs.COL_DATE_OF_OPERATION, job.getDateOfOperation());
        values.put(TableJobs.COL_HAS_CHANGED, job.getHasChanged());
        values.put(TableJobs.COL_DATE_CHANGED, job.getDateChanged());
        values.put(TableJobs.COL_OPERATION_ID, currentOperationId);

        if (job.getId() == null) {
            Integer insertId = (int) database.insert(TableJobs.TABLE_NAME, null, values);
            currentJob.setId(insertId);
            if (job.getWorkerName().isEmpty() == false) {
                // Save this choice in preferences for next open
                SharedPreferences prefs = PreferenceManager
                        .getDefaultSharedPreferences(getApplicationContext());
                SharedPreferences.Editor editor = prefs.edit();
                editor.putString("WorkerName", job.getWorkerName());
                editor.commit();
            }
            if (job.getSeedName().isEmpty() == false) {
                // Save this choice in preferences for next open
                SharedPreferences prefs = PreferenceManager
                        .getDefaultSharedPreferences(getApplicationContext());
                SharedPreferences.Editor editor = prefs.edit();
                editor.putString("SeedName", job.getSeedName());
                editor.commit();
            }
            Log.d("MainActivity - EditJobSave", "Adding new job to db:" + job.getFieldName() + " - Field Id:"
                    + Integer.toString(insertId) + ", Op Id:" + currentOperationId);
        } else {
            // Update job
            String where = TableJobs.COL_ID + " = " + job.getId() + " AND " + TableJobs.COL_DELETED + " = 0";
            ;
            database.update(TableJobs.TABLE_NAME, values, where, null);
            Log.d("MainActivity - EditJobSave", "Updating job in db:" + job.getFieldName() + " - Field Id:"
                    + Integer.toString(job.getId()) + ", Op Id:" + currentOperationId);
        }

        //Add notes to notes table
        List<Note> notes = currentJob.getNotes();
        Log.d("MainActivity - EditJobSave", "Number of notes: " + Integer.toString(notes.size()));
        for (int i = 0; i < notes.size(); i++) {
            Note toadd = notes.get(i);
            ContentValues values2 = new ContentValues();
            values2.put(TableNotes.COL_TOPIC, toadd.getTopic());
            values2.put(TableNotes.COL_COMMENT, toadd.getComment());
            values2.put(TableNotes.COL_FIELD_NAME, currentJob.getFieldName());
            if (toadd.getId() == null) {
                //New note, no id
                Integer newNoteId = (int) database.insert(TableNotes.TABLE_NAME, null, values2);
                toadd.setId(newNoteId);
                Log.d("MainActivity - EditJobSave", "Inserted new note in db");
            } else {
                //Update this note in the db
                String where2 = TableNotes.COL_ID + " = " + toadd.getId() + " AND " + TableNotes.COL_DELETED
                        + " = 0";
                database.update(TableNotes.TABLE_NAME, values2, where2, null);
                Log.d("MainActivity - EditJobSave", "Updated note comments");
            }
        }
        dbHelper.close();
        // Set fill according to status
        if (this.currentPolygon != null) {
            if (currentJob.getStatus() == Job.STATUS_NOT_PLANNED) {
                this.currentPolygon.setFillColor(Field.FILL_COLOR_NOT_PLANNED);
            } else if (currentJob.getStatus() == Job.STATUS_PLANNED) {
                this.currentPolygon.setFillColor(Field.FILL_COLOR_PLANNED);
            } else if (currentJob.getStatus() == Job.STATUS_STARTED) {
                this.currentPolygon.setFillColor(Field.FILL_COLOR_STARTED);
            } else if (currentJob.getStatus() == Job.STATUS_DONE) {
                this.currentPolygon.setFillColor(Field.FILL_COLOR_DONE);
            }
        }
    } else {
        currentJob = null;
    }
    if (changeState)
        hideEdit(true);

    if (unselect) {
        this.currentField = null;
        this.currentJob = null;
    }
    if (this.fragmentListView != null)
        this.fragmentListView.getData();

    this.trelloController.syncDelayed();
}