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.github.gw2app.events.Gw2StaticData.java

private void _update_map_names() {
    if (Gw2JSONDownloader.internetAvailable(mContext)) {
        String result = Gw2JSONDownloader.downloadJSON(Gw2JSONDownloader.event_map_names_url);
        SQLiteDatabase db = mDBHelper.getWritableDatabase();

        try {//from w ww .  j a v a 2s. co  m
            JSONArray jsData;
            jsData = new JSONArray(result);

            for (int i = 0; i < jsData.length(); i++) {
                JSONObject obj = jsData.getJSONObject(i);
                Integer id = obj.getInt("id");
                String name = obj.getString("name");

                ContentValues row = new ContentValues(2);
                row.put("_id", id);
                row.put("name", name);

                if (db != null) {
                    db.insert(Gw2DB.MAP_NAMES_TABLE, null, row);
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    } else {
        //TODO: Throw exception.
    }
}

From source file:com.github.gw2app.events.Gw2StaticData.java

private void _update_world_names() {
    if (Gw2JSONDownloader.internetAvailable(mContext)) {
        String result = Gw2JSONDownloader.downloadJSON(Gw2JSONDownloader.event_world_names_url);
        SQLiteDatabase db = mDBHelper.getWritableDatabase();

        try {/* w w w  . j  a  va 2s  . com*/
            JSONArray jsData;
            jsData = new JSONArray(result);

            for (int i = 0; i < jsData.length(); i++) {
                JSONObject obj = jsData.getJSONObject(i);
                Integer id = obj.getInt("id");
                String name = obj.getString("name");

                ContentValues row = new ContentValues(2);
                row.put("_id", id);
                row.put("name", name);

                if (db != null) {
                    db.insert(Gw2DB.WORLD_NAMES_TABLE, null, row);
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    } else {
        //TODO: Throw Exception.
    }
}

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

private void search(final String string, boolean cache) {
    try {//from  w  ww.ja  va  2s . co m
        RequestQueue requestQueue = Volley.newRequestQueue(mContext);

        String apiUri = getString(R.string.project_website_uri) + "api/1/clinicaltrials/?search="
                + URLEncoder.encode(string.toLowerCase(), "utf-8");

        if (!cache)
            requestQueue.getCache().remove(apiUri);

        JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(apiUri, new Response.Listener<JSONArray>() {
            @Override
            public void onResponse(JSONArray response) {
                mProgressBar.setVisibility(View.GONE);
                mSwipeRefreshLayout.setRefreshing(false);

                if (response.length() == 0) {
                    mSwipeRefreshLayout.setVisibility(View.GONE);
                    mNoClinicalTrialsLayout.setVisibility(View.VISIBLE);
                } else {
                    if (mTools.isTablet()) {
                        int spanCount = (response.length() == 1) ? 1 : 2;

                        mRecyclerView.setLayoutManager(
                                new StaggeredGridLayoutManager(spanCount, StaggeredGridLayoutManager.VERTICAL));
                    }

                    mRecyclerView.setAdapter(new ClinicalTrialsCardsAdapter(mContext, response));

                    ContentValues contentValues = new ContentValues();
                    contentValues.put(ClinicalTrialsSQLiteHelper.COLUMN_STRING, string);

                    SQLiteDatabase sqLiteDatabase = new ClinicalTrialsSQLiteHelper(mContext)
                            .getWritableDatabase();

                    sqLiteDatabase.delete(ClinicalTrialsSQLiteHelper.TABLE,
                            ClinicalTrialsSQLiteHelper.COLUMN_STRING + " = " + mTools.sqe(string)
                                    + " COLLATE NOCASE",
                            null);
                    sqLiteDatabase.insert(ClinicalTrialsSQLiteHelper.TABLE, null, contentValues);

                    sqLiteDatabase.close();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                mProgressBar.setVisibility(View.GONE);
                mSwipeRefreshLayout.setRefreshing(false);

                mTools.showToast(getString(R.string.clinicaltrials_cards_something_went_wrong), 1);

                finish();

                Log.e("ClinicalTrialsCards", error.toString());
            }
        });

        jsonArrayRequest.setRetryPolicy(new DefaultRetryPolicy(30000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

        requestQueue.add(jsonArrayRequest);
    } catch (Exception e) {
        Log.e("ClinicalTrialsCards", Log.getStackTraceString(e));
    }
}

From source file:com.example.jesse.barscan.BarcodeCaptureActivity.java

/**
 * onTap returns the tapped barcode result to the calling Activity.
 *///ww  w  . ja  v  a  2  s.  c om
public boolean onTap(float rawX, float rawY) {
    // Find tap point in preview frame coordinates.
    int[] location = new int[2];
    mGraphicOverlay.getLocationOnScreen(location);
    float x = (rawX - location[0]) / mGraphicOverlay.getWidthScaleFactor();
    float y = (rawY - location[1]) / mGraphicOverlay.getHeightScaleFactor();

    // Find the barcode whose center is closest to the tapped point.
    Barcode best = null;
    float bestDistance = Float.MAX_VALUE;
    for (BarcodeGraphic graphic : mGraphicOverlay.getGraphics()) {
        Barcode barcode = graphic.getBarcode();
        if (barcode.getBoundingBox().contains((int) x, (int) y)) {
            // Exact hit, no need to keep looking.
            best = barcode;
            break;
        }
        float dx = x - barcode.getBoundingBox().centerX();
        float dy = y - barcode.getBoundingBox().centerY();
        float distance = (dx * dx) + (dy * dy); // actually squared distance
        if (distance < bestDistance) {
            best = barcode;
            bestDistance = distance;
        }
    }

    if (best != null) {
        Intent data = new Intent();
        data.putExtra(BarcodeObject, best);
        setResult(CommonStatusCodes.SUCCESS, data);

        LayoutInflater inflater = getLayoutInflater();
        View layout = inflater.inflate(R.layout.barcode_toast,
                (ViewGroup) findViewById(R.id.custom_toast_container));

        Barcode barcode = data.getParcelableExtra(BarcodeCaptureActivity.BarcodeObject);
        //Barcode.DriverLicense dlBarcode = barcode.driverLicense;

        Barcode.DriverLicense sample = barcode.driverLicense;

        TextView name = (TextView) layout.findViewById(R.id.name);
        TextView address = (TextView) layout.findViewById(R.id.address);
        TextView cityStateZip = (TextView) layout.findViewById(R.id.cityStateZip);
        TextView gender = (TextView) layout.findViewById(R.id.gender);
        TextView dob = (TextView) layout.findViewById(R.id.dob);
        TableLayout tbl = (TableLayout) layout.findViewById(R.id.tableLayout);

        try {
            int age = DateDifference.generateAge(sample.birthDate);
            if (age < minAge)
                tbl.setBackgroundColor(Color.parseColor("#980517"));
            else
                tbl.setBackgroundColor(Color.parseColor("#617C17"));

        } catch (ParseException e) {
            e.printStackTrace();
        }

        String cityContent = new String(
                sample.addressCity + ", " + sample.addressState + " " + (sample.addressZip).substring(0, 5));

        address.setText(sample.addressStreet);
        cityStateZip.setText(cityContent);

        String genderString;
        if ((sample.gender).equals("1"))
            genderString = "Male";
        else if ((sample.gender).equals("2"))
            genderString = "Female";
        else
            genderString = "Other";

        gender.setText(genderString);

        dob.setText((sample.birthDate).substring(0, 2) + "/" + (sample.birthDate).substring(2, 4) + "/"
                + (sample.birthDate).substring(4, 8));

        String nameString = new String(sample.firstName + " " + sample.middleName + " " + sample.lastName);

        name.setText(nameString);

        Toast toast = new Toast(getApplicationContext());
        toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
        toast.setDuration(Toast.LENGTH_LONG);
        toast.setView(layout);
        toast.show();

        Date today = Calendar.getInstance().getTime();
        String reportDate = df.format(today);
        SQLiteDatabase db = helper.getWritableDatabase();
        ContentValues row = new ContentValues();
        row.put("dateVar", reportDate);
        row.put("dobVar", sample.birthDate);
        row.put("zipVar", sample.addressZip);
        row.put("genderVar", genderString);
        db.insert("test", null, row);
        db.close();

        return true;
    }
    return false;
}

From source file:com.fachri.makers.pets.EditorActivity.java

/**
 * Get user input from editor and save new pet into database.
 *//*from  ww w.  j av a2 s  .co m*/
private void insertPet() {
    // Read from input fields
    // Use trim to eliminate leading or trailing white space
    String nameString = mNameEditText.getText().toString().trim();
    String breedString = mBreedEditText.getText().toString().trim();
    String weightString = mWeightEditText.getText().toString().trim();
    int weight = Integer.parseInt(weightString);

    // Create database helper
    PetDbHelper mDbHelper = new PetDbHelper(this);

    // Gets the database in write mode
    SQLiteDatabase db = mDbHelper.getWritableDatabase();

    // Create a ContentValues object where column names are the keys,
    // and pet attributes from the editor are the values.
    ContentValues values = new ContentValues();
    values.put(PetContract.PetEntry.COLUMN_PET_NAME, nameString);
    values.put(PetContract.PetEntry.COLUMN_PET_BREED, breedString);
    values.put(PetContract.PetEntry.COLUMN_PET_GENDER, mGender);
    values.put(PetContract.PetEntry.COLUMN_PET_WEIGHT, weight);

    // Insert a new row for pet in the database, returning the ID of that new row.
    long newRowId = db.insert(PetContract.PetEntry.TABLE_NAME, null, values);

    // Show a toast message depending on whether or not the insertion was successful
    if (newRowId == -1) {
        // If the row ID is -1, then there was an error with insertion.
        Toast.makeText(this, "Error with saving pet", Toast.LENGTH_SHORT).show();
    } else {
        // Otherwise, the insertion was successful and we can display a toast with the row ID.
        Toast.makeText(this, "Pet saved with row id: " + newRowId, Toast.LENGTH_SHORT).show();
    }
}

From source file:org.mozilla.gecko.sync.repositories.android.AndroidBrowserHistoryDataExtender.java

/**
 * Store visit data.//from  w  ww .j  a  v  a  2  s.c om
 *
 * If a row with GUID `guid` does not exist, insert a new row.
 * If a row with GUID `guid` does exist, replace the visits column.
 *
 * @param guid The GUID to store to.
 * @param visits New visits data.
 */
public void store(String guid, JSONArray visits) {
    SQLiteDatabase db = this.getCachedWritableDatabase();

    ContentValues cv = new ContentValues();
    cv.put(COL_GUID, guid);
    if (visits == null) {
        cv.put(COL_VISITS, "[]");
    } else {
        cv.put(COL_VISITS, visits.toJSONString());
    }

    String where = COL_GUID + " = ?";
    String[] args = new String[] { guid };
    int rowsUpdated = db.update(TBL_HISTORY_EXT, cv, where, args);
    if (rowsUpdated >= 1) {
        Logger.debug(LOG_TAG, "Replaced history extension record for row with GUID " + guid);
    } else {
        long rowId = db.insert(TBL_HISTORY_EXT, null, cv);
        Logger.debug(LOG_TAG, "Inserted history extension record into row: " + rowId);
    }
}

From source file:cn.scujcc.bug.bitcoinplatformandroid.fragment.BuyAndSellFragment.java

/**
 * ??//from w  w w. java 2  s  .c o  m
 *
 * @param orderID
 */
public void saveOrderID(String orderID) {
    DatabaseHelper database = new DatabaseHelper(getActivity());//?Activity?this
    SQLiteDatabase db = null;
    db = database.getWritableDatabase();
    ContentValues cv = new ContentValues();
    cv.put("orderid", orderID);
    cv.put("time", new Date().getTime());
    db.insert("orders", null, cv);//??
}

From source file:com.almarsoft.GroundhogReader.lib.DBUtils.java

public static void updateStarredThread(boolean starred, String clean_subject, int groupid, Context context) {
    DBHelper db = new DBHelper(context);
    SQLiteDatabase dbWrite = db.getWritableDatabase();

    clean_subject = clean_subject.replace("'", "''");

    String query;//from w  ww . java  2s  .  c  om

    if (starred == false) {
        query = "DELETE FROM starred_threads WHERE subscribed_group_id=" + groupid + " AND clean_subject="
                + esc(clean_subject);
        dbWrite.execSQL(query);
    } else {
        // Check that it's not already on the table
        query = "SELECT _ID FROM starred_threads WHERE subscribed_group_id=" + groupid + " AND clean_subject="
                + esc(clean_subject);
        Cursor c = dbWrite.rawQuery(query, null);

        if (c.getCount() == 0) {
            ContentValues cv = new ContentValues();
            cv.put("subscribed_group_id", groupid);
            cv.put("clean_subject", clean_subject);
            dbWrite.insert("starred_threads", null, cv);
        }
        c.close();
    }
    dbWrite.close();
    db.close();
}

From source file:com.fututel.db.DBProvider.java

@Override
public Uri insert(Uri uri, ContentValues initialValues) {
    int matched = URI_MATCHER.match(uri);
    String matchedTable = null;//from w  ww .ja v a  2  s  .  c  o  m
    Uri baseInsertedUri = null;
    switch (matched) {
    case ACCOUNTS:
    case ACCOUNTS_ID:
        matchedTable = SipProfile.ACCOUNTS_TABLE_NAME;
        baseInsertedUri = SipProfile.ACCOUNT_ID_URI_BASE;
        break;
    case CALLLOGS:
    case CALLLOGS_ID:
        matchedTable = SipManager.CALLLOGS_TABLE_NAME;
        baseInsertedUri = SipManager.CALLLOG_ID_URI_BASE;
        break;
    case FILTERS:
    case FILTERS_ID:
        matchedTable = SipManager.FILTERS_TABLE_NAME;
        baseInsertedUri = SipManager.FILTER_ID_URI_BASE;
        break;
    case MESSAGES:
    case MESSAGES_ID:
        matchedTable = SipMessage.MESSAGES_TABLE_NAME;
        baseInsertedUri = SipMessage.MESSAGE_ID_URI_BASE;
        break;
    case ACCOUNTS_STATUS_ID:
        long id = ContentUris.parseId(uri);
        synchronized (profilesStatus) {
            SipProfileState ps = new SipProfileState();
            if (profilesStatus.containsKey(id)) {
                ContentValues currentValues = profilesStatus.get(id);
                ps.createFromContentValue(currentValues);
            }
            ps.createFromContentValue(initialValues);
            ContentValues cv = ps.getAsContentValue();
            cv.put(SipProfileState.ACCOUNT_ID, id);
            profilesStatus.put(id, cv);
            Log.d(THIS_FILE, "Added " + cv);
        }
        getContext().getContentResolver().notifyChange(uri, null);
        return uri;
    default:
        break;
    }

    if (matchedTable == null) {
        throw new IllegalArgumentException(UNKNOWN_URI_LOG + uri);
    }

    ContentValues values;

    if (initialValues != null) {
        values = new ContentValues(initialValues);
    } else {
        values = new ContentValues();
    }

    SQLiteDatabase db = mOpenHelper.getWritableDatabase();

    long rowId = db.insert(matchedTable, null, values);

    // If the insert succeeded, the row ID exists.
    if (rowId >= 0) {
        // TODO : for inserted account register it here

        Uri retUri = ContentUris.withAppendedId(baseInsertedUri, rowId);
        getContext().getContentResolver().notifyChange(retUri, null);

        if (matched == ACCOUNTS || matched == ACCOUNTS_ID) {
            broadcastAccountChange(rowId);
        }
        if (matched == CALLLOGS || matched == CALLLOGS_ID) {
            db.delete(SipManager.CALLLOGS_TABLE_NAME,
                    CallLog.Calls._ID + " IN " + "(SELECT " + CallLog.Calls._ID + " FROM "
                            + SipManager.CALLLOGS_TABLE_NAME + " ORDER BY " + CallLog.Calls.DEFAULT_SORT_ORDER
                            + " LIMIT -1 OFFSET 500)",
                    null);
        }
        if (matched == ACCOUNTS_STATUS || matched == ACCOUNTS_STATUS_ID) {
            broadcastRegistrationChange(rowId);
        }
        if (matched == FILTERS || matched == FILTERS_ID) {
            Filter.resetCache();
        }

        return retUri;
    }

    throw new SQLException("Failed to insert row into " + uri);
}

From source file:de.nware.app.hsDroid.provider.onlineService2Provider.java

@Override
public Uri insert(Uri uri, ContentValues initialValues) {
    if (mUriMatcher.match(uri) != EXAMS) {
        throw new IllegalArgumentException("Unbekannte URI " + uri);
    }//from  w w  w  . j a  va2s .com

    ContentValues contentValues;
    if (initialValues != null) {
        contentValues = new ContentValues(initialValues);
    } else {
        contentValues = new ContentValues();
    }
    if (mOpenHelper == null) {
        Log.d(TAG, "mOpenHelper NULL");
    }
    SQLiteDatabase db = mOpenHelper.getWritableDatabase();
    long rowID = db.insert(mOpenHelper.getTableName(), ExamsCol.EXAMNAME, contentValues);
    if (rowID > 0) {
        Uri examsUri = ContentUris.withAppendedId(ExamsCol.CONTENT_URI, rowID);
        getContext().getContentResolver().notifyChange(examsUri, null); // Observer?
        return examsUri;
    }
    throw new SQLException("Konnte row nicht zu " + uri + " hinzufgen");
}