Example usage for android.database.sqlite SQLiteException getMessage

List of usage examples for android.database.sqlite SQLiteException getMessage

Introduction

In this page you can find the example usage for android.database.sqlite SQLiteException getMessage.

Prototype

public String getMessage() 

Source Link

Document

Returns the detail message string of this throwable.

Usage

From source file:com.zetaDevelopment.phonegap.plugin.sqlitePlugin.SQLitePlugin.java

/**
 * Executes a batch request and sends the results via sendJavascriptCB().
 *
 * @param dbname/*www.j  a  v  a 2s .  c  o m*/
 *            The name of the database.
 *
 * @param queryarr
 *            Array of query strings
 *
 * @param jsonparams
 *            Array of JSON query parameters
 *
 * @param queryIDs
 *            Array of query ids
 *
 * @param tx_id
 *            Transaction id
 *
 */
private void executeSqlBatch(String dbname, String[] queryarr, JSONArray[] jsonparams, String[] queryIDs,
        String tx_id) {
    SQLiteDatabase mydb = this.getDatabase(dbname);

    if (mydb == null)
        return;

    try {
        mydb.beginTransaction();

        String query = "";
        String query_id = "";
        int len = queryarr.length;

        for (int i = 0; i < len; i++) {
            query = queryarr[i];
            query_id = queryIDs[i];
            if (query.toLowerCase(Locale.getDefault()).startsWith("insert") && jsonparams != null) {
                SQLiteStatement myStatement = mydb.compileStatement(query);
                for (int j = 0; j < jsonparams[i].length(); j++) {
                    if (jsonparams[i].get(j) instanceof Float || jsonparams[i].get(j) instanceof Double) {
                        myStatement.bindDouble(j + 1, jsonparams[i].getDouble(j));
                    } else if (jsonparams[i].get(j) instanceof Number) {
                        myStatement.bindLong(j + 1, jsonparams[i].getLong(j));
                    } else {
                        myStatement.bindString(j + 1, jsonparams[i].getString(j));
                    }
                }
                long insertId = myStatement.executeInsert();

                String result = "{'insertId':'" + insertId + "'}";
                this.sendJavascriptCB("window.SQLitePluginTransactionCB.queryCompleteCallback('" + tx_id + "','"
                        + query_id + "', " + result + ");");
            } else {
                String[] params = null;

                if (jsonparams != null) {
                    params = new String[jsonparams[i].length()];

                    for (int j = 0; j < jsonparams[i].length(); j++) {
                        if (jsonparams[i].isNull(j))
                            params[j] = "";
                        else
                            params[j] = jsonparams[i].getString(j);
                    }
                }

                Cursor myCursor = mydb.rawQuery(query, params);

                if (query_id.length() > 0)
                    this.processResults(myCursor, query_id, tx_id);

                myCursor.close();
            }
        }
        mydb.setTransactionSuccessful();
    } catch (SQLiteException ex) {
        ex.printStackTrace();
        Log.v("executeSqlBatch", "SQLitePlugin.executeSql(): Error=" + ex.getMessage());
        this.sendJavascriptCB("window.SQLitePluginTransactionCB.txErrorCallback('" + tx_id + "', '"
                + ex.getMessage() + "');");
    } catch (JSONException ex) {
        ex.printStackTrace();
        Log.v("executeSqlBatch", "SQLitePlugin.executeSql(): Error=" + ex.getMessage());
        this.sendJavascriptCB("window.SQLitePluginTransactionCB.txErrorCallback('" + tx_id + "', '"
                + ex.getMessage() + "');");
    } finally {
        mydb.endTransaction();
        Log.v("executeSqlBatch", tx_id);
        this.sendJavascriptCB("window.SQLitePluginTransactionCB.txCompleteCallback('" + tx_id + "');");
    }
}

From source file:com.uphyca.stetho_realm.Database.java

