Example usage for android.net Uri withAppendedPath

List of usage examples for android.net Uri withAppendedPath

Introduction

In this page you can find the example usage for android.net Uri withAppendedPath.

Prototype

public static Uri withAppendedPath(Uri baseUri, String pathSegment) 

Source Link

Document

Creates a new Uri by appending an already-encoded path segment to a base Uri.

Usage

From source file:name.gumartinm.weather.information.widget.WidgetIntentService.java

private RemoteViews makeView(final Current current, final WeatherLocation weatherLocation,
        final int appWidgetId) {

    // 1. Update units of measurement.

    UnitsConversor tempUnitsConversor;/*from w  ww  .j ava2s.  co m*/
    String keyPreference = this.getApplicationContext()
            .getString(R.string.widget_preferences_temperature_units_key);
    String realKeyPreference = keyPreference + "_" + appWidgetId;
    // What was saved to permanent storage (or default values if it is the first time)
    final int tempValue = this.getSharedPreferences(WIDGET_PREFERENCES_NAME, Context.MODE_PRIVATE)
            .getInt(realKeyPreference, 0);
    final String tempSymbol = this.getResources()
            .getStringArray(R.array.weather_preferences_temperature)[tempValue];
    if (tempValue == 0) {
        tempUnitsConversor = new UnitsConversor() {

            @Override
            public double doConversion(final double value) {
                return value - 273.15;
            }

        };
    } else if (tempValue == 1) {
        tempUnitsConversor = new UnitsConversor() {

            @Override
            public double doConversion(final double value) {
                return (value * 1.8) - 459.67;
            }

        };
    } else {
        tempUnitsConversor = new UnitsConversor() {

            @Override
            public double doConversion(final double value) {
                return value;
            }

        };
    }

    // 2. Update country.
    keyPreference = this.getApplicationContext().getString(R.string.widget_preferences_country_switch_key);
    realKeyPreference = keyPreference + "_" + appWidgetId;
    // What was saved to permanent storage (or default values if it is the first time)
    final boolean isCountry = this.getSharedPreferences(WIDGET_PREFERENCES_NAME, Context.MODE_PRIVATE)
            .getBoolean(realKeyPreference, false);

    // 3. Formatters
    final DecimalFormat tempFormatter = (DecimalFormat) NumberFormat.getNumberInstance(Locale.US);
    tempFormatter.applyPattern("###.##");

    // 4. Prepare data for RemoteViews.
    String tempMax = "";
    if (current.getMain().getTemp_max() != null) {
        double conversion = (Double) current.getMain().getTemp_max();
        conversion = tempUnitsConversor.doConversion(conversion);
        tempMax = tempFormatter.format(conversion) + tempSymbol;
    }
    String tempMin = "";
    if (current.getMain().getTemp_min() != null) {
        double conversion = (Double) current.getMain().getTemp_min();
        conversion = tempUnitsConversor.doConversion(conversion);
        tempMin = tempFormatter.format(conversion) + tempSymbol;
    }
    Bitmap picture;
    if ((current.getWeather().size() > 0) && (current.getWeather().get(0).getIcon() != null)
            && (IconsList.getIcon(current.getWeather().get(0).getIcon()) != null)) {
        final String icon = current.getWeather().get(0).getIcon();
        picture = BitmapFactory.decodeResource(this.getResources(),
                IconsList.getIcon(icon).getResourceDrawable());
    } else {
        picture = BitmapFactory.decodeResource(this.getResources(), R.drawable.weather_severe_alert);
    }
    final String city = weatherLocation.getCity();
    final String country = weatherLocation.getCountry();

    // 5. Insert data in RemoteViews.
    final RemoteViews remoteView = new RemoteViews(this.getApplicationContext().getPackageName(),
            R.layout.appwidget);
    remoteView.setImageViewBitmap(R.id.weather_appwidget_image, picture);
    remoteView.setTextViewText(R.id.weather_appwidget_temperature_max, tempMax);
    remoteView.setTextViewText(R.id.weather_appwidget_temperature_min, tempMin);
    remoteView.setTextViewText(R.id.weather_appwidget_city, city);
    if (!isCountry) {
        remoteView.setViewVisibility(R.id.weather_appwidget_country, View.GONE);
    } else {
        // TODO: It is as if Android had a view cache. If I did not set VISIBLE value,
        // the country field would be gone forever... :/
        remoteView.setViewVisibility(R.id.weather_appwidget_country, View.VISIBLE);
        remoteView.setTextViewText(R.id.weather_appwidget_country, country);
    }

    // 6. Activity launcher.
    final Intent resultIntent = new Intent(this.getApplicationContext(), WidgetConfigure.class);
    resultIntent.putExtra("actionFromUser", true);
    resultIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
    // From: http://stackoverflow.com/questions/4011178/multiple-instances-of-widget-only-updating-last-widget
    final Uri data = Uri.withAppendedPath(Uri.parse("PAIN" + "://widget/id/"), String.valueOf(appWidgetId));
    resultIntent.setData(data);

    final TaskStackBuilder stackBuilder = TaskStackBuilder.create(this.getApplicationContext());
    // Adds the back stack for the Intent (but not the Intent itself)
    stackBuilder.addParentStack(WidgetConfigure.class);
    // Adds the Intent that starts the Activity to the top of the stack
    stackBuilder.addNextIntent(resultIntent);
    final PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0,
            PendingIntent.FLAG_UPDATE_CURRENT);
    remoteView.setOnClickPendingIntent(R.id.weather_appwidget, resultPendingIntent);

    return remoteView;
}

