Example usage for android.database.sqlite SQLiteDatabase beginTransaction

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

Introduction

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

Prototype

public void beginTransaction() 

Source Link

Document

Begins a transaction in EXCLUSIVE mode.

Usage

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

private boolean importDict(InputStream is) {
    boolean success = false;
    SQLiteDatabase db = getWritableDatabase();
    db.beginTransaction();
    try {/*from w w  w .  j  a  v  a  2 s  .  c om*/
        String line;
        StringBuilder content = new StringBuilder();
        InputStreamReader ir = new InputStreamReader(is);
        BufferedReader br = new BufferedReader(ir);
        while ((line = br.readLine()) != null && !line.contentEquals(fs)) {
            content.append(line);
            content.append(newline);
        }

        Yaml yaml = new Yaml();
        Map<String, Object> y = (Map<String, Object>) (yaml.load(content.toString()));
        String table = (String) y.get("name");

        db.execSQL("DROP TABLE IF EXISTS " + table);
        db.execSQL(String.format("CREATE VIRTUAL TABLE %s USING fts3(hz, py)", table));

        ContentValues initialValues = new ContentValues(2);
        int max = is.available();
        int progress = 0;
        int count = 0;
        while ((line = br.readLine()) != null) {
            if (line.startsWith(comment))
                continue;
            String[] s = line.split("\t");
            if (s.length < 2)
                continue;
            initialValues.put("hz", s[0]);
            initialValues.put("py", s[1]);
            db.insert(table, null, initialValues);
            initialValues.clear();
            count++;
            if ((count % 1000) == 0) {
                progress = max - is.available();
                mBuilder.setProgress(max, progress, false)
                        .setContentText(String.format("%d / 100", progress * 100 / max));
                mNotifyManager.notify(notify_id, mBuilder.build());
            }
        }
        is.close();
        db.setTransactionSuccessful();
        success = true;
    } catch (Exception e) {
        throw new RuntimeException("Error import dict", e);
    } finally {
        db.endTransaction();
        mNotifyManager.cancel(notify_id);
    }
    return success;
}

From source file:ch.sebastienzurfluh.swissmuseumguides.contentprovider.model.io.connectors.LocalConnector.java

@Override
public void addAll(final Affiliations affiliations) {
    new Thread() {
        @Override/* ww  w .j  ava 2s . c om*/
        public void run() {
            SQLiteDatabase writableDatabase = getWritableDatabase();

            writableDatabase.beginTransaction();
            try {
                for (Affiliation affiliation : affiliations) {
                    String query = "INSERT OR REPLACE INTO " + affiliations.getTableName() + " VALUES (\""
                            + affiliation.getId() + "\", \"" + affiliation.getPageId() + "\", \""
                            + affiliation.getGroupId() + "\", " + affiliation.getOrder() + ");";
                    getWritableDatabase().execSQL(query);
                }
                writableDatabase.setTransactionSuccessful();
            } catch (JSONException e) {
                System.out.println("Malformed json in affiliations");
                e.printStackTrace();
            } finally {
                writableDatabase.endTransaction();
            }
        }
    }.start();
}

From source file:ch.sebastienzurfluh.swissmuseumguides.contentprovider.model.io.connectors.LocalConnector.java

@Override
public void addAll(final Groups groups) {
    new Thread() {
        @Override/*from  ww w .j a v a  2s.c o  m*/
        public void run() {
            SQLiteDatabase writableDatabase = getWritableDatabase();

            writableDatabase.beginTransaction();
            try {
                for (Group group : groups) {
                    String query = "INSERT OR REPLACE INTO " + groups.getTableName() + " VALUES (\""
                            + group.getId() + "\", \"" + group.getName() + "\", \"" + group.getMenuId()
                            + "\");";
                    getWritableDatabase().execSQL(query);
                }
                writableDatabase.setTransactionSuccessful();
            } catch (JSONException e) {
                System.out.println("Malformed json in groups");
                e.printStackTrace();
            } finally {
                writableDatabase.endTransaction();
            }
        }
    }.start();
}

From source file:ch.sebastienzurfluh.swissmuseumguides.contentprovider.model.io.connectors.LocalConnector.java

@Override
public void addAll(final Menus menus) {
    new Thread() {
        @Override/*from w w w . ja  va 2s. c  o m*/
        public void run() {
            SQLiteDatabase writableDatabase = getWritableDatabase();

            writableDatabase.beginTransaction();
            try {
                for (Menu menu : menus) {
                    String query = "INSERT OR REPLACE INTO " + menus.getTableName() + " VALUES (\""
                            + menu.getId() + "\", \"" + menu.getTitle() + "\", \"" + menu.getDescription()
                            + "\", \"" + menu.getThumbImgURL() + "\", \"" + menu.getImgURL() + "\");";
                    getWritableDatabase().execSQL(query);
                }
                writableDatabase.setTransactionSuccessful();
            } catch (JSONException e) {
                System.out.println("Malformed json in menus");
                e.printStackTrace();
            } finally {
                writableDatabase.endTransaction();
            }
        }
    }.start();
}

From source file:ch.sebastienzurfluh.swissmuseumguides.contentprovider.model.io.connectors.LocalConnector.java

@Override
public void addAll(final Pages pages) {
    new Thread() {
        @Override//w w  w .  jav a  2 s  . c  o  m
        public void run() {
            SQLiteDatabase writableDatabase = getWritableDatabase();

            writableDatabase.beginTransaction();
            try {
                for (Page page : pages) {
                    String query = "INSERT OR REPLACE INTO " + pages.getTableName() + " VALUES (\""
                            + page.getId() + "\", \"" + page.getTitle() + "\", \"" + page.getSubtitle()
                            + "\", \"" + page.getContent() + "\", \"" + page.getMenuId() + "\");";
                    getWritableDatabase().execSQL(query);
                }
                writableDatabase.setTransactionSuccessful();
            } catch (JSONException e) {
                System.out.println("Malformed json in pages");
                e.printStackTrace();
            } finally {
                writableDatabase.endTransaction();
            }
        }
    }.start();
}

