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:heartware.com.heartware_master.DBAdapter.java

public void createProfile(HashMap<String, String> queryValues) {
    SQLiteDatabase database = this.getWritableDatabase();
    ContentValues values = new ContentValues();
    values.put(USERNAME, queryValues.get(USERNAME));
    values.put(PASSWORD, queryValues.get(PASSWORD));
    values.put(DIFFICULTY, queryValues.get(DIFFICULTY));
    values.put(DISABILITY, queryValues.get(DISABILITY));
    database.insert(PROFILES_TABLE, null, values);
    database.close();/*  www  . ja v a2 s  . com*/
}

From source file:cn.edu.wyu.documentviewer.RecentsProvider.java

@Override
public Uri insert(Uri uri, ContentValues values) {
    final SQLiteDatabase db = mHelper.getWritableDatabase();
    final ContentValues key = new ContentValues();
    switch (sMatcher.match(uri)) {
    case URI_RECENT:
        values.put(RecentColumns.TIMESTAMP, System.currentTimeMillis());
        db.insert(TABLE_RECENT, null, values);
        final long cutoff = System.currentTimeMillis() - MAX_HISTORY_IN_MILLIS;
        db.delete(TABLE_RECENT, RecentColumns.TIMESTAMP + "<" + cutoff, null);
        return uri;
    case URI_STATE:
        final String authority = uri.getPathSegments().get(1);
        final String rootId = uri.getPathSegments().get(2);
        final String documentId = uri.getPathSegments().get(3);

        key.put(StateColumns.AUTHORITY, authority);
        key.put(StateColumns.ROOT_ID, rootId);
        key.put(StateColumns.DOCUMENT_ID, documentId);

        // Ensure that row exists, then update with changed values
        db.insertWithOnConflict(TABLE_STATE, null, key, SQLiteDatabase.CONFLICT_IGNORE);
        db.update(TABLE_STATE, values, StateColumns.AUTHORITY + "=? AND " + StateColumns.ROOT_ID + "=? AND "
                + StateColumns.DOCUMENT_ID + "=?", new String[] { authority, rootId, documentId });

        return uri;
    case URI_RESUME:
        values.put(ResumeColumns.TIMESTAMP, System.currentTimeMillis());

        final String packageName = uri.getPathSegments().get(1);
        key.put(ResumeColumns.PACKAGE_NAME, packageName);

        // Ensure that row exists, then update with changed values
        db.insertWithOnConflict(TABLE_RESUME, null, key, SQLiteDatabase.CONFLICT_IGNORE);
        db.update(TABLE_RESUME, values, ResumeColumns.PACKAGE_NAME + "=?", new String[] { packageName });
        return uri;
    default:/*w w w  . ja v  a2  s. c  o m*/
        throw new UnsupportedOperationException("Unsupported Uri " + uri);
    }
}

From source file:com.seneca.android.senfitbeta.DbHelper.java

public boolean insertCAL(int num, int month, int day, int year, String name) {
    Log.d("INSERT Calen", "Inserting dates...");

    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues values = new ContentValues();

    values.put(CAL_NUM, num);/*from  w  ww. j  a  v a2s .  c om*/
    values.put(MONTH, month);
    values.put(DAY, day);
    values.put(YEAR, year);
    values.put(CAL_NAME, name);

    long info = db.insert(CALENDER_TABLE, null, values);

    if (info != -1) {
        return true;
    }

    return false;
}

From source file:nerd.tuxmobil.fahrplan.congress.FahrplanMisc.java