From source file:org.odk.collect.android.utilities.MediaUtils.java

public static final int deleteVideoInFolderFromMediaProvider(File folder) {
    ContentResolver cr = Collect.getInstance().getContentResolver();
    // video//from w ww.  j  av  a 2 s .com
    int count = 0;
    Cursor videoCursor = null;
    try {
        String select = Video.Media.DATA + " like ? escape '!'";
        String[] selectArgs = { escapePath(folder.getAbsolutePath()) };

        String[] projection = { Video.VideoColumns._ID };
        videoCursor = cr.query(android.provider.MediaStore.Video.Media.EXTERNAL_CONTENT_URI, projection, select,
                selectArgs, null);
        if (videoCursor.getCount() > 0) {
            videoCursor.moveToFirst();
            List<Uri> videoToDelete = new ArrayList<Uri>();
            do {
                String id = videoCursor.getString(videoCursor.getColumnIndex(Video.VideoColumns._ID));

                videoToDelete.add(
                        Uri.withAppendedPath(android.provider.MediaStore.Video.Media.EXTERNAL_CONTENT_URI, id));
            } while (videoCursor.moveToNext());

            for (Uri uri : videoToDelete) {
                Log.i(t, "attempting to delete: " + uri);
                count += cr.delete(uri, null, null);
            }
        }
    } catch (Exception e) {
        Log.e(t, e.toString());
    } finally {
        if (videoCursor != null) {
            videoCursor.close();
        }
    }
    return count;
}

From source file:at.bitfire.vcard4android.AndroidContact.java

protected void populatePhoto(ContentValues row) throws RemoteException {
    if (row.containsKey(Photo.PHOTO_FILE_ID)) {
        Uri photoUri = Uri.withAppendedPath(rawContactSyncURI(), RawContacts.DisplayPhoto.CONTENT_DIRECTORY);
        try {// w  w  w  .  jav a  2 s . c o m
            @Cleanup
            AssetFileDescriptor fd = addressBook.provider.openAssetFile(photoUri, "r");
            @Cleanup
            InputStream stream = fd.createInputStream();
            if (stream != null)
                contact.photo = IOUtils.toByteArray(stream);
            else
                Constants.log.warn("Ignoring inaccessible local contact photo file");
        } catch (IOException e) {
            Constants.log.warn("Couldn't read local contact photo file", e);
        }
    } else
        contact.photo = row.getAsByteArray(Photo.PHOTO);
}

From source file:cz.maresmar.sfm.utils.ActionUtils.java

/**
 * Changes {@link ProviderContract#ACTION_SYNC_STATUS_EDIT} actions to {@link ProviderContract#ACTION_SYNC_STATUS_LOCAL}
 * and starts changes sync.//from   ww  w  .jav a2 s  . c  om
 *
 * @param context Some valid context
 * @param userUri User Uri prefix
 */
