Example usage for android.database.sqlite SQLiteDatabase execSQL

List of usage examples for android.database.sqlite SQLiteDatabase execSQL

Introduction

In this page you can find the example usage for android.database.sqlite SQLiteDatabase execSQL.

Prototype

public void execSQL(String sql) throws SQLException 

Source Link

Document

Execute a single SQL statement that is NOT a SELECT or any other SQL statement that returns data.

Usage

From source file:com.shalzz.attendance.DatabaseHandler.java

/**
 * Drop the table if it exist and create a new table.
 *///from  ww  w  . ja v a  2s.c o  m
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    switch (oldVersion) {
    case 1:
    case 2:
    case 3:
    case 4:
    case 5:
    case 6:
    case 7:
    case 8:

        // Drop older table if existed
        db.execSQL("DROP TABLE IF EXISTS " + Subject.TABLE_NAME);
        db.execSQL("DROP TABLE IF EXISTS " + Period.TABLE_NAME);
        db.execSQL("DROP TABLE IF EXISTS " + User.TABLE_NAME);
        db.execSQL("DROP TABLE IF EXISTS " + AbsentDate.TABLE_NAME);

        // Create tables again
        onCreate(db);
        break;
    }
}

From source file:com.google.samples.apps.topeka.persistence.TopekaDatabaseHelper.java

@Override
public void onCreate(SQLiteDatabase db) {
    /*//from   w  ww  . ja  v  a  2  s  . c om
     * create the category table first, as quiz table has a foreign key
     * constraint on category id
     */
    db.execSQL(CategoryTable.CREATE);
    db.execSQL(QuizTable.CREATE);
    preFillDatabase(db);
}

From source file:be.benvd.mvforandroid.data.DatabaseHelper.java

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    switch (oldVersion) {
    case 1://from  w  w w.  j a  va 2s.  c  om
        if (newVersion < 2) {
            return;
        }
        // add the column for super-on-net sms's
        db.execSQL("ALTER TABLE " + Credit.TABLE_NAME + " ADD COLUMN sms_son INTEGER NOT NULL DEFAULT 0;");
    }
}

From source file:com.example.petri.myapplication.GCMMessageListenerService.java

/**
 * Called when message is received.//ww w.  j a  v a  2  s. c  om
 *
 * @param from SenderID of the sender.
 * @param data Data bundle containing message data as key/value pairs.
 *             For Set of keys use data.keySet().
 */
// [START receive_message]
@Override
public void onMessageReceived(String from, Bundle data) {
    String message = data.getString("message");
    int from_id = Integer.parseInt(data.getString("from_id"));
    int to_id = Integer.parseInt(data.getString("to_id"));
    Log.d(TAG, "From: " + from);
    Log.d(TAG, "Message: " + message);
    DatabaseHelper helper = new DatabaseHelper(this);
    SQLiteDatabase db = helper.getWritableDatabase();

    ContentValues values = new ContentValues();
    values.put("message", message);
    values.put("from_id", from_id);
    values.put("to_id", to_id);

    // Insert the new row, returning the primary key value of the new row
    long newRowId;
    newRowId = db.insert("messages", "message_id", values);
    String strSQL = "UPDATE chats SET last_activity = CURRENT_TIMESTAMP WHERE user_id = " + from_id;
    db.execSQL(strSQL);

    //        SQLiteDatabase dbr = helper.getReadableDatabase();

    //        Cursor cursor = dbr.query(false, "messages", new String[]{"message"}, null, null, null, null, null, null);
    //        cursor.moveToLast();
    //        String this_message = cursor.getString(
    //                cursor.getColumnIndexOrThrow("message")
    //        );
    //        Log.d("mygcm", this_message);

    Intent broadcastIntent = new Intent();
    broadcastIntent.setAction(ChatActivity.MessageResponseReceiver.ACTION_RESP);
    broadcastIntent.addCategory(Intent.CATEGORY_DEFAULT);
    broadcastIntent.putExtra("from_id", from_id);
    LocalBroadcastManager.getInstance(this).sendBroadcast(broadcastIntent);

    //        SQLiteDatabase mydatabase =
    //        mydatabase.execSQL("CREATE TABLE IF NOT EXISTS messages(message_id INT auto_increment, message TEXT, primary key(message_id));");
    //        mydatabase.execSQL("INSERT INTO TutorialsPoint VALUES('null','" + message + "');");
    /**
     * Production applications would usually process the message here.
     * Eg: - Syncing with server.
     *     - Store message in local database.
     *     - Update UI.
     */

    /**
     * In some cases it may be useful to show a notification indicating to the user
     * that a message was received.
     */
    sendNotification(message, from_id);
}