public static void addAlarm(Context context, Lecture lecture, int alarmTimesIndex) {
    int[] alarm_times = { 0, 5, 10, 15, 30, 45, 60 };
    long when;//w  w  w .  j a va 2  s.c  o  m
    Time time;
    long startTime;
    long startTimeInSeconds = lecture.dateUTC;

    if (startTimeInSeconds > 0) {
        when = startTimeInSeconds;
        startTime = startTimeInSeconds;
        time = new Time();
    } else {
        time = lecture.getTime();
        startTime = time.normalize(true);
        when = time.normalize(true);
    }
    long alarmTimeDiffInSeconds = alarm_times[alarmTimesIndex] * 60 * 1000;
    when -= alarmTimeDiffInSeconds;

    // DEBUG
    // when = System.currentTimeMillis() + (30 * 1000);

    time.set(when);
    MyApp.LogDebug("addAlarm", "Alarm time: " + time.format("%Y-%m-%dT%H:%M:%S%z") + ", in seconds: " + when);

    Intent intent = new Intent(context, AlarmReceiver.class);
    intent.putExtra(BundleKeys.ALARM_LECTURE_ID, lecture.lecture_id);
    intent.putExtra(BundleKeys.ALARM_DAY, lecture.day);
    intent.putExtra(BundleKeys.ALARM_TITLE, lecture.title);
    intent.putExtra(BundleKeys.ALARM_START_TIME, startTime);
    intent.setAction(AlarmReceiver.ALARM_LECTURE);

    intent.setData(Uri.parse("alarm://" + lecture.lecture_id));

    AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    PendingIntent pendingintent = PendingIntent.getBroadcast(context, Integer.parseInt(lecture.lecture_id),
            intent, 0);

    // Cancel any existing alarms for this lecture
    alarmManager.cancel(pendingintent);

    // Set new alarm
    alarmManager.set(AlarmManager.RTC_WAKEUP, when, pendingintent);

    int alarmTimeInMin = alarm_times[alarmTimesIndex];

    // write to DB

    AlarmsDBOpenHelper alarmDB = new AlarmsDBOpenHelper(context);

    SQLiteDatabase db = alarmDB.getWritableDatabase();

    // delete any previous alarms of this lecture
    try {
        db.beginTransaction();
        db.delete(AlarmsTable.NAME, AlarmsTable.Columns.EVENT_ID + "=?", new String[] { lecture.lecture_id });

        ContentValues values = new ContentValues();

        values.put(AlarmsTable.Columns.EVENT_ID, Integer.parseInt(lecture.lecture_id));
        values.put(AlarmsTable.Columns.EVENT_TITLE, lecture.title);
        values.put(AlarmsTable.Columns.ALARM_TIME_IN_MIN, alarmTimeInMin);
        values.put(AlarmsTable.Columns.TIME, when);
        DateFormat df = SimpleDateFormat.getDateTimeInstance(SimpleDateFormat.SHORT, SimpleDateFormat.SHORT);
        values.put(AlarmsTable.Columns.TIME_TEXT, df.format(new Date(when)));
        values.put(AlarmsTable.Columns.DISPLAY_TIME, startTime);
        values.put(AlarmsTable.Columns.DAY, lecture.day);

        db.insert(AlarmsTable.NAME, null, values);
        db.setTransactionSuccessful();
    } catch (SQLException e) {
    } finally {
        db.endTransaction();
        db.close();
    }

    lecture.has_alarm = true;
}

From source file:com.hufeiya.SignIn.persistence.TopekaDatabaseHelper.java

private void fillCategory(SQLiteDatabase db, ContentValues values, JSONObject category, String categoryId)
        throws JSONException {
    values.clear();/*from  w w  w . j a v a  2 s  . c  om*/
    values.put(CategoryTable.COLUMN_ID, categoryId);
    values.put(CategoryTable.COLUMN_NAME, category.getString(JsonAttributes.NAME));
    values.put(CategoryTable.COLUMN_THEME, category.getString(JsonAttributes.THEME));
    values.put(CategoryTable.COLUMN_SOLVED, category.getString(JsonAttributes.SOLVED));
    db.insert(CategoryTable.NAME, null, values);
}

From source file:com.citrus.sdk.database.DBHandler.java