@WorkerThread
public static void saveEdits(@NonNull Context context, @NonNull Uri userUri) {
    Uri actionUri = Uri.withAppendedPath(userUri, ProviderContract.ACTION_PATH);
    long userId = ContentUris.parseId(userUri);

    // Delete conflict local rows
    int conflictRows = context.getContentResolver().delete(actionUri,
            ProviderContract.Action.SYNC_STATUS + " == " + ProviderContract.ACTION_SYNC_STATUS_LOCAL + " AND "
                    + "EXISTS ( SELECT * FROM " + DbContract.FoodAction.TABLE_NAME + " AS EditAct WHERE "
                    + "EditAct." + DbContract.FoodAction.COLUMN_NAME_CID + " == "
                    + ProviderContract.Action.CREDENTIAL_ID + " AND " + "EditAct."
                    + DbContract.FoodAction.COLUMN_NAME_ME_PID + " == " + ProviderContract.Action.ME_PORTAL_ID
                    + " AND " + "EditAct." + DbContract.FoodAction.COLUMN_NAME_ME_RELATIVE_ID + " == "
                    + ProviderContract.Action.ME_RELATIVE_ID + " AND " + "EditAct."
                    + DbContract.FoodAction.COLUMN_NAME_SYNC_STATUS + " == "
                    + ProviderContract.ACTION_SYNC_STATUS_EDIT + " )",
            null);
    Timber.d("Deleted %d rows with conflict local values", conflictRows);

    // Save rows that has different values then the synced ones
    ContentValues newValues = new ContentValues();
    newValues.put(ProviderContract.Action.SYNC_STATUS, ProviderContract.ACTION_SYNC_STATUS_LOCAL);
    newValues.put(ProviderContract.Action.LAST_CHANGE, System.currentTimeMillis());

    int updatedRows = context.getContentResolver().update(actionUri, newValues,
            ProviderContract.Action.SYNC_STATUS + " == " + ProviderContract.ACTION_SYNC_STATUS_EDIT + " AND ("
                    + "NOT EXISTS (SELECT * FROM " + DbContract.FoodAction.TABLE_NAME + " AS SyncAct WHERE "
                    + "SyncAct." + DbContract.FoodAction.COLUMN_NAME_CID + " IN (SELECT "
                    + DbContract.Credential._ID + " FROM " + DbContract.Credential.TABLE_NAME + " WHERE "
                    + DbContract.Credential.COLUMN_NAME_UID + " == " + userId + ") AND " + "SyncAct."
                    + DbContract.FoodAction.COLUMN_NAME_ME_PID + " == " + ProviderContract.Action.ME_PORTAL_ID
                    + " AND " + "SyncAct." + DbContract.FoodAction.COLUMN_NAME_ME_RELATIVE_ID + " == "
                    + ProviderContract.Action.ME_RELATIVE_ID + " AND " + "SyncAct."
                    + DbContract.FoodAction.COLUMN_NAME_SYNC_STATUS + " == "
                    + ProviderContract.ACTION_SYNC_STATUS_SYNCED + " ) " + "AND ("
                    + ProviderContract.Action.RESERVED_AMOUNT + " > 0 OR "
                    + ProviderContract.Action.OFFERED_AMOUNT + " > 0 ) " + "OR EXISTS (SELECT * FROM "
                    + DbContract.FoodAction.TABLE_NAME + " AS SyncAct WHERE " + "SyncAct."
                    + DbContract.FoodAction.COLUMN_NAME_CID + " IN (SELECT " + DbContract.Credential._ID
                    + " FROM " + DbContract.Credential.TABLE_NAME + " WHERE "
                    + DbContract.Credential.COLUMN_NAME_UID + " == " + userId + ") AND " + "SyncAct."
                    + DbContract.FoodAction.COLUMN_NAME_ME_PID + " == " + ProviderContract.Action.ME_PORTAL_ID
                    + " AND " + "SyncAct." + DbContract.FoodAction.COLUMN_NAME_ME_RELATIVE_ID + " == "
                    + ProviderContract.Action.ME_RELATIVE_ID + " AND " + "SyncAct."
                    + DbContract.FoodAction.COLUMN_NAME_SYNC_STATUS + " == "
                    + ProviderContract.ACTION_SYNC_STATUS_SYNCED + " AND (" + "SyncAct."
                    + DbContract.FoodAction.COLUMN_NAME_RESERVED_AMOUNT + " != "
                    + ProviderContract.Action.RESERVED_AMOUNT + " OR " + "SyncAct."
                    + DbContract.FoodAction.COLUMN_NAME_OFFERED_AMOUNT + " != "
                    + ProviderContract.Action.OFFERED_AMOUNT + " ) ) )",
            null);

    // Delete rest
    int unnecessaryRows = context.getContentResolver().delete(actionUri,
            ProviderContract.Action.SYNC_STATUS + " == " + ProviderContract.ACTION_SYNC_STATUS_EDIT, null);

    // Check invariants
    if (BuildConfig.DEBUG) {
        Assert.that(updatedRows + unnecessaryRows > 0, "Should change at least one rows");
        Assert.that(conflictRows <= updatedRows + unnecessaryRows, "Conflict rows overflow");
    }

    SyncHandler.planChangesSync(context);
}