@ChromeDevtoolsMethod
@SuppressWarnings("unused")
public JsonRpcResult executeSQL(JsonRpcPeer peer, JSONObject params) {
    ExecuteSQLRequest request = this.objectMapper.convertValue(params, ExecuteSQLRequest.class);

    try {//from w ww .j a v  a  2 s.  c  o m
        return realmPeerManager.executeSQL(request.databaseId, request.query,
                new RealmPeerManager.ExecuteResultHandler<ExecuteSQLResponse>() {
                    public ExecuteSQLResponse handleRawQuery() throws SQLiteException {
                        ExecuteSQLResponse response = new ExecuteSQLResponse();
                        response.columnNames = Collections.singletonList("success");
                        response.values = Collections.<Object>singletonList("true");
                        return response;
                    }

                    public ExecuteSQLResponse handleSelect(Table table, boolean addRowIndex)
                            throws SQLiteException {
                        ExecuteSQLResponse response = new ExecuteSQLResponse();

                        final ArrayList<String> columnNames = new ArrayList<>();
                        if (addRowIndex) {
                            columnNames.add("<index>");
                        }
                        for (int i = 0; i < table.getColumnCount(); i++) {
                            columnNames.add(table.getColumnName(i));
                        }

                        response.columnNames = columnNames;
                        response.values = flattenRows(table, MAX_EXECUTE_RESULTS, addRowIndex);
                        return response;
                    }

                    public ExecuteSQLResponse handleInsert(long insertedId) throws SQLiteException {
                        ExecuteSQLResponse response = new ExecuteSQLResponse();
                        response.columnNames = Collections.singletonList("ID of last inserted row");
                        response.values = Collections.<Object>singletonList(insertedId);
                        return response;
                    }

                    public ExecuteSQLResponse handleUpdateDelete(int count) throws SQLiteException {
                        ExecuteSQLResponse response = new ExecuteSQLResponse();
                        response.columnNames = Collections.singletonList("Modified rows");
                        response.values = Collections.<Object>singletonList(count);
                        return response;
                    }
                });
    } catch (SQLiteException e) {
        Error error = new Error();
        error.code = 0;
        error.message = e.getMessage();
        ExecuteSQLResponse response = new ExecuteSQLResponse();
        response.sqlError = error;
        return response;
    }
}

From source file:com.aquatest.dbinterface.tools.DatabaseUpdater.java

/**
 * Run the updater to synchronise the device with the server. </p> Method
 * cycles through all the database tables, and for each one, it retrieves
 * records that have been added, changed or deleted.
 *///from ww  w .j  av  a 2s .c o  m
public void run() {
    try {
        long updateTime = System.currentTimeMillis();
        boolean result;

        Vector<String> tables = getTables();
        sendMessage("Table list downloaded: " + tables.size() + " tables found.", ITEM_COMPLETE);

        // begin database transaction
        dA.database.beginTransaction();

        try {

            // loop through all the tables
            int tableCount = tables.size();
            for (int i = 0; i < tableCount; i++) {
                String tableName = tables.get(i);
                int k = i + 1;

                // ignore authoritymanager table
                if (tableName.compareTo("authoritymanager") == 0) {
                    continue;
                } // if

                // retrieve ADDED rows
                sendMessage(tableName + " (table " + k + "/" + tableCount + "): retrieving new records...",
                        ITEM_COMPLETE);
                result = fetchAndExecuteQueries(TYPE_ADDED, tableName);

                if (!result) {
                    // Log.v("THREAD", "KILLING");
                    sendMessage("Update cancelled!", CANCELLED);
                    return;
                } // if

                // retrieve UPDATED rows
                sendMessage(tableName + " (table " + k + "/" + tableCount + "): retrieving updated records...",
                        ITEM_COMPLETE);
                result = fetchAndExecuteQueries(TYPE_UPDATED, tableName);

                if (!result) {
                    // Log.v("THREAD", "KILLING");
                    sendMessage("Update cancelled!", CANCELLED);
                    return;
                } // if

                // retrieve DELETED rows
                sendMessage(tableName + " (table " + k + "/" + tableCount + "): retrieving deleted rows...",
                        ITEM_COMPLETE);
                result = fetchAndExecuteQueries(TYPE_DELETED, tableName);

                if (!result) {
                    // Log.v("THREAD", "KILLING");
                    sendMessage("Update cancelled!", CANCELLED);
                    return;
                } // if
            } // for

            // signal transaction can be committed
            dA.database.setTransactionSuccessful();
        } finally {
            // commit or rollback transaction
            dA.database.endTransaction();

        }

        // return success in a Bundle
        Bundle b = new Bundle();
        b.putString("msg", "Update complete!");
        b.putLong("time", updateTime);
        sendMessage(b, COMPLETE);

    } catch (JSONException jE) {
        sendMessage(jE.getMessage(), ERROR);
        return;
    } catch (ClientProtocolException cE) {
        sendMessage(cE.getMessage() + " This is possibly caused by a lack of connectivity. "
                + "Restart the app and try again after ensuring you have a valid connection.", ERROR);
        return;
    } catch (IOException iE) {
        sendMessage(iE.getMessage() + " This is possibly caused by a lack of connectivity. "
                + "Restart the app and try again after ensuring you have a valid connection.", ERROR);
        return;
    } catch (SQLiteException sE) {
        sendMessage("A SQLite exception occured: " + sE.getMessage(), ERROR);
        return;
    } // catch
}