public void addBankOptions(JSONArray netbankingOption) {
    SQLiteDatabase db = this.getWritableDatabase();

    for (int i = 0; i < netbankingOption.length(); i++) {
        ContentValues loadValue = new ContentValues();
        try {//from w  w w.j  a v a 2 s .c om
            JSONObject bankOption = netbankingOption.getJSONObject(i);
            loadValue.put(BANK, bankOption.getString("bankName"));
            loadValue.put(BANK_CID, bankOption.getString("issuerCode"));
        } catch (JSONException e) {

        }
        db.insert(BANK_TABLE, null, loadValue);
    }
}

From source file:com.example.easyvoice.MessageDetail.java

public void onSave(View view) {

    Log.i("MessageDetail", "onSave");

    SQLiteDatabase sampleDB = null;
    try {/*ww w .j a va2 s  .c om*/
        sampleDB = this.openOrCreateDatabase(DB_NAME, MODE_PRIVATE, null);

        ContentValues values = new ContentValues();
        values.putNull("msg_id");
        values.put("disp_name", displayEdit.getText().toString());
        values.put("content", contentEdit.getText().toString());

        long insertId = sampleDB.insert(TABLE_NAME, null, values);
        Log.i(getClass().getSimpleName(), "inserted " + Long.toString(insertId));

        // invalidate?

        // go back
        Intent intent = new Intent(this, MainActivity.class);
        startActivity(intent);

    } catch (SQLiteException se) {
        Log.e(getClass().getSimpleName(), "Could not create or Open the database");
    }

}

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

/**
 * Inserts a value in the database.// w w w .ja va  2  s. c o m
 * 
 * @param table
  *      The table where the values will be inserted
 * @param values
 *      The values that will be inserted
 * @throws
 *       SQLiteException   Thrown, if writing to the database failed.
 */
private synchronized void insert(String table, ContentValues values) {
    // Insert value into table

    try {
        SQLiteDatabase db = this.getWritableDatabase();

        db.insert(table, null, values);

        db.close();
    } catch (SQLiteException e) {
        Log.e(TAG, "Failed writing to database.");
    }
}

From source file:com.dm.material.dashboard.candybar.databases.Database.java

public void addAllWallpapers(WallpaperJSON wallpaper) {
    SQLiteDatabase db = this.getWritableDatabase();
    for (int i = 0; i < wallpaper.getWalls.size(); i++) {
        ContentValues values = new ContentValues();
        values.put(KEY_NAME, wallpaper.getWalls.get(i).name);
        values.put(KEY_AUTHOR, wallpaper.getWalls.get(i).author);
        values.put(KEY_URL, wallpaper.getWalls.get(i).url);
        values.put(KEY_THUMB_URL, wallpaper.getWalls.get(i).thumbUrl);

        db.insert(TABLE_WALLPAPERS, null, values);
    }/*from w  w  w  .j av a  2s  .  co  m*/
    db.close();
}

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

private void search(final String string, boolean cache) {
    try {/*ww  w. j  av  a 2s. c  o m*/
        RequestQueue requestQueue = Volley.newRequestQueue(mContext);

        String apiUri = getString(R.string.project_website_uri) + "api/1/interactions/?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);
                    mNoInteractionsLayout.setVisibility(View.VISIBLE);
                } else {
                    if (mTools.isTablet()) {
                        int spanCount = (response.length() == 1) ? 1 : 2;

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

                    mRecyclerView.setAdapter(new InteractionsCardsAdapter(mContext, mProgressBar, response));

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

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

                    sqLiteDatabase.delete(InteractionsSQLiteHelper.TABLE, InteractionsSQLiteHelper.COLUMN_STRING
                            + " = " + mTools.sqe(string) + " COLLATE NOCASE", null);
                    sqLiteDatabase.insert(InteractionsSQLiteHelper.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.interactions_cards_something_went_wrong), 1);

                finish();

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

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