From source file:com.fanfou.app.opensource.HomePage.java

@SuppressWarnings("deprecation")
private Cursor initMessageCursor() {
    final Uri uri = Uri.withAppendedPath(DirectMessageInfo.CONTENT_URI, "list");
    return managedQuery(uri, DirectMessageInfo.COLUMNS, null, null, null);
}

From source file:org.opendatakit.survey.android.tasks.InitializationTask.java

/**
 * Remove definitions from the Forms database that are no longer present on
 * disk.// ww w  .  j a va  2  s  .c  o m
 */
private final void removeStaleFormInfo(List<File> discoveredFormDefDirs) {
    Uri formsProviderContentUri = Uri.parse("content://" + FormsProviderAPI.AUTHORITY);

    String completionString = appContext.getString(R.string.searching_for_deleted_forms);
    publishProgress(completionString, null);

    WebLogger.getLogger(appName).i(t, "removeStaleFormInfo " + appName + " begin");
    ArrayList<Uri> badEntries = new ArrayList<Uri>();
    Cursor c = null;
    try {
        c = appContext.getContentResolver().query(Uri.withAppendedPath(formsProviderContentUri, appName), null,
                null, null, null);

        if (c == null) {
            WebLogger.getLogger(appName).w(t,
                    "removeStaleFormInfo " + appName + " null cursor returned from query.");
            return;
        }

        if (c.moveToFirst()) {
            do {
                String id = ODKDatabaseUtils.get().getIndexAsString(c, c.getColumnIndex(FormsColumns.FORM_ID));
                Uri otherUri = Uri.withAppendedPath(Uri.withAppendedPath(formsProviderContentUri, appName), id);

                String examString = appContext.getString(R.string.examining_form, id);
                publishProgress(examString, null);

                int appRelativeFormMediaPathIdx = c.getColumnIndex(FormsColumns.APP_RELATIVE_FORM_MEDIA_PATH);
                if (appRelativeFormMediaPathIdx == -1) {
                    throw new IllegalStateException("Column " + FormsColumns.APP_RELATIVE_FORM_MEDIA_PATH
                            + " missing from database table. Incompatible versions?");
                }
                String appRelativeFormMediaPath = ODKDatabaseUtils.get().getIndexAsString(c,
                        appRelativeFormMediaPathIdx);
                File f = ODKFileUtils.asAppFile(appName, appRelativeFormMediaPath);
                File formDefJson = new File(f, ODKFileUtils.FORMDEF_JSON_FILENAME);
                if (!f.exists() || !f.isDirectory() || !formDefJson.exists() || !formDefJson.isFile()) {
                    // the form definition does not exist
                    badEntries.add(otherUri);
                    continue;
                } else {
                    // ////////////////////////////////
                    // formdef.json exists. See if it is
                    // unchanged...
                    String json_md5 = ODKDatabaseUtils.get().getIndexAsString(c,
                            c.getColumnIndex(FormsColumns.JSON_MD5_HASH));
                    String fileMd5 = ODKFileUtils.getMd5Hash(appName, formDefJson);
                    if (json_md5.equals(fileMd5)) {
                        // it is unchanged -- no need to rescan it
                        discoveredFormDefDirs.remove(f);
                    }
                }
            } while (c.moveToNext());
        }
    } catch (Exception e) {
        WebLogger.getLogger(appName).e(t, "removeStaleFormInfo " + appName + " exception: " + e.toString());
        WebLogger.getLogger(appName).printStackTrace(e);
    } finally {
        if (c != null && !c.isClosed()) {
            c.close();
        }
    }

    // delete the other entries (and directories)
    for (Uri badUri : badEntries) {
        WebLogger.getLogger(appName).i(t,
                "removeStaleFormInfo: " + appName + " deleting: " + badUri.toString());
        try {
            appContext.getContentResolver().delete(badUri, null, null);
        } catch (Exception e) {
            WebLogger.getLogger(appName).e(t, "removeStaleFormInfo " + appName + " exception: " + e.toString());
            WebLogger.getLogger(appName).printStackTrace(e);
            // and continue -- don't throw an error
        }
    }
    WebLogger.getLogger(appName).i(t, "removeStaleFormInfo " + appName + " end");
}