From source file:android.database.DatabaseUtils.java

/**
 * Creates a db and populates it with the sql statements in sqlStatements.
 *
 * @param context the context to use to create the db
 * @param dbName the name of the db to create
 * @param dbVersion the version to set on the db
 * @param sqlStatements the statements to use to populate the db. This should be a single string
 *   of the form returned by sqlite3's <tt>.dump</tt> command (statements separated by
 *   semicolons)/*from w w  w .jav  a 2  s  .  co  m*/
 */
static public void createDbFromSqlStatements(Context context, String dbName, int dbVersion,
        String sqlStatements) {
    SQLiteDatabase db = context.openOrCreateDatabase(dbName, 0, null);
    // TODO: this is not quite safe since it assumes that all semicolons at the end of a line
    // terminate statements. It is possible that a text field contains ;\n. We will have to fix
    // this if that turns out to be a problem.
    String[] statements = TextUtils.split(sqlStatements, ";\n");
    for (String statement : statements) {
        if (TextUtils.isEmpty(statement))
            continue;
        db.execSQL(statement);
    }
    db.setVersion(dbVersion);
    db.close();
}

From source file:uk.org.rivernile.edinburghbustracker.android.SettingsDatabase.java

/**
 * This is called when the DB does not exist.
 *
 * @param db The database object to interface with.
 */// w w w . j  a  v  a 2  s .c o  m
@Override
public void onCreate(final SQLiteDatabase db) {
    // This is what happens when the application cannot find a database
    // with the database name.
    db.execSQL("CREATE TABLE " + FAVOURITE_STOPS_TABLE + " (" + FAVOURITE_STOPS_STOPCODE + " TEXT PRIMARY KEY,"
            + FAVOURITE_STOPS_STOPNAME + " TEXT NOT NULL);");
    db.execSQL("CREATE TABLE " + ALERTS_TABLE + " (" + ALERTS_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
            + ALERTS_TYPE + " NUMERIC NOT NULL," + ALERTS_TIME_ADDED + " INTEGER NOT NULL," + ALERTS_STOPCODE
            + " TEXT NOT NULL," + ALERTS_DISTANCE_FROM + " INTEGER," + ALERTS_SERVICE_NAMES + " TEXT,"
            + ALERTS_TIME_TRIGGER + " INTEGER);");
}

From source file:me.jreilly.JamesTweet.Adapters.TweetDataHelper.java

@Override
public void onCreate(SQLiteDatabase db) {
    DATABASE_CREATE = "CREATE TABLE " + TIMELINE_TABLE_NAME + " (" + HOME_COL
            + " INTEGER PRIMARY KEY AUTOINCREMENT, " + UPDATE_COL + " TEXT, " + NAME_COL + " Text, " + USER_COL
            + " TEXT, " + TIME_COL + " INTEGER, " + USER_IMG + " TEXT, " + MEDIA_COL + " TEXT, " + FAVORITE_COL
            + " INTEGER, " + RETWEET_COL + " INTEGER, " + RETWEETED_COL + " INTEGER, " + ORIGINAL_COL
            + " TEXT);";
    db.execSQL(DATABASE_CREATE);
    DATABASE_CREATE = "CREATE TABLE " + TABLE_QUEUE_NAME + " (" + HOME_COL
            + " INTEGER PRIMARY KEY AUTOINCREMENT, " + UPDATE_COL + " TEXT, " + NAME_COL + " Text, " + USER_COL
            + " TEXT, " + TIME_COL + " INTEGER, " + USER_IMG + " TEXT, " + MEDIA_COL + " TEXT, " + FAVORITE_COL
            + " INTEGER, " + RETWEET_COL + " INTEGER, " + RETWEETED_COL + " INTEGER, " + ORIGINAL_COL
            + " TEXT);";
    db.execSQL(DATABASE_CREATE);//from  w w w . ja  v  a 2s. co m
}

