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.android.leanlauncher.WidgetPreviewLoader.java

private void writeToDb(Object o, Bitmap preview) {
    String name = getObjectName(o);
    SQLiteDatabase db = mDb.getWritableDatabase();
    ContentValues values = new ContentValues();

    values.put(CacheDb.COLUMN_NAME, name);
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    preview.compress(Bitmap.CompressFormat.PNG, 100, stream);
    values.put(CacheDb.COLUMN_PREVIEW_BITMAP, stream.toByteArray());
    values.put(CacheDb.COLUMN_SIZE, mSize);
    try {/*  w ww  .jav  a 2  s. c o  m*/
        db.insert(CacheDb.TABLE_NAME, null, values);
    } catch (SQLiteDiskIOException e) {
        recreateDb();
    } catch (SQLiteCantOpenDatabaseException e) {
        throw e;
    }
}

From source file:syncthing.android.settings.AppSettings.java

public void saveCredentials(Credentials creds) {
    SQLiteDatabase _db = db.getWritableDatabase();
    Cursor c = null;//from ww w. java  2s  . co  m
    try {
        ContentValues cv = new ContentValues();
        cv.put(CredentialsDB.SCHEMA.ALIAS, creds.alias);
        cv.put(CredentialsDB.SCHEMA.URL, creds.url);
        cv.put(CredentialsDB.SCHEMA.API_KEY, creds.apiKey);
        cv.put(CredentialsDB.SCHEMA.CERT, creds.caCert);
        String[] sel = new String[] { creds.id };
        _db.beginTransaction();
        c = _db.query(CredentialsDB.SCHEMA.TABLE, idCols, credentialsDeviceIdSel, sel, null, null, null);
        if (c != null && c.getCount() > 0) {
            _db.update(CredentialsDB.SCHEMA.TABLE, cv, credentialsDeviceIdSel, sel);
        } else {
            cv.put(CredentialsDB.SCHEMA.DEVICE_ID, creds.id);
            _db.insert(CredentialsDB.SCHEMA.TABLE, null, cv);
        }
        _db.setTransactionSuccessful();
    } finally {
        _db.endTransaction();
        if (c != null)
            c.close();
    }
}

From source file:net.smart_json_database.JSONDatabase.java

private int insertTag(String name, SQLiteDatabase db) {
    int returnValue = -1;

    ContentValues value = new ContentValues();
    value.put("name", name);
    returnValue = Util.LongToInt(db.insert(TABLE_TAG, null, value));
    tags.put(name, new Integer(returnValue));
    invertedTags.put(new Integer(returnValue), name);

    return returnValue;
}

From source file:com.data.pack.ViewVideo.java

/**
 * Insert data into table/*ww  w. ja v a 2 s. c  om*/
 * 
 * @param String
 *            , String , String , String , String ,String ,String
 * @return
 */
private void insertDurationData(String id, String duration) {
    try {
        SQLiteDatabase db = placeData.getWritableDatabase();
        ContentValues values;
        values = new ContentValues();
        values.put("ID", id);
        values.put("Duration", duration);
        db.insert("FitnessWorkoutDuration", null, values);
        db.close();
    } catch (Exception e) {
        // TODO: handle exception
    }
}

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