From source file:org.ciasaboark.tacere.database.DatabaseInterface.java

public EventInstance getEvent(long instanceId) throws NoSuchEventInstanceException {
    String whereClause = Columns._ID + " = ?";
    String[] whereArgs = new String[] { String.valueOf(instanceId) };
    EventInstance thisEvent = null;// w w  w  .j  a  v a  2 s  .com
    Cursor cursor = null;
    try {
        cursor = eventsDB.query(EventDatabaseOpenHelper.TABLE_EVENTS, LOCAL_DB_PROJECTION, whereClause,
                whereArgs, null, null, null);

        if (cursor.moveToFirst()) {
            do {
                int id = cursor.getInt(cursor.getColumnIndex(Columns._ID));
                if (id == instanceId) {
                    long cal_id = cursor.getInt(cursor.getColumnIndex(Columns.CAL_ID));
                    int event_id = cursor.getInt(cursor.getColumnIndex(Columns.EVENT_ID));
                    String title = cursor.getString(cursor.getColumnIndex(Columns.TITLE));
                    long begin = cursor.getLong(cursor.getColumnIndex(Columns.BEGIN));
                    long originalEnd = cursor.getLong(cursor.getColumnIndex(Columns.ORGINAL_END));
                    String description = cursor.getString(cursor.getColumnIndex(Columns.DESCRIPTION));
                    int ringerInt = cursor.getInt(cursor.getColumnIndex(Columns.RINGER_TYPE));
                    int displayColor = cursor.getInt(cursor.getColumnIndex(Columns.DISPLAY_COLOR));
                    boolean isFreeTime = cursor.getInt(cursor.getColumnIndex(Columns.IS_FREETIME)) == 1;
                    boolean isAllDay = cursor.getInt(cursor.getColumnIndex(Columns.IS_ALLDAY)) == 1;
                    String location = cursor.getString(cursor.getColumnIndex(Columns.LOCATION));
                    int extendBuffer = cursor.getInt(cursor.getColumnIndex(Columns.EXTEND_BUFFER));

                    thisEvent = new EventInstance(cal_id, id, event_id, title, begin, originalEnd, description,
                            displayColor, isFreeTime, isAllDay, extendBuffer);
                    RingerType ringerType = RingerType.getTypeForInt(ringerInt);
                    thisEvent.setRingerType(ringerType);
                    thisEvent.setLocation(location);

                    break;
                }
            } while (cursor.moveToNext());
        }
    } catch (SQLiteException e) {
        Log.e(TAG, "caught SQLiteException while trying to get local database cursor: " + e.getMessage());
        Log.w(TAG, "sending ARCA bug report");
        ACRA.getErrorReporter().handleSilentException(null);
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }

    if (thisEvent == null) {
        throw new NoSuchEventInstanceException(TAG + " can not find event with given id " + instanceId);
    }
    return thisEvent;
}

From source file:com.aware.Aware.java

/**
 * Insert / Update settings of the framework
 * @param key/*from   w  ww .  j  a v a2  s  .  c om*/
 * @param value
 */