From source file:org.opendatakit.common.android.task.InitializationTask.java

/**
 * Remove definitions from the Forms database that are no longer present on
 * disk.//from   w  w w . jav a  2s . co  m
 */
private final void removeStaleFormInfo(List<File> discoveredFormDefDirs) {
    Uri formsProviderContentUri = Uri.parse("content://" + FormsProviderAPI.AUTHORITY);

    String completionString = appContext.getString(R.string.searching_for_deleted_forms);
    publishProgress(completionString, null);

    WebLogger.getLogger(appName).i(t, "removeStaleFormInfo " + appName + " begin");
    ArrayList<Uri> badEntries = new ArrayList<Uri>();
    Cursor c = null;
    try {
        c = appContext.getContentResolver().query(Uri.withAppendedPath(formsProviderContentUri, appName), null,
                null, null, null);

        if (c == null) {
            WebLogger.getLogger(appName).w(t,
                    "removeStaleFormInfo " + appName + " null cursor returned from query.");
            return;
        }

        if (c.moveToFirst()) {
            do {
                String tableId = ODKCursorUtils.getIndexAsString(c, c.getColumnIndex(FormsColumns.TABLE_ID));
                String formId = ODKCursorUtils.getIndexAsString(c, c.getColumnIndex(FormsColumns.FORM_ID));
                Uri otherUri = Uri.withAppendedPath(
                        Uri.withAppendedPath(Uri.withAppendedPath(formsProviderContentUri, appName), tableId),
                        formId);

                String examString = appContext.getString(R.string.examining_form, tableId, formId);
                publishProgress(examString, null);

                String formDir = ODKFileUtils.getFormFolder(appName, tableId, formId);
                File f = new File(formDir);
                File formDefJson = new File(f, ODKFileUtils.FORMDEF_JSON_FILENAME);
                if (!f.exists() || !f.isDirectory() || !formDefJson.exists() || !formDefJson.isFile()) {
                    // the form definition does not exist
                    badEntries.add(otherUri);
                    continue;
                } else {
                    // ////////////////////////////////
                    // formdef.json exists. See if it is
                    // unchanged...
                    String json_md5 = ODKCursorUtils.getIndexAsString(c,
                            c.getColumnIndex(FormsColumns.JSON_MD5_HASH));
                    String fileMd5 = ODKFileUtils.getMd5Hash(appName, formDefJson);
                    if (json_md5.equals(fileMd5)) {
                        // it is unchanged -- no need to rescan it
                        discoveredFormDefDirs.remove(f);
                    }
                }
            } while (c.moveToNext());
        }
    } catch (Exception e) {
        WebLogger.getLogger(appName).e(t, "removeStaleFormInfo " + appName + " exception: " + e.toString());
        WebLogger.getLogger(appName).printStackTrace(e);
    } finally {
        if (c != null && !c.isClosed()) {
            c.close();
        }
    }

    // delete the other entries (and directories)
    for (Uri badUri : badEntries) {
        WebLogger.getLogger(appName).i(t,
                "removeStaleFormInfo: " + appName + " deleting: " + badUri.toString());
        try {
            appContext.getContentResolver().delete(badUri, null, null);
        } catch (Exception e) {
            WebLogger.getLogger(appName).e(t, "removeStaleFormInfo " + appName + " exception: " + e.toString());
            WebLogger.getLogger(appName).printStackTrace(e);
            // and continue -- don't throw an error
        }
    }
    WebLogger.getLogger(appName).i(t, "removeStaleFormInfo " + appName + " end");
}

From source file:org.opendatakit.common.android.provider.impl.FormsProviderImpl.java