private void _update_event_names() {
    if (Gw2JSONDownloader.internetAvailable(mContext)) {
        String result = Gw2JSONDownloader.downloadJSON(Gw2JSONDownloader.event_names_url);

        SQLiteDatabase db = mDBHelper.getWritableDatabase();
        Cursor cursor = db.query(Gw2DB.EVENT_NAMES_TABLE, null, null, null, null, null, null);

        JSONArray jsData;//from ww  w  .  j a  va2  s.c  o m

        try {
            jsData = new JSONArray(result);
            Log.d("Gw2", "LENGTH: " + jsData.length());
            Log.d("Gw2", "POCESSING STARTS");
            for (int i = 0; i < jsData.length(); i++) {
                JSONObject obj = jsData.getJSONObject(i);
                String id = obj.getString("id");
                String name = obj.getString("name");
                //Log.d("Gw2", name);

                ContentValues row = new ContentValues(3);
                row.put("_id", id);
                row.put("name", name);
                row.put("lang", "en");

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

From source file:eu.rubenrosado.tinypasswordmanager.AllRows.java

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == 0) {
        if (resultCode == Activity.RESULT_OK) {
            toastMessage(getString(R.string.saving));
            int position = data.getIntExtra("position", -1);
            int id = data.getIntExtra("id", -1);
            String site = data.getStringExtra("site");
            String user = data.getStringExtra("user");
            String password = data.getStringExtra("password");

            DBHelper dbhelper = new DBHelper(this);
            SQLiteDatabase sql = dbhelper.getWritableDatabase();

            try {
                ObjectRows sp = new ObjectRows(id, Encryption.decrypt(Main.MASTERPASSWORD, site),
                        Encryption.decrypt(Main.MASTERPASSWORD, user), HIDEPW);
                ContentValues cv = new ContentValues();
                cv.put(DBHelper.COLSITE, site);
                cv.put(DBHelper.COLUSER, user);
                cv.put(DBHelper.COLPASS, password);
                if (position != -1) {
                    sql.update(DBHelper.TABLENAME, cv, DBHelper.COLID + "=" + id, null);
                    spArray.set(position, sp);
                    decryptedPasswords.set(position, Encryption.decrypt(Main.MASTERPASSWORD, password));
                } else {
                    sql.insert(DBHelper.TABLENAME, null, cv);
                    spArray.add(sp);//from   w  ww. j a va 2  s.com
                    decryptedPasswords.add(Encryption.decrypt(Main.MASTERPASSWORD, password));
                }
                toastMessage(getString(R.string.saved));
            } catch (Exception e) {
                toastMessage(getString(R.string.internal_error));
            } finally {
                sql.close();
                dbhelper.close();
            }
            adapter.notifyDataSetChanged();
        }
    }
}

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

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Connected?
    if (!mTools.isDeviceConnected()) {
        mTools.showToast(getString(R.string.device_not_connected), 1);

        finish();/*  www .  ja  v  a  2 s.  c  om*/

        return;
    }

    // Intent
    final Intent intent = getIntent();

    searchString = intent.getStringExtra("search");

    // Layout
    setContentView(R.layout.activity_poisonings_cards);

    // Toolbar
    mToolbar = (Toolbar) findViewById(R.id.poisonings_cards_toolbar);
    mToolbar.setTitle(getString(R.string.poisonings_cards_search) + ": \"" + searchString + "\"");

    setSupportActionBar(mToolbar);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    // Progress bar
    mProgressBar = (ProgressBar) findViewById(R.id.poisonings_cards_toolbar_progressbar);
    mProgressBar.setVisibility(View.VISIBLE);

    // Refresh
    mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.poisonings_cards_swipe_refresh_layout);
    mSwipeRefreshLayout.setColorSchemeResources(R.color.accent_blue, R.color.accent_green,
            R.color.accent_purple, R.color.accent_orange);

    mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
            search(searchString, false);
        }
    });

    // Recycler view
    mRecyclerView = (RecyclerView) findViewById(R.id.poisonings_cards_cards);

    mRecyclerView.setHasFixedSize(true);
    mRecyclerView.setAdapter(new PoisoningsCardsAdapter(mContext, new JSONArray()));
    mRecyclerView.setLayoutManager(new LinearLayoutManager(mContext));

    // No poisonings
    mNoPoisoningsLayout = (LinearLayout) findViewById(R.id.poisonings_cards_no_poisonings);

    Button noPoisoningsHelsenorgeButton = (Button) findViewById(R.id.poisonings_cards_check_on_helsenorge);
    Button noPoisoningsHelsebiblioteketButton = (Button) findViewById(
            R.id.poisonings_cards_check_on_helsebiblioteket);

    noPoisoningsHelsenorgeButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            try {
                Intent intent = new Intent(mContext, MainWebViewActivity.class);
                intent.putExtra("title",
                        getString(R.string.poisonings_cards_search) + ": \"" + searchString + "\"");
                intent.putExtra("uri", "https://helsenorge.no/sok/giftinformasjon/?k="
                        + URLEncoder.encode(searchString.toLowerCase(), "utf-8"));
                mContext.startActivity(intent);
            } catch (Exception e) {
                Log.e("PoisoningsCardsActivity", Log.getStackTraceString(e));
            }
        }
    });

    noPoisoningsHelsebiblioteketButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            try {
                Intent intent = new Intent(mContext, MainWebViewActivity.class);
                intent.putExtra("title",
                        getString(R.string.poisonings_cards_search) + ": \"" + searchString + "\"");
                intent.putExtra("uri",
                        "http://www.helsebiblioteket.no/forgiftninger/alle-anbefalinger?cx=005475784484624053973%3A3bnj2dj_uei&ie=UTF-8&q="
                                + URLEncoder.encode(searchString.toLowerCase(), "utf-8") + "&sa=S%C3%B8k");
                mContext.startActivity(intent);
            } catch (Exception e) {
                Log.e("PoisoningsCardsActivity", Log.getStackTraceString(e));
            }
        }
    });

    // Search
    search(searchString, true);

    // Correct
    RequestQueue requestQueue = Volley.newRequestQueue(mContext);

    try {
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET,
                getString(R.string.project_website_uri) + "api/1/correct/?search="
                        + URLEncoder.encode(searchString, "utf-8"),
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        try {
                            final String correctSearchString = response.getString("correct");

                            if (!correctSearchString.equals("")) {
                                new MaterialDialog.Builder(mContext)
                                        .title(getString(R.string.correct_dialog_title))
                                        .content(Html.fromHtml(getString(R.string.correct_dialog_message)
                                                + ":<br><br><b>" + correctSearchString + "</b>"))
                                        .positiveText(getString(R.string.correct_dialog_positive_button))
                                        .negativeText(getString(R.string.correct_dialog_negative_button))
                                        .callback(new MaterialDialog.ButtonCallback() {
                                            @Override
                                            public void onPositive(MaterialDialog dialog) {
                                                ContentValues contentValues = new ContentValues();
                                                contentValues.put(PoisoningsSQLiteHelper.COLUMN_STRING,
                                                        correctSearchString);

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

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

                                                sqLiteDatabase.close();

                                                mToolbar.setTitle(getString(R.string.poisonings_cards_search)
                                                        + ": \"" + correctSearchString + "\"");

                                                mProgressBar.setVisibility(View.VISIBLE);

                                                mNoPoisoningsLayout.setVisibility(View.GONE);
                                                mSwipeRefreshLayout.setVisibility(View.VISIBLE);

                                                search(correctSearchString, true);
                                            }
                                        }).contentColorRes(R.color.black).positiveColorRes(R.color.dark_blue)
                                        .negativeColorRes(R.color.black).show();
                            }
                        } catch (Exception e) {
                            Log.e("PoisoningsCardsActivity", Log.getStackTraceString(e));
                        }
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Log.e("PoisoningsCardsActivity", error.toString());
                    }
                });

        jsonObjectRequest.setRetryPolicy(new DefaultRetryPolicy(10000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

        requestQueue.add(jsonObjectRequest);
    } catch (Exception e) {
        Log.e("PoisoningsCardsActivity", Log.getStackTraceString(e));
    }
}