public static void setSetting(Context context, String key, Object value) {

    boolean is_restricted_package = true;

    ArrayList<String> global_settings = new ArrayList<String>();
    global_settings.add("debug_flag");
    global_settings.add("debug_tag");
    global_settings.add("study_id");
    global_settings.add("study_start");

    if (global_settings.contains(key)) {
        is_restricted_package = false;
    }

    //Only AWARE client can change the device ID if needed
    if (key.equals("device_id") && !context.getPackageName().equals("com.aware")) {
        return;
    }

    ContentValues setting = new ContentValues();
    setting.put(Aware_Settings.SETTING_KEY, key);
    setting.put(Aware_Settings.SETTING_VALUE, value.toString());
    setting.put(Aware_Settings.SETTING_PACKAGE_NAME, context.getPackageName());

    Cursor qry = context.getContentResolver().query(Aware_Settings.CONTENT_URI, null, Aware_Settings.SETTING_KEY
            + " LIKE '" + key + "'"
            + (is_restricted_package
                    ? " AND " + Aware_Settings.SETTING_PACKAGE_NAME + " LIKE '" + context.getPackageName() + "'"
                    : ""),
            null, null);
    //update
    if (qry != null && qry.moveToFirst()) {
        try {
            if (!qry.getString(qry.getColumnIndex(Aware_Settings.SETTING_VALUE)).equals(value.toString())) {
                context.getContentResolver().update(Aware_Settings.CONTENT_URI, setting,
                        Aware_Settings.SETTING_ID + "="
                                + qry.getInt(qry.getColumnIndex(Aware_Settings.SETTING_ID)),
                        null);
                if (Aware.DEBUG)
                    Log.d(Aware.TAG, "Updated: " + key + "=" + value);
            }
        } catch (SQLiteException e) {
            if (Aware.DEBUG)
                Log.d(TAG, e.getMessage());
        } catch (SQLException e) {
            if (Aware.DEBUG)
                Log.d(TAG, e.getMessage());
        }
        //insert
    } else {
        try {
            context.getContentResolver().insert(Aware_Settings.CONTENT_URI, setting);
            if (Aware.DEBUG)
                Log.d(Aware.TAG, "Added: " + key + "=" + value);
        } catch (SQLiteException e) {
            if (Aware.DEBUG)
                Log.d(TAG, e.getMessage());
        } catch (SQLException e) {
            if (Aware.DEBUG)
                Log.d(TAG, e.getMessage());
        }
    }
    if (qry != null && !qry.isClosed())
        qry.close();
}

From source file:io.github.gjyaiya.stetho.realm.Database.java

@ChromeDevtoolsMethod
@SuppressWarnings("unused")
public JsonRpcResult executeSQL(JsonRpcPeer peer, JSONObject params) {
    ExecuteSQLRequest request = this.objectMapper.convertValue(params, ExecuteSQLRequest.class);

    try {//from  w ww .ja v  a2  s. co m
        return realmPeerManager.executeSQL(request.databaseId, request.query,
                new RealmPeerManager.ExecuteResultHandler<ExecuteSQLResponse>() {
                    public ExecuteSQLResponse handleRawQuery() throws SQLiteException {
                        ExecuteSQLResponse response = new ExecuteSQLResponse();
                        response.columnNames = Collections.singletonList("success");
                        response.values = Collections.<Object>singletonList("true");
                        return response;
                    }

                    public ExecuteSQLResponse handleSelect(Table table, boolean addRowIndex)
                            throws SQLiteException {
                        ExecuteSQLResponse response = new ExecuteSQLResponse();

                        final ArrayList<String> columnNames = new ArrayList<>();
                        if (addRowIndex) {
                            columnNames.add("<index>");
                        }
                        for (int i = 0; i < table.getColumnCount(); i++) {
                            columnNames.add(table.getColumnName(i));
                        }

                        response.columnNames = columnNames;
                        response.values = flattenRows(table, limit, addRowIndex);
                        return response;
                    }

                    public ExecuteSQLResponse handleInsert(long insertedId) throws SQLiteException {
                        ExecuteSQLResponse response = new ExecuteSQLResponse();
                        response.columnNames = Collections.singletonList("ID of last inserted row");
                        response.values = Collections.<Object>singletonList(insertedId);
                        return response;
                    }

                    public ExecuteSQLResponse handleUpdateDelete(int count) throws SQLiteException {
                        ExecuteSQLResponse response = new ExecuteSQLResponse();
                        response.columnNames = Collections.singletonList("Modified rows");
                        response.values = Collections.<Object>singletonList(count);
                        return response;
                    }
                });
    } catch (SQLiteException e) {
        Error error = new Error();
        error.code = 0;
        error.message = e.getMessage();
        ExecuteSQLResponse response = new ExecuteSQLResponse();
        response.sqlError = error;
        return response;
    }
}

From source file:com.balakrish.gpstracker.WaypointsListActivity.java