@Override
public synchronized Uri insert(Uri uri, ContentValues initialValues) {
    List<String> segments = uri.getPathSegments();

    if (segments.size() != 1) {
        throw new IllegalArgumentException("Unknown URI (too many segments!) " + uri);
    }// www.j  a  va  2 s .c o  m

    String appName = segments.get(0);
    ODKFileUtils.verifyExternalStorageAvailability();
    ODKFileUtils.assertDirectoryStructure(appName);
    WebLogger log = WebLogger.getLogger(appName);

    ContentValues values;
    if (initialValues != null) {
        values = new ContentValues(initialValues);
    } else {
        values = new ContentValues();
    }

    // ODK2: require FORM_MEDIA_PATH (different behavior -- ODK1 and
    // required FORM_FILE_PATH)
    if (!values.containsKey(FormsColumns.APP_RELATIVE_FORM_MEDIA_PATH)) {
        throw new IllegalArgumentException(FormsColumns.APP_RELATIVE_FORM_MEDIA_PATH + " must be specified.");
    }

    // Normalize path...
    File mediaPath = ODKFileUtils.asAppFile(appName,
            values.getAsString(FormsColumns.APP_RELATIVE_FORM_MEDIA_PATH));

    // require that the form directory actually exists
    if (!mediaPath.exists()) {
        throw new IllegalArgumentException(FormsColumns.APP_RELATIVE_FORM_MEDIA_PATH
                + " directory does not exist: " + mediaPath.getAbsolutePath());
    }

    patchUpValues(appName, values);

    if (values.containsKey(FormsColumns.DISPLAY_SUBTEXT) == false) {
        Date today = new Date();
        String ts = new SimpleDateFormat(getContext().getString(R.string.added_on_date_at_time),
                Locale.getDefault()).format(today);
        values.put(FormsColumns.DISPLAY_SUBTEXT, ts);
    }

    if (values.containsKey(FormsColumns.DISPLAY_NAME) == false) {
        values.put(FormsColumns.DISPLAY_NAME, mediaPath.getName());
    }

    // first try to see if a record with this filename already exists...
    String[] projection = { FormsColumns.FORM_ID, FormsColumns.APP_RELATIVE_FORM_MEDIA_PATH };
    String[] selectionArgs = { ODKFileUtils.asRelativePath(appName, mediaPath) };
    String selection = FormsColumns.APP_RELATIVE_FORM_MEDIA_PATH + "=?";
    Cursor c = null;

    SQLiteDatabase db = null;
    try {
        db = DatabaseFactory.get().getDatabase(getContext(), appName);
        db.beginTransaction();
        try {
            c = db.query(DatabaseConstants.FORMS_TABLE_NAME, projection, selection, selectionArgs, null, null,
                    null);
            if (c == null) {
                throw new SQLException("FAILED Insert into " + uri
                        + " -- unable to query for existing records: " + mediaPath.getAbsolutePath());
            }
            if (c.getCount() > 0) {
                // already exists
                throw new SQLException("FAILED Insert into " + uri
                        + " -- row already exists for form directory: " + mediaPath.getAbsolutePath());
            }
        } catch (Exception e) {
            log.w(t, "FAILED Insert into " + uri + " -- query for existing row failed: " + e.toString());

            if (e instanceof SQLException) {
                throw (SQLException) e;
            } else {
                throw new SQLException(
                        "FAILED Insert into " + uri + " -- query for existing row failed: " + e.toString());
            }
        } finally {
            if (c != null) {
                c.close();
            }
        }

        try {
            long rowId = db.insert(DatabaseConstants.FORMS_TABLE_NAME, null, values);
            db.setTransactionSuccessful();
            if (rowId > 0) {
                Uri formUri = Uri.withAppendedPath(
                        Uri.withAppendedPath(Uri.parse("content://" + getFormsAuthority()), appName),
                        values.getAsString(FormsColumns.FORM_ID));
                getContext().getContentResolver().notifyChange(formUri, null);
                Uri idUri = Uri.withAppendedPath(
                        Uri.withAppendedPath(Uri.parse("content://" + getFormsAuthority()), appName),
                        Long.toString(rowId));
                getContext().getContentResolver().notifyChange(idUri, null);

                return formUri;
            }
        } catch (Exception e) {
            log.w(t, "FAILED Insert into " + uri + " -- insert of row failed: " + e.toString());

            if (e instanceof SQLException) {
                throw (SQLException) e;
            } else {
                throw new SQLException(
                        "FAILED Insert into " + uri + " -- insert of row failed: " + e.toString());
            }
        }
    } finally {
        if (db != null) {
            db.endTransaction();
            db.close();
        }
    }

    throw new SQLException("Failed to insert row into " + uri);
}