From source file:com.osfans.trime.DictionaryHelper.java

private boolean importSchema(InputStream is) {
    boolean success = false;
    SQLiteDatabase db = getWritableDatabase();
    db.beginTransaction();/*from www  . j a v  a2 s . c o m*/
    try {
        Yaml yaml = new Yaml();
        Map<String, Object> y = (Map<String, Object>) (yaml.load(is));
        Map<String, Object> m = (Map<String, Object>) y.get("schema");
        String schema_id = (String) m.get("schema_id");
        String name = (String) m.get("name");
        String full = yaml.dump(y);
        is.close();

        ContentValues initialValues = new ContentValues();
        initialValues.put("schema_id", schema_id);
        initialValues.put("name", name);
        initialValues.put("full", full);

        long r = db.update("schema", initialValues, "schema_id = ?", new String[] { schema_id });
        if (r == 0)
            r = db.insert("schema", null, initialValues);
        db.setTransactionSuccessful();
        success = true;
    } catch (Exception e) {
        throw new RuntimeException("Error import schema", e);
    } finally {
        db.endTransaction();
    }
    return success;
}

From source file:com.maxwen.wallpaper.board.databases.Database.java

public void addCategories(List<Category> categories) {
    SQLiteDatabase db = this.getWritableDatabase();
    for (int i = 0; i < categories.size(); i++) {
        ContentValues values = new ContentValues();
        values.put(KEY_NAME, categories.get(i).getName());
        values.put(KEY_THUMB_URL, categories.get(i).getThumbUrl());
        // new categories are always selected by default
        values.put(KEY_SELECTED, 1);/*from w  ww  .  jav  a 2s  .  c o m*/

        db.insert(TABLE_CATEGORIES, null, values);
    }
    db.close();
}

From source file:net.smart_json_database.JSONDatabase.java

private int relateTagWithJsonEntity(int from, int to, SQLiteDatabase db) {
    int returnValue = -1;
    ContentValues values = new ContentValues();
    values.put("from_id", from);
    values.put("to_id", to);
    returnValue = Util.LongToInt(db.insert(TABLE_REL_TAG_JSON_DATA, null, values));
    return returnValue;
}