/**
 * Imports waypoints from gpx file/*  w  w  w .  j av  a  2  s. co m*/
 */
protected void importFromXMLFile() {

    File importFolder = new File(app.getAppDir() + "/" + Constants.PATH_WAYPOINTS);

    final String importFiles[] = importFolder.list();

    if (importFiles == null || importFiles.length == 0) {
        Toast.makeText(WaypointsListActivity.this, "Import folder is empty", Toast.LENGTH_SHORT).show();
        return;
    }

    // first file is preselected
    // TODO: remove class variable
    importWaypointsFileName = importFiles[0];

    AlertDialog.Builder builder = new AlertDialog.Builder(this);

    builder.setSingleChoiceItems(importFiles, 0, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int whichButton) {
            importWaypointsFileName = importFiles[whichButton];
        }
    })

            .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int id) {

                    try {

                        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
                        DocumentBuilder db = dbf.newDocumentBuilder();
                        File file = new File(app.getAppDir() + "/" + Constants.PATH_WAYPOINTS,
                                importWaypointsFileName);

                        Document doc = db.parse(file);
                        doc.getDocumentElement().normalize();

                        NodeList waypointsList = doc.getElementsByTagName("wpt");

                        boolean updateRequired = false;

                        for (int i = 0; i < waypointsList.getLength(); i++) {

                            Waypoint wp = new Waypoint();

                            wp.setLat(
                                    Double.parseDouble(((Element) waypointsList.item(i)).getAttribute("lat")));
                            wp.setLng(
                                    Double.parseDouble(((Element) waypointsList.item(i)).getAttribute("lon")));

                            Node item = waypointsList.item(i);

                            NodeList properties = item.getChildNodes();
                            for (int j = 0; j < properties.getLength(); j++) {

                                Node property = properties.item(j);
                                String name = property.getNodeName();

                                if (name.equalsIgnoreCase("ELE") && property.getFirstChild() != null) {
                                    wp.setElevation(
                                            Double.parseDouble(property.getFirstChild().getNodeValue()));
                                }
                                if (name.equalsIgnoreCase("TIME") && property.getFirstChild() != null) {
                                    wp.setTime((new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'"))
                                            .parse(property.getFirstChild().getNodeValue()).getTime());
                                }
                                if (name.equalsIgnoreCase("NAME") && property.getFirstChild() != null) {
                                    wp.setTitle(property.getFirstChild().getNodeValue());
                                }

                                if (name.equalsIgnoreCase("DESC") && property.getFirstChild() != null) {
                                    wp.setDescr(property.getFirstChild().getNodeValue());
                                }

                            }

                            // adding imported waypoint to db
                            if (!inWaypointsArray(wp.getTitle())) {

                                try {

                                    Waypoints.insert(app.getDatabase(), wp);

                                    // if at least one record added, update waypoints list
                                    updateRequired = true;

                                } catch (SQLiteException e) {
                                    Log.e(Constants.TAG, "SQLiteException: " + e.getMessage(), e);
                                }

                            }

                        }

                        if (updateRequired) {
                            updateWaypointsArray();
                            waypointsArrayAdapter.setItems(waypoints);
                            waypointsArrayAdapter.notifyDataSetChanged();
                        }

                        Toast.makeText(WaypointsListActivity.this, R.string.import_completed,
                                Toast.LENGTH_SHORT).show();

                    } catch (IOException e) {
                        AppLog.e(WaypointsListActivity.this, e.getMessage());
                    } catch (ParserConfigurationException e) {
                        AppLog.e(WaypointsListActivity.this, e.getMessage());
                    } catch (ParseException e) {
                        AppLog.e(WaypointsListActivity.this, e.getMessage());
                    } catch (SAXException e) {
                        AppLog.e(WaypointsListActivity.this, e.getMessage());
                    }

                    dialog.dismiss();
                }
            })

            .setTitle(R.string.select_file).setCancelable(true);

    AlertDialog alert = builder.create();

    alert.show();

}

From source file:com.nogago.android.tracks.services.TrackRecordingService.java

/**
 * Inserts a new location in the track points db and updates the corresponding
 * track in the track db.//from   ww w  .j a  v  a2 s  .c  om
 *
 * @param location the location to be inserted
 * @param lastRecordedLocation the last recorded location before this one (or
 *        null if none)
 * @param trackId the id of the track
 * @return true if successful. False if SQLite3 threw an exception.
 */