From source file:edu.nd.darts.cimon.MonitorReport.java

/**
 * Generate monitor report and store on SD card.
 * /*from  w  ww  .  j a  v a 2  s  . com*/
 * @return true if file successfully created
 */
private boolean createFile() {

    if (DebugLog.DEBUG)
        Log.d(TAG, "MonitorReport - createFile:" + monitorId + " metric:" + metricId);
    String state = Environment.getExternalStorageState();
    if (!Environment.MEDIA_MOUNTED.equals(state)) {
        if (DebugLog.WARNING)
            Log.w(TAG, "MonitorReport.createFile - external storage not available");
        return false;
    }
    File file = new File(context.getExternalFilesDir(null), "monitor" + monitorId + ".csv");
    BufferedWriter writer;
    try {
        writer = new BufferedWriter(new FileWriter(file));

        if (metadata) {
            writer.write("sep=\t");
            writer.newLine();
            Uri metricUri = Uri.withAppendedPath(CimonContentProvider.METRICS_URI, String.valueOf(metricId));
            Cursor metricCursor = context.getContentResolver().query(metricUri, null, null, null, null);
            if (metricCursor == null) {
                if (DebugLog.WARNING)
                    Log.w(TAG, "MonitorReport.createFile - metric cursor is empty");
            } else {
                int nameCol = metricCursor.getColumnIndex(MetricsTable.COLUMN_METRIC);
                int unitsCol = metricCursor.getColumnIndex(MetricsTable.COLUMN_UNITS);
                if (metricCursor.moveToFirst()) {
                    if (nameCol < 0) {
                        if (DebugLog.WARNING)
                            Log.w(TAG, "MonitorReport.createFile - metric name column not found");
                    } else {
                        metricName = metricCursor.getString(nameCol);
                    }
                    writer.write("Metric: " + metricName);
                    writer.newLine();

                    if (unitsCol < 0) {
                        if (DebugLog.WARNING)
                            Log.w(TAG, "MonitorReport.createFile - metric name column not found");
                    } else {
                        String units = metricCursor.getString(unitsCol);
                        writer.write("Units: " + units);
                        writer.newLine();
                    }
                } else {
                    if (DebugLog.WARNING)
                        Log.w(TAG, "MonitorReport.createFile - metric cursor empty");
                }
            }
            metricCursor.close();

            Uri monitorUri = Uri.withAppendedPath(CimonContentProvider.MONITOR_URI, String.valueOf(monitorId));
            Cursor monitorCursor = context.getContentResolver().query(monitorUri, null, null, null, null);
            if (monitorCursor == null) {
                if (DebugLog.WARNING)
                    Log.w(TAG, "MonitorReport.createFile - monitor cursor is empty");
            } else {
                int offsetCol = monitorCursor.getColumnIndex(MonitorTable.COLUMN_TIME_OFFSET);
                if (monitorCursor.moveToFirst()) {
                    if (offsetCol < 0) {
                        if (DebugLog.WARNING)
                            Log.w(TAG, "MonitorReport.createFile - epoch offset column not found");
                    } else {
                        long offset = monitorCursor.getLong(offsetCol);
                        writer.write("Offset from epoch (milliseconds): " + offset);
                        writer.newLine();
                    }
                } else {
                    if (DebugLog.WARNING)
                        Log.w(TAG, "MonitorReport.createFile - monitor cursor empty");
                }
            }
            monitorCursor.close();

            writer.newLine();
        }
        writer.write("Timestamp\tValue");
        writer.newLine();

        String[] projection = { DataTable.COLUMN_TIMESTAMP, DataTable.COLUMN_VALUE };
        Uri monitorUri = Uri.withAppendedPath(CimonContentProvider.MONITOR_DATA_URI, String.valueOf(monitorId));
        Cursor mCursor = context.getContentResolver().query(monitorUri, projection, null, null, null);
        if (mCursor == null) {
            if (DebugLog.WARNING)
                Log.w(TAG, "MonitorReport.createFile - data cursor is empty");
            writer.close();
            return false;
        }
        int timestampCol = mCursor.getColumnIndex(DataTable.COLUMN_TIMESTAMP);
        if (timestampCol < 0) {
            if (DebugLog.WARNING)
                Log.w(TAG, "MonitorReport.createFile - timestamp column not found");
            mCursor.close();
            writer.close();
            return false;
        }
        int valueCol = mCursor.getColumnIndex(DataTable.COLUMN_VALUE);
        if (valueCol < 0) {
            if (DebugLog.WARNING)
                Log.w(TAG, "MonitorReport.createFile - value column not found");
            mCursor.close();
            writer.close();
            return false;
        }
        long timestamp;
        float value;
        if (mCursor.moveToFirst()) {
            while (!mCursor.isAfterLast()) {
                timestamp = mCursor.getLong(timestampCol);
                value = mCursor.getFloat(valueCol);
                writer.write(timestamp + "\t" + value);
                writer.newLine();
                mCursor.moveToNext();
            }
        }
        mCursor.close();

        writer.flush();
        writer.close();
    } catch (IOException e) {
        if (DebugLog.WARNING)
            Log.w(TAG, "MonitorReport.createFile - file writer failed");
        e.printStackTrace();
        return false;
    }

    return true;
}