From source file:ch.sebastienzurfluh.swissmuseumguides.contentprovider.model.io.connectors.LocalConnector.java

@Override
public void addAll(final Resources resources) {
    new Thread() {
        @Override//from  w w w .java  2s .  c o  m
        public void run() {
            SQLiteDatabase writableDatabase = getWritableDatabase();

            writableDatabase.beginTransaction();
            try {
                for (Resource resource : resources) {
                    String query = "INSERT OR REPLACE INTO " + resources.getTableName() + " VALUES (\""
                            + resource.getId() + "\", \"" + resource.getTitle() + "\", \"" + resource.getURL()
                            + "\", \"" + resource.getDescription() + "\", \"" + resource.getType() + "\");";
                    getWritableDatabase().execSQL(query);
                }
                writableDatabase.setTransactionSuccessful();
            } catch (JSONException e) {
                System.out.println("Malformed json in resources");
                e.printStackTrace();
            } finally {
                writableDatabase.endTransaction();
            }
        }
    }.start();
}

From source file:net.willwebberley.gowertides.utils.WeatherDatabase.java

public Boolean insertAllData(String data) {
    JSONObject jsonArray = null;// w  ww  .  j a  va2  s  .  c  o m
    JSONArray weatherArray = null;
    JSONArray surfArray = null;

    try {
        jsonArray = new JSONObject(data);
        weatherArray = jsonArray.getJSONArray("weather");
        surfArray = jsonArray.getJSONArray("surf");
    } catch (Exception e) {
        System.err.println("couldn't parse JSON");
        return false;
    }

    SQLiteDatabase db = this.getWritableDatabase();
    int err_count = 0;

    /* Insert weather data */
    db.beginTransaction();
    Boolean weatherSuccess = insertWeatherData(weatherArray.toString(), db);
    if (!weatherSuccess) {
        err_count++;
        System.err.println("Error storing weather");
        db.endTransaction();
    } else {
        db.setTransactionSuccessful();
        db.endTransaction();
    }

    /* Insert surf data - using transactions to help performance */
    db.beginTransaction();
    Boolean surfSuccess = insertSurfData(surfArray.toString(), db);
    if (!surfSuccess) {
        err_count++;
        System.err.println("Error storing surf");
        db.endTransaction();
    } else {
        db.setTransactionSuccessful();
        db.endTransaction();
    }

    if (err_count > 0) {
        db.endTransaction();
        return false;
    }

    return true;
}

From source file:github.popeen.dsub.util.SongDBHandler.java

protected synchronized void addSongsImpl(SQLiteDatabase db, int serverKey, List<Pair<String, String>> entries) {
    db.beginTransaction();
    try {/* w  w  w. j a  va2 s  .c om*/
        for (Pair<String, String> entry : entries) {
            ContentValues values = new ContentValues();
            values.put(SONGS_SERVER_KEY, serverKey);
            values.put(SONGS_SERVER_ID, entry.getFirst());
            values.put(SONGS_COMPLETE_PATH, entry.getSecond());

            db.insertWithOnConflict(TABLE_SONGS, null, values, SQLiteDatabase.CONFLICT_IGNORE);
        }

        db.setTransactionSuccessful();
    } catch (Exception e) {
    }

    db.endTransaction();
}

From source file:com.cloudmine.api.db.RequestDBOpenHelper.java

public void insertRequest(ContentValues requestValues, ContentValues[] headerValues) {
    SQLiteDatabase db = getWritableDatabase();
    db.beginTransaction();
    try {// ww  w .ja  v  a  2  s . c om
        long requestId = db.insertOrThrow(REQUEST_DATABASE_TABLE, null, requestValues);
        throwIfFailed(requestId);
        for (ContentValues headerValue : headerValues) {
            headerValue.put(KEY_HEADER_REQUEST_FK, requestId);
            long result = db.insertOrThrow(HEADER_DATABASE_TABLE, null, headerValue);
            throwIfFailed(result);
        }
        db.setTransactionSuccessful();
    } finally {
        db.endTransaction();
    }
}

From source file:com.cloudmine.api.db.RequestDBOpenHelper.java

/**
 * Load all of the unsynced requests, and set their status to in progress.
 * @return// www  .  ja v a 2s . c o  m
 */
private Cursor loadRequestTableContentsForUpdating() {
    SQLiteDatabase db = getWritableDatabase();
    db.beginTransaction();
    try {
        String[] unsychronizedSelectionArgs = { UNSYCHRONIZED.toString() };
        Cursor cursor = db.query(BOTH_DATABASE_TABLE_JOIN, RESULTS_COLUMNS, SYNCHRONIZED_VALUE_WHERE,
                unsychronizedSelectionArgs, null, null, requestColumn(KEY_REQUEST_ID));
        cursor.getCount(); //For some reason, accessing the cursor count before performing the update is required for the load to work. Doesn't make much sense unless it is ignoring order.
        ContentValues updatedValues = getUpdateSynchronizedContentValues(IN_PROGRESS);
        db.update(REQUEST_DATABASE_TABLE, updatedValues, SYNCHRONIZED_VALUE_WHERE, unsychronizedSelectionArgs);

        db.setTransactionSuccessful();

        return cursor;
    } catch (Throwable t) {
        throw new RuntimeException(t);
    } finally {
        db.endTransaction();
    }
}