private boolean insertLocation(Location location, Location lastRecordedLocation, long trackId) {

    // Keep track of length along recorded track (needed when a waypoint is
    // inserted):
    if (LocationUtils.isValidLocation(location)) {
        if (lastValidLocation != null) {
            length += location.distanceTo(lastValidLocation);
        }
        lastValidLocation = location;
    }

    // Insert the new location:
    try {
        Location locationToInsert = location;
        if (sensorManager != null && sensorManager.isEnabled()) {
            SensorDataSet sd = sensorManager.getSensorDataSet();
            if (sd != null && sensorManager.isSensorDataSetValid()) {
                locationToInsert = new MyTracksLocation(location, sd);
            }
        }
        Uri pointUri = providerUtils.insertTrackPoint(locationToInsert, trackId);
        int pointId = Integer.parseInt(pointUri.getLastPathSegment());

        // Update the current track:
        if (lastRecordedLocation != null && lastRecordedLocation.getLatitude() < 90) {
            TripStatistics tripStatistics = statsBuilder.getStatistics();
            tripStatistics.setStopTime(System.currentTimeMillis());

            if (recordingTrack.getStartId() < 0) {
                recordingTrack.setStartId(pointId);
            }
            recordingTrack.setStopId(pointId);
            recordingTrack.setNumberOfPoints(recordingTrack.getNumberOfPoints() + 1);
            recordingTrack.setTripStatistics(tripStatistics);
            providerUtils.updateTrack(recordingTrack);
            updateCurrentWaypoint();
        }
    } catch (SQLiteException e) {
        // Insert failed, most likely because of SqlLite error code 5
        // (SQLite_BUSY). This is expected to happen extremely rarely (if our
        // listener gets invoked twice at about the same time).
        Log.w(TAG, "Caught SQLiteException: " + e.getMessage(), e);
        return false;
    }
    announcementExecutor.update();
    splitExecutor.update();
    return true;
}

From source file:com.aware.Aware.java

private void get_device_info() {
    Cursor awareContextDevice = awareContext.getContentResolver().query(Aware_Device.CONTENT_URI, null, null,
            null, null);//from  www.  j av a  2 s.co m
    if (awareContextDevice == null || !awareContextDevice.moveToFirst()) {
        ContentValues rowData = new ContentValues();
        rowData.put("timestamp", System.currentTimeMillis());
        rowData.put("device_id", Aware.getSetting(awareContext, Aware_Preferences.DEVICE_ID));
        rowData.put("board", Build.BOARD);
        rowData.put("brand", Build.BRAND);
        rowData.put("device", Build.DEVICE);
        rowData.put("build_id", Build.DISPLAY);
        rowData.put("hardware", Build.HARDWARE);
        rowData.put("manufacturer", Build.MANUFACTURER);
        rowData.put("model", Build.MODEL);
        rowData.put("product", Build.PRODUCT);
        rowData.put("serial", Build.SERIAL);
        rowData.put("release", Build.VERSION.RELEASE);
        rowData.put("release_type", Build.TYPE);
        rowData.put("sdk", Build.VERSION.SDK_INT);

        try {
            awareContext.getContentResolver().insert(Aware_Device.CONTENT_URI, rowData);

            Intent deviceData = new Intent(ACTION_AWARE_DEVICE_INFORMATION);
            sendBroadcast(deviceData);

            if (Aware.DEBUG)
                Log.d(TAG, "Device information:" + rowData.toString());

        } catch (SQLiteException e) {
            if (Aware.DEBUG)
                Log.d(TAG, e.getMessage());
        } catch (SQLException e) {
            if (Aware.DEBUG)
                Log.d(TAG, e.getMessage());
        }
    }
    if (awareContextDevice != null && !awareContextDevice.isClosed())
        awareContextDevice.close();
}

From source file:com.ezac.gliderlogs.FlightOverviewActivity.java

