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.almarsoft.GroundhogReader.lib.DBUtils.java

public static long insertArticleToGroupID(int groupID, Article articleInfo, String finalRefs, String finalFrom,
        String finalSubject, Context context, SQLiteDatabase catchedDB) {

    // The called can create a single SQLiteDatabase object to avoid too many object
    // creations if we're inside a loop
    DBHelper db = null;/*from  w  w w  . ja  v  a  2  s.c o m*/
    SQLiteDatabase dbwrite = null;

    if (catchedDB == null) {
        db = new DBHelper(context);
        dbwrite = db.getWritableDatabase();
    } else {
        dbwrite = catchedDB;
    }

    ContentValues cv = new ContentValues();
    cv.put("subscribed_group_id", groupID);
    cv.put("reference_list", finalRefs);
    cv.put("server_article_id", articleInfo.getArticleId());
    cv.put("date", articleInfo.getDate());
    cv.put("server_article_number", articleInfo.getArticleNumber());
    cv.put("from_header", finalFrom);
    cv.put("subject_header", finalSubject);
    cv.put("read", 0);
    cv.put("catched", 0);

    long ret = dbwrite.insert("headers", null, cv);

    if (catchedDB == null) {
        dbwrite.close();
        db.close();
    }
    return ret;
}

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

private void search(final String string, boolean cache) {
    try {//from  ww w .j  a  va2 s.com
        RequestQueue requestQueue = Volley.newRequestQueue(mContext);

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

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

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

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

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

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

                finish();

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

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

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

From source file:heartware.com.heartware_master.DBAdapter.java

public void createMeetup(HashMap<String, String> queryValues) {
    SQLiteDatabase database = this.getWritableDatabase();
    ContentValues values = new ContentValues();
    values.put(USER_ID, queryValues.get(USER_ID));
    values.put(NOTE, queryValues.get(NOTE));
    values.put(EXERCISE, queryValues.get(EXERCISE));
    values.put(LOCATION, queryValues.get(LOCATION));
    values.put(DATE, queryValues.get(DATE));
    values.put(PEOPLE, queryValues.get(PEOPLE));
    database.insert(MEETUPS_TABLE, null, values);
    database.close();//from w  w  w. j  a  va 2 s . c om
}

From source file:tk.android.client.activity.Activity_client.java

@Override
public void onClick(View v) {
    switch (v.getId()) {
    case R.id.button_version: {
        try {//from ww  w.j a v  a2s. co m
            startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(PLAY_STORE_URL)));
        } catch (ActivityNotFoundException e) {
            e.printStackTrace();
        }
        break;
    }
    case R.id.layout_support: {
        startActivity(new Intent(activity, Activity_user.class)
                .setData(Uri.parse("https://twitter.com/OrangeSphereApp")));
        break;
    }
    case R.id.layout_pro: {
        if (PropertyManager.getInstance().isProUser()) {
            Toast.makeText(activity, "You alreadry Pro User :)", Toast.LENGTH_SHORT).show();
            break;
        }
        String TAG = "EditDialog-Pro";
        final EditDialog dialog = new EditDialog();
        dialog.newInstance(activity);
        dialog.setTitle(R.string.advertisement);
        dialog.setOnFinishEditListener(new OnFinishEditListener() {

            @Override
            public void onFinishEdit(final String text) {
                int length = text.length();
                if (length > 100 || length == 0) {
                    Toast.makeText(activity, R.string.bad_string_length, Toast.LENGTH_SHORT).show();
                    return;
                }
                dialog.dismiss();
                new Thread(new Runnable() {

                    @Override
                    public void run() {
                        try {
                            Twitter twitter = core.getTwitter();
                            if (twitter == null) {
                                throw new Exception();
                            }
                            twitter.updateStatus(text + " " + PLAY_STORE_URL + " #OrangeSphere");
                            PropertyManager.getInstance().toBeProUser();
                            SQLiteManager manager = new SQLiteManager(activity);
                            SQLiteDatabase db = manager.getWritableDatabase();
                            ContentValues values = new ContentValues();
                            values.put("client_name", "OrangeSpherePro");
                            values.put("consumer_key", "b1NEqKgA8CGudo6yhkg");
                            values.put("consumer_secret", "awqnQwi3BXUqkyjlMZHlDIvad3bV3cVO03MxRTV4s");
                            db.insert("client_table", null, values);
                            db.close();
                            new UiHandler() {

                                @Override
                                public void run() {
                                    Toast.makeText(activity, R.string.be_pro_user, Toast.LENGTH_SHORT).show();
                                }

                            }.post();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                }).start();
            }

        });
        dialog.show(getSupportFragmentManager(), TAG);
        break;
    }
    case R.id.layout_license: {
        new LicenseDialog().show(getSupportFragmentManager(), "LicenseDialog");
        break;
    }
    }
}

From source file:com.yammy.meter.MainActivity.java

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

    setContentView(R.layout.isvo_activity_main);
    lat = (TextView) this.findViewById(R.id.main_lat);
    longi = (TextView) this.findViewById(R.id.main_long);
    nopol = (TextView) this.findViewById(R.id.main_nopol);
    jarak = (TextView) this.findViewById(R.id.main_jarak);
    start = (Button) this.findViewById(R.id.buttonStartRec);
    stop = (Button) this.findViewById(R.id.buttonStopRec);
    reset = (Button) this.findViewById(R.id.buttonClrMapMain);
    stop.setEnabled(false);/*from  w w w  . j  a  va2s .com*/
    reset.setEnabled(false);
    Location location = null;

    getVehVal();

    int result = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getApplicationContext());
    if (result != ConnectionResult.SUCCESS) {
        GooglePlayServicesUtil.getErrorDialog(result, MainActivity.this, 1).show();
    } else {
        /**
         * try to get current location via GPS
         * pending : path recording using Polyline & get length
         */

        locationManager = (LocationManager) this.getSystemService(LOCATION_SERVICE);
        boolean enabledGPS = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        if (!enabledGPS) {
            requestGPS();
            finish();
        }

        map = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map_main)).getMap();
        GooglePlayServicesUtil.getOpenSourceSoftwareLicenseInfo(getBaseContext());

        map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
        map.setIndoorEnabled(false);

        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 2000, 0, this);
        location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);

        try {
            user_pos = new LatLng(location.getLatitude(), location.getLongitude());
            if (location != null
                    && location.getTime() > Calendar.getInstance().getTimeInMillis() - 2 * 60 * 1000) {
                Toast.makeText(getApplicationContext(),
                        "Current Location : " + location.getLatitude() + "," + location.getLongitude(),
                        Toast.LENGTH_LONG).show();
                drawMarker(location);
            } else {
                locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, this);
                drawMarker(location);
            }
        } catch (NullPointerException e) {
            //requestGPS();
        }
    }

    start.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            recording = true;
            Toast.makeText(getBaseContext(), "Mulai merekam perjalanan", Toast.LENGTH_SHORT).show();
            stop.setEnabled(true);
            start.setEnabled(false);
            reset.setEnabled(false);
            jarakTotal = 0.0;
        }
    });
    stop.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            recording = false;
            Toast.makeText(getBaseContext(), "Selesai merekam perjalanan", Toast.LENGTH_SHORT).show();
            Toast.makeText(getBaseContext(), "Perjalanan terakhir " + jarakTotal + " m", Toast.LENGTH_SHORT)
                    .show();
            /**
             * then save to database
             */
            try {
                dbHelper = new MySQLHelper(getApplicationContext());
                SQLiteDatabase db = dbHelper.getWritableDatabase();
                ContentValues simpan = new ContentValues();
                simpan.put("id_kendaraan", idkendaraan);
                simpan.put("jarak", jarakTotal);
                db.insert("perjalanan", null, simpan);
                Toast.makeText(getBaseContext(), "Perjalanan tersimpan", Toast.LENGTH_SHORT).show();
                db.close();
            } catch (Exception e) {
                Toast.makeText(getBaseContext(), "Tidak bisa menyimpan perjalanan", Toast.LENGTH_SHORT).show();
            }

            //partial reset
            stop.setEnabled(false);
            start.setEnabled(true);
            reset.setEnabled(true);
            jarakTotal = 0.0;

            checkJarak();
        }
    });
    reset.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            map.clear();
            jarakTotal = 0.0;
            jarak.setText(null);
        }
    });
    checkJarak();
}