From source file:com.hybris.mobile.lib.commerce.sync.CatalogSyncAdapter.java

/**
 * Sync the catalog/*from w ww . ja v a2  s  .  c  o  m*/
 *
 * @param categoryList List of categories
 * @throws InterruptedException
 */
private void syncCatalog(final String[] categoryList) {
    Log.i(TAG, "Syncing the catalog for categories " + Arrays.toString(categoryList));

    QueryCatalog queryCatalog = new QueryCatalog();
    queryCatalog.setCatalogId(mContentServiceHelper.getConfiguration().getCatalogId());
    queryCatalog.setCatalogVersionId(mContentServiceHelper.getConfiguration().getCatalogVersionId());
    queryCatalog.setCatalogCategoryId(mContentServiceHelper.getConfiguration().getCatalogIdMainCategory());

    // Getting all the catalog with the cache parameter to true
    mContentServiceHelper.getCatalogCategory(new ResponseReceiver<CategoryHierarchy>() {

        @Override
        public void onResponse(Response<CategoryHierarchy> response) {
            Log.i(TAG, "Response received after syncing the catalog");

            // Because we cache this call - see the parameter true - we get first the cached data
            // We do the work only with the synced data
            if (response.isSync()) {

                // Create the links with the parent for all the categories
                if (response.getData() != null && response.getData().getSubcategories() != null) {
                    for (CategoryHierarchy categoryHierarchy : response.getData().getSubcategories()) {
                        categoryHierarchy.setParent(response.getData());
                    }
                }

                // We loop specific categories
                if (categoryList != null && categoryList.length > 0) {
                    Log.i(TAG, "Syncing the categories: " + Arrays.toString(categoryList));

                    for (final String aCategoryList : categoryList) {
                        if (StringUtils.isNotBlank(aCategoryList)) {
                            // Finding the category that matches the id
                            CategoryHierarchy categoryHierarchy = getCategory(response.getData(),
                                    aCategoryList);

                            if (categoryHierarchy != null) {
                                // Deleting the product-category links first
                                getContext().getContentResolver()
                                        .delete(Uri.withAppendedPath(
                                                CatalogContract.Provider.getUriGroup(AUTHORITY),
                                                categoryHierarchy.getId()), null, null);

                                Log.i(TAG, "Syncing the category " + categoryHierarchy.getId());
                                loopCategory(categoryHierarchy, 0, false, true);
                            }
                        }
                    }
                }
                // We loop through all the categories
                else {
                    // Deleting all the product-category links first
                    getContext().getContentResolver().delete(CatalogContract.Provider.getUriGroup(AUTHORITY),
                            null, null);

                    Log.i(TAG, "Syncing the entire catalog");
                    loopCategory(response.getData(), 0, true, true);
                }

                // We send a message to update the cache on the app
                LocalBroadcastManager.getInstance(getContext())
                        .sendBroadcast(new Intent(getContext().getString(R.string.intent_action_update_cache)));
            }
        }

        @Override
        public void onError(Response<ErrorList> response) {
            Log.e(TAG, ErrorUtils.getFirstErrorMessage(response.getData()));
        }
    }, null, queryCatalog, true, null, null);
}