@SuppressLint("SimpleDateFormat")
public void GliderLogToCSV(String DB, String device_id) {
    // format date's
    SimpleDateFormat CSV = new SimpleDateFormat("yyyyMMdd_kkss");
    SimpleDateFormat DIR = new SimpleDateFormat("yyyy/MM_dd");
    Date myDate = new Date();
    String TS_DB = CSV.format(myDate);
    String TS_DIR = DIR.format(myDate);
    // to internal sdcard
    File dir = new File(Environment.getExternalStorageDirectory() + "/Download/" + TS_DIR);
    if (!dir.exists() || !dir.isDirectory()) {
        dir.mkdir();/*w ww.  j  a  v  a  2s  .  com*/
    }
    File myFile = new File(Environment.getExternalStorageDirectory() + "/Download/" + TS_DIR + "/"
            + device_id.toUpperCase(Locale.US) + "_" + TS_DB + ".csv");

    try {
        myFile.createNewFile();
        FileOutputStream fOut = new FileOutputStream(myFile);
        OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
        myOutWriter.append(
                "datum;start;landing;duur;soort;registratie;piloot;piloot_id;tweede;tweede_id;instructie;opmerking;methode");
        myOutWriter.append("\n");
        Uri uri = FlightsContentProvider.CONTENT_URI_FLIGHT;
        String[] projection = { GliderLogTables.F_DATE, GliderLogTables.F_STARTED, GliderLogTables.F_LANDED,
                GliderLogTables.F_DURATION, GliderLogTables.F_TYPE, GliderLogTables.F_REGISTRATION,
                GliderLogTables.F_PILOT, GliderLogTables.F_PILOT_ID, GliderLogTables.F_COPILOT,
                GliderLogTables.F_COPILOT_ID, GliderLogTables.F_INSTRUCTION, GliderLogTables.F_NOTES,
                GliderLogTables.F_LAUNCH };
        Cursor cur_go = getContentResolver().query(uri, projection, null, null, null);
        if (cur_go != null) {
            //Log.d(TAG,"cnt " + cursor.getCount());
            try {
                if ((cur_go.getCount()) > 0) {
                    cur_go.moveToFirst();
                    do {
                        myOutWriter.append(cur_go
                                .getString(cur_go.getColumnIndexOrThrow(GliderLogTables.F_DATE)) + ";"
                                + cur_go.getString(cur_go.getColumnIndexOrThrow(GliderLogTables.F_STARTED))
                                + ";" + cur_go.getString(cur_go.getColumnIndexOrThrow(GliderLogTables.F_LANDED))
                                + ";"
                                + cur_go.getString(cur_go.getColumnIndexOrThrow(GliderLogTables.F_DURATION))
                                + ";" + cur_go.getString(cur_go.getColumnIndexOrThrow(GliderLogTables.F_TYPE))
                                + ";"
                                + cur_go.getString(cur_go.getColumnIndexOrThrow(GliderLogTables.F_REGISTRATION))
                                + ";" + cur_go.getString(cur_go.getColumnIndexOrThrow(GliderLogTables.F_PILOT))
                                + ";"
                                + cur_go.getString(cur_go.getColumnIndexOrThrow(GliderLogTables.F_PILOT_ID))
                                + ";"
                                + cur_go.getString(cur_go.getColumnIndexOrThrow(GliderLogTables.F_COPILOT))
                                + ";"
                                + cur_go.getString(cur_go.getColumnIndexOrThrow(GliderLogTables.F_COPILOT_ID))
                                + ";"
                                + cur_go.getString(cur_go.getColumnIndexOrThrow(GliderLogTables.F_INSTRUCTION))
                                + ";" + cur_go.getString(cur_go.getColumnIndexOrThrow(GliderLogTables.F_NOTES))
                                + ";"
                                + cur_go.getString(cur_go.getColumnIndexOrThrow(GliderLogTables.F_LAUNCH)));
                        myOutWriter.append("\n");
                        //   Log.d(TAG,"gld " + cursor
                        //         .getColumnIndexOrThrow(GliderLogTables.F_REGISTRATION));
                    } while (cur_go.moveToNext());
                }
            } finally {
                if (!cur_go.isClosed()) {
                    cur_go.close();
                }
            }
        }
        myOutWriter.close();
        fOut.close();
    } catch (IOException ioe) {
        Log.e(TAG, "Could not open/write the csv file, error: " + ioe.getMessage());
    } catch (SQLiteException e) {
        Log.e(TAG, "SQLiteException:" + e.getMessage());
    } catch (Exception e) {
        Log.e(TAG, "Could not open/read the DB, error: " + e.getMessage());
    }

}