From source file:net.survivalpad.android.entity.Article.java

@Override
public long insert(SQLiteDatabase db) {
    ContentValues values = new ContentValues();
    write(values);//from ww w. j a va 2  s  .  c  o  m
    id = db.insert(getTableName(), null, values);

    for (Column column : columns) {
        column.setArticleId(id);
        column.insert(db);
    }

    for (DisasterType disasterType : disasterTypes) {
        ArticleDisasterType obj = new ArticleDisasterType();
        obj.setArticleId(id);
        obj.setDisastertypeId(disasterType.getId());
        obj.insert(db);
    }

    return id;
}

From source file:com.example.shutapp.DatabaseHandler.java

/**
 * Adds a chatroom to the database.//from  w ww  . j ava 2  s .c  om
 * @param chatroom
 */
public void addChatroom(Chatroom chatroom) {
    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues values = new ContentValues();
    values.put(KEY_NAME, chatroom.getName()); // Chatroom Name
    values.put(KEY_LATITUDE, chatroom.getLatitude()); // Chatroom Latitude
    values.put(KEY_LONGITUDE, chatroom.getLongitude()); // Chatroom Longitude
    values.put(KEY_RADIUS, chatroom.getRadius()); // Chatroom Radius

    // Inserting Row
    db.insert(TABLE_CHATROOMS, null, values);
    db.close(); // Closing database connection
}

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