From source file:com.concentricsky.android.khanacademy.data.remote.LibraryUpdaterTask.java

@Override
protected Integer doInBackground(Void... params) {

    SharedPreferences prefs = dataService.getSharedPreferences(SETTINGS_NAME, Context.MODE_PRIVATE);

    // Connectivity receiver.
    final NetworkInfo activeNetwork = connectivityManager.getActiveNetworkInfo();
    ComponentName receiver = new ComponentName(dataService, WifiReceiver.class);
    PackageManager pm = dataService.getPackageManager();
    if (activeNetwork == null || !activeNetwork.isConnected()) {
        // We've missed a scheduled update. Enable the receiver so it can launch an update when we reconnect.
        Log.d(LOG_TAG, "Missed library update: not connected. Enabling connectivity receiver.");
        pm.setComponentEnabledSetting(receiver, PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
                PackageManager.DONT_KILL_APP);
        return RESULT_CODE_FAILURE;
    } else {/*ww  w. ja  v  a2s .  c om*/
        // We are connected. Disable the receiver.
        Log.d(LOG_TAG, "Library updater connected. Disabling connectivity receiver.");
        pm.setComponentEnabledSetting(receiver, PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
                PackageManager.DONT_KILL_APP);
    }

    InputStream in = null;
    String etag = prefs.getString(SETTING_LIBRARY_ETAG, null);

    try {
        HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
        if (etag != null && !force) {
            conn.setRequestProperty("If-None-Match", etag);
        }

        int code = conn.getResponseCode();
        switch (code) {
        case HttpStatus.SC_NOT_MODIFIED:
            // If we got a 304, we're done.
            // Use failure code to indicate there is no temp db to copy over.
            Log.d(LOG_TAG, "304 in library response.");
            return RESULT_CODE_FAILURE;
        default:
            // Odd, but on 1/3/13 I received correct json responses with a -1 for responseCode. Fall through.
            Log.w(LOG_TAG, "Error code in library response: " + code);
        case HttpStatus.SC_OK:
            // Parse response.
            in = conn.getInputStream();
            JsonFactory factory = new JsonFactory();
            final JsonParser parser = factory.createJsonParser(in);

            SQLiteDatabase tempDb = tempDbHelper.getWritableDatabase();
            tempDb.beginTransaction();
            try {
                tempDb.execSQL("delete from topic");
                tempDb.execSQL("delete from topicvideo");
                tempDb.execSQL("delete from video");

                parseObject(parser, tempDb, null, 0);
                tempDb.setTransactionSuccessful();
            } catch (Exception e) {
                e.printStackTrace();
                return RESULT_CODE_FAILURE;
            } finally {
                tempDb.endTransaction();
                tempDb.close();
            }

            // Save etag once we've successfully parsed the response.
            etag = conn.getHeaderField("ETag");
            prefs.edit().putString(SETTING_LIBRARY_ETAG, etag).apply();

            // Move this new content from the temp db into the main one.
            mergeDbs();

            return RESULT_CODE_SUCCESS;
        }
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (JsonParseException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        tempDbHelper.close();
    }

    return RESULT_CODE_FAILURE;
}

From source file:com.cyanogenmod.eleven.provider.LocalizedStore.java

public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    // If we ever have downgrade, drop the table to be safe
    db.execSQL("DROP TABLE IF EXISTS " + SongSortColumns.TABLE_NAME);
    db.execSQL("DROP TABLE IF EXISTS " + AlbumSortColumns.TABLE_NAME);
    db.execSQL("DROP TABLE IF EXISTS " + ArtistSortColumns.TABLE_NAME);
    onCreate(db);//  w w w .j ava2  s  .c o  m
}

From source file:com.snt.bt.recon.database.DBHandler.java

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    // Drop older tables if existed
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_TRIPS);
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_LOCATIONS);
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_BC);
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_BLE);

    // Creating tables again
    onCreate(db);/* w  w w . j av  a 2 s .co m*/
}