public void insertExercise(String aut, String des, String name, String ogName, String date, String cat,
        int id) {
    Log.d("INSERT EXDB", "Inserting exercise...");

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

    values.put(AUTHOR, aut);/*  w w  w  . j a  v  a2s  .  co m*/
    values.put(DESCRIPTION, des);
    values.put(NAMETYPE, name);
    values.put(ORIGNALNAME, ogName);
    values.put(CREATIONDATE, date);
    values.put(CATEGORY, cat);
    values.put(EXERCISE_ID, id);

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

From source file:org.akop.crosswords.Storage.java

public void write(long puzzleId, Crossword.State state) {
    long started = SystemClock.uptimeMillis();

    ContentValues cv = new ContentValues();

    cv.put(PuzzleState.PUZZLE_ID, puzzleId);
    cv.put(PuzzleState.CLASS, state.getClass().getName());
    cv.put(PuzzleState.OBJECT, mGson.toJson(state));
    cv.put(PuzzleState.OBJECT_VERSION, 1);
    cv.put(PuzzleState.PERCENT_SOLVED, state.getPercentSolved());
    cv.put(PuzzleState.PERCENT_CHEATED, state.getPercentCheated());
    cv.put(PuzzleState.PERCENT_WRONG, state.getPercentWrong());
    cv.put(PuzzleState.PLAY_TIME_MILLIS, state.getPlayTimeMillis());

    long lastPlayed = 0;
    if (state.getLastPlayed() != null) {
        lastPlayed = state.getLastPlayed().getMillis();
    }/*from  w  ww. jav  a 2s. co m*/
    cv.put(PuzzleState.LAST_PLAYED, lastPlayed);

    cv.put(PuzzleState.LAST_UPDATED, System.currentTimeMillis());

    StorageHelper helper = getHelper();
    SQLiteDatabase db = helper.getWritableDatabase();

    try {
        // Delete any existing rows
        db.delete(PuzzleState.TABLE, PuzzleState.PUZZLE_ID + "=" + puzzleId, null);
        // Insert the new one
        db.insert(PuzzleState.TABLE, null, cv);
    } finally {
        db.close();
    }

    Crosswords.logv("Wrote state for %d (%dms)", puzzleId, SystemClock.uptimeMillis() - started);

    // Add a copy to the cache
    mStateCache.put((int) puzzleId, new Crossword.State(state));

    // Broadcast the change
    Intent intent = new Intent(ACTION_PUZZLE_STATE_CHANGE);
    intent.putExtra(INTENT_PUZZLE_ID, puzzleId);

    Context context = Crosswords.getInstance();
    LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
}

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

public static void banThread(String group, String clean_subject, Context context) {
    int groupid = getGroupIdFromName(group, context);

    DBHelper db = new DBHelper(context);
    SQLiteDatabase dbwrite = db.getWritableDatabase();

    // First, check if it already is on the banned_threads table (it could be with unbanned=1)
    Cursor c = dbwrite.rawQuery("SELECT _id FROM banned_threads " + " WHERE subscribed_group_id=" + groupid
            + " AND clean_subject=" + esc(clean_subject), null);

    if (c.getCount() > 0) { // Existed
        c.moveToFirst();/*  w  w w .  j ava2  s .  c  o m*/
        dbwrite.execSQL("UPDATE banned_threads SET bandisabled=0 WHERE _id=" + c.getInt(0));

    } else {
        // New troll goes down to the pit
        ContentValues cv = new ContentValues();
        cv.put("subscribed_group_id", groupid);
        cv.put("bandisabled", 0);
        cv.put("clean_subject", clean_subject);
        dbwrite.insert("banned_threads", null, cv);
    }

    // Mark all the messages from the thread as read so they get cleaned later
    dbwrite.execSQL("UPDATE headers SET read=1, read_unixdate=" + System.currentTimeMillis()
            + " WHERE subscribed_group_id=" + groupid + " AND clean_subject=" + esc(clean_subject));

    c.close();
    dbwrite.close();
    db.close();
}