Example usage for android.content ContentValues ContentValues

List of usage examples for android.content ContentValues ContentValues

Introduction

In this page you can find the example usage for android.content ContentValues ContentValues.

Prototype

public ContentValues() 

Source Link

Document

Creates an empty set of values using the default initial size

Usage

From source file:com.mio.jrdv.sunshine.FetchWeatherTask.java

/**
 * Helper method to handle insertion of a new location in the weather database.
 *
 * @param locationSetting The location string used to request updates from the server.
 * @param cityName A human-readable city name, e.g "Mountain View"
 * @param lat the latitude of the city//from  w w w .ja v a  2s  .  com
 * @param lon the longitude of the city
 * @return the row ID of the added location.
 */

//este metodo lo he tenido que hace public para poder accederlo desde el TEstFetchWeatherTask!!

public long addLocation(String locationSetting, String cityName, double lat, double lon) {
    // Students: First, check if the location with this city name exists in the db
    // If it exists, return the current ID
    // Otherwise, insert it using the content resolver and the base URI
    // return 0;
    long locationId;

    // First, check if the location with this city name exists in the db
    Cursor locationCursor = mContext.getContentResolver().query(WeatherContract.LocationEntry.CONTENT_URI,
            new String[] { WeatherContract.LocationEntry._ID },
            WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING + " = ?", new String[] { locationSetting },
            null);
    // WeatherContract.LocationEntry.CONTENT_URI:
    //  ES content://com.mio.jrdv.sunshine.app/location

    if (locationCursor.moveToFirst()) {
        int locationIdIndex = locationCursor.getColumnIndex(WeatherContract.LocationEntry._ID);
        locationId = locationCursor.getLong(locationIdIndex);
    } else {
        // Now that the content provider is set up, inserting rows of data is pretty simple.
        // First create a ContentValues object to hold the data you want to insert.
        ContentValues locationValues = new ContentValues();

        // Then add the data, along with the corresponding name of the data type,
        // so the content provider knows what kind of value is being inserted.
        locationValues.put(WeatherContract.LocationEntry.COLUMN_CITY_NAME, cityName);
        locationValues.put(WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING, locationSetting);
        locationValues.put(WeatherContract.LocationEntry.COLUMN_COORD_LAT, lat);
        locationValues.put(WeatherContract.LocationEntry.COLUMN_COORD_LONG, lon);

        // Finally, insert location data into the database.
        Uri insertedUri = mContext.getContentResolver().insert(WeatherContract.LocationEntry.CONTENT_URI,
                locationValues);

        // The resulting URI contains the ID for the row.  Extract the locationId from the Uri.
        locationId = ContentUris.parseId(insertedUri);
    }

    locationCursor.close();
    // Wait, that worked?  Yes!
    return locationId;
}

From source file:edu.cwru.apo.Login.java

public void onRestRequestComplete(Methods method, JSONObject result) {
    if (method == Methods.login) {
        if (result != null) {
            try {
                String requestStatus = result.getString("requestStatus");
                if (requestStatus.compareTo("valid login") == 0) {
                    Auth.loggedIn = true;
                    Auth.Hmac.setCounter(result.getInt("counter"));
                    Auth.Hmac.setIncrement(result.getInt("increment"));
                    PhoneOpenHelper db = new PhoneOpenHelper(this);
                    if (database == null)
                        database = db.getWritableDatabase();
                    API api = new API(this);
                    if (!api.callMethod(Methods.phone, this, (String[]) null)) {
                        Toast msg = Toast.makeText(this, "Error: Calling phone", Toast.LENGTH_LONG);
                        msg.show();/*from w  w w  .  java2s.c  o m*/
                    }

                } else if (requestStatus.compareTo("invalid username") == 0) {
                    Toast msg = Toast.makeText(getApplicationContext(), "Invalid username", Toast.LENGTH_LONG);
                    msg.show();
                } else if (requestStatus.compareTo("invalid login") == 0) {
                    Toast msg = Toast.makeText(getApplicationContext(), "Invalid username and/or password",
                            Toast.LENGTH_LONG);
                    msg.show();
                } else if (requestStatus.compareTo("no user") == 0) {
                    Toast msg = Toast.makeText(getApplicationContext(), "No username was provided",
                            Toast.LENGTH_LONG);
                    msg.show();
                } else {
                    Toast msg = Toast.makeText(getApplicationContext(), "Invalid requestStatus",
                            Toast.LENGTH_LONG);
                    msg.show();
                }
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        } else {
            Toast msg = Toast.makeText(getApplicationContext(),
                    "Could not contact web server.  Please check your connection", Toast.LENGTH_LONG);
            msg.show();
        }
    } else if (method == Methods.phone) {
        if (result != null) {
            try {
                String requestStatus = result.getString("requestStatus");
                if (requestStatus.compareTo("success") == 0) {
                    SharedPreferences.Editor editor = getSharedPreferences(APO.PREF_FILE_NAME, MODE_PRIVATE)
                            .edit();
                    editor.putLong("updateTime", result.getLong("updateTime"));
                    editor.commit();
                    int numbros = result.getInt("numBros");

                    if (numbros > 0) {
                        JSONArray caseID = result.getJSONArray("caseID");
                        JSONArray first = result.getJSONArray("first");
                        JSONArray last = result.getJSONArray("last");
                        JSONArray phone = result.getJSONArray("phone");
                        JSONArray family = result.getJSONArray("family");
                        ContentValues values;
                        for (int i = 0; i < numbros; i++) {
                            values = new ContentValues();
                            values.put("_id", caseID.getString(i));
                            values.put("first", first.getString(i));
                            values.put("last", last.getString(i));
                            values.put("phone", phone.getString(i));
                            values.put("family", family.getString(i));
                            database.replace("phoneDB", null, values);
                        }
                    }
                    Intent homeIntent = new Intent(Login.this, Home.class);
                    Login.this.startActivity(homeIntent);
                    finish();
                } else if (requestStatus.compareTo("timestamp invalid") == 0) {
                    Toast msg = Toast.makeText(this, "Invalid timestamp.  Please try again.",
                            Toast.LENGTH_LONG);
                    msg.show();
                } else if (requestStatus.compareTo("HMAC invalid") == 0) {
                    Toast msg = Toast.makeText(this,
                            "You have been logged out by the server.  Please log in again.", Toast.LENGTH_LONG);
                    msg.show();
                } else {
                    Toast msg = Toast.makeText(this, "Invalid requestStatus", Toast.LENGTH_LONG);
                    msg.show();
                }
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    } else {
        Toast msg = Toast.makeText(getApplicationContext(), "Invalid method callback", Toast.LENGTH_LONG);
        msg.show();
    }
}

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

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

    // Connected?
    if (!mTools.isDeviceConnected()) {
        mTools.showToast(getString(R.string.device_not_connected), 1);

        finish();/*  w ww . java2 s .c  o  m*/

        return;
    }

    // Intent
    final Intent intent = getIntent();

    searchString = intent.getStringExtra("search");

    // Layout
    setContentView(R.layout.activity_interactions_cards);

    // Toolbar
    mToolbar = (Toolbar) findViewById(R.id.interactions_cards_toolbar);
    mToolbar.setTitle(getString(R.string.interactions_cards_search) + ": \"" + searchString + "\"");

    setSupportActionBar(mToolbar);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    // Progress bar
    mProgressBar = (ProgressBar) findViewById(R.id.interactions_cards_toolbar_progressbar);
    mProgressBar.setVisibility(View.VISIBLE);

    // Refresh
    mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.interactions_cards_swipe_refresh_layout);
    mSwipeRefreshLayout.setColorSchemeResources(R.color.accent_blue, R.color.accent_green,
            R.color.accent_purple, R.color.accent_orange);

    mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
            search(searchString, false);
        }
    });

    // Recycler view
    mRecyclerView = (RecyclerView) findViewById(R.id.interactions_cards_cards);

    mRecyclerView.setHasFixedSize(true);
    mRecyclerView.setAdapter(new InteractionsCardsAdapter(mContext, mProgressBar, new JSONArray()));
    mRecyclerView.setLayoutManager(new LinearLayoutManager(mContext));

    // No interactions
    mNoInteractionsLayout = (LinearLayout) findViewById(R.id.interactions_cards_no_interactions);

    Button noInteractionsButton = (Button) findViewById(R.id.interactions_cards_no_interactions_button);

    noInteractionsButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            try {
                Intent intent = new Intent(mContext, MainWebViewActivity.class);
                intent.putExtra("title",
                        getString(R.string.interactions_cards_search) + ": \"" + searchString + "\"");
                intent.putExtra("uri", "http://interaksjoner.no/analyser.asp?PreparatNavn="
                        + URLEncoder.encode(searchString.toLowerCase(), "utf-8") + "&submit1=Sjekk");
                mContext.startActivity(intent);
            } catch (Exception e) {
                Log.e("InteractionsCards", Log.getStackTraceString(e));
            }
        }
    });

    // Search
    search(searchString, true);

    // Correct
    RequestQueue requestQueue = Volley.newRequestQueue(mContext);

    try {
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET,
                getString(R.string.project_website_uri) + "api/1/correct/?search="
                        + URLEncoder.encode(searchString, "utf-8"),
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        try {
                            final String correctSearchString = response.getString("correct");

                            if (!correctSearchString.equals("")) {
                                new MaterialDialog.Builder(mContext)
                                        .title(getString(R.string.correct_dialog_title))
                                        .content(Html.fromHtml(getString(R.string.correct_dialog_message)
                                                + ":<br><br><b>" + correctSearchString + "</b>"))
                                        .positiveText(getString(R.string.correct_dialog_positive_button))
                                        .negativeText(getString(R.string.correct_dialog_negative_button))
                                        .callback(new MaterialDialog.ButtonCallback() {
                                            @Override
                                            public void onPositive(MaterialDialog dialog) {
                                                ContentValues contentValues = new ContentValues();
                                                contentValues.put(InteractionsSQLiteHelper.COLUMN_STRING,
                                                        correctSearchString);

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

                                                sqLiteDatabase.delete(InteractionsSQLiteHelper.TABLE,
                                                        InteractionsSQLiteHelper.COLUMN_STRING + " = "
                                                                + mTools.sqe(searchString) + " COLLATE NOCASE",
                                                        null);
                                                sqLiteDatabase.insert(InteractionsSQLiteHelper.TABLE, null,
                                                        contentValues);

                                                sqLiteDatabase.close();

                                                mToolbar.setTitle(getString(R.string.interactions_cards_search)
                                                        + ": \"" + correctSearchString + "\"");

                                                mProgressBar.setVisibility(View.VISIBLE);

                                                mNoInteractionsLayout.setVisibility(View.GONE);
                                                mSwipeRefreshLayout.setVisibility(View.VISIBLE);

                                                search(correctSearchString, true);
                                            }
                                        }).contentColorRes(R.color.black).positiveColorRes(R.color.dark_blue)
                                        .negativeColorRes(R.color.black).show();
                            }
                        } catch (Exception e) {
                            Log.e("InteractionsCards", Log.getStackTraceString(e));
                        }
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Log.e("InteractionsCards", error.toString());
                    }
                });

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

        requestQueue.add(jsonObjectRequest);
    } catch (Exception e) {
        Log.e("InteractionsCards", Log.getStackTraceString(e));
    }
}

From source file:net.naonedbus.manager.impl.FavoriManager.java

@Override
protected ContentValues getContentValues(final Favori item) {
    final ContentValues values = new ContentValues();
    values.put(FavoriTable._ID, item.getId());
    values.put(FavoriTable.CODE_LIGNE, item.getCodeLigne());
    values.put(FavoriTable.CODE_SENS, item.getCodeSens());
    values.put(FavoriTable.CODE_ARRET, item.getCodeArret());
    values.put(FavoriTable.NOM, item.getNomFavori());

    return values;
}

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

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

    // Connected?
    if (!mTools.isDeviceConnected()) {
        mTools.showToast(getString(R.string.device_not_connected), 1);

        finish();/*from  ww  w  . j  a va  2  s .co m*/

        return;
    }

    // Intent
    final Intent intent = getIntent();

    searchString = intent.getStringExtra("search");

    // Layout
    setContentView(R.layout.activity_clinicaltrials_cards);

    // Toolbar
    mToolbar = (Toolbar) findViewById(R.id.clinicaltrials_cards_toolbar);
    mToolbar.setTitle(getString(R.string.clinicaltrials_cards_search) + ": \"" + searchString + "\"");

    setSupportActionBar(mToolbar);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    // Progress bar
    mProgressBar = (ProgressBar) findViewById(R.id.clinicaltrials_cards_toolbar_progressbar);
    mProgressBar.setVisibility(View.VISIBLE);

    // Refresh
    mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.clinicaltrials_cards_swipe_refresh_layout);
    mSwipeRefreshLayout.setColorSchemeResources(R.color.accent_blue, R.color.accent_green,
            R.color.accent_purple, R.color.accent_orange);

    mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
            search(searchString, false);
        }
    });

    // Recycler view
    mRecyclerView = (RecyclerView) findViewById(R.id.clinicaltrials_cards_cards);

    mRecyclerView.setHasFixedSize(true);
    mRecyclerView.setAdapter(new ClinicalTrialsCardsAdapter(mContext, new JSONArray()));
    mRecyclerView.setLayoutManager(new LinearLayoutManager(mContext));

    // No clinical trials
    mNoClinicalTrialsLayout = (LinearLayout) findViewById(R.id.clinicaltrials_cards_no_clinicaltrials);

    Button noClinicalTrialsButton = (Button) findViewById(R.id.clinicaltrials_cards_no_results_button);

    noClinicalTrialsButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            try {
                Intent intent = new Intent(mContext, MainWebViewActivity.class);
                intent.putExtra("title",
                        getString(R.string.clinicaltrials_cards_search) + ": \"" + searchString + "\"");
                intent.putExtra("uri", "https://clinicaltrials.gov/ct2/results?term="
                        + URLEncoder.encode(searchString.toLowerCase(), "utf-8") + "&no_unk=Y");
                mContext.startActivity(intent);
            } catch (Exception e) {
                Log.e("ClinicalTrialsCards", Log.getStackTraceString(e));
            }
        }
    });

    // Search
    search(searchString, true);

    // Correct
    RequestQueue requestQueue = Volley.newRequestQueue(mContext);

    try {
        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET,
                getString(R.string.project_website_uri) + "api/1/correct/?search="
                        + URLEncoder.encode(searchString, "utf-8"),
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        try {
                            final String correctSearchString = response.getString("correct");

                            if (!correctSearchString.equals("")) {
                                new MaterialDialog.Builder(mContext)
                                        .title(getString(R.string.correct_dialog_title))
                                        .content(Html.fromHtml(getString(R.string.correct_dialog_message)
                                                + ":<br><br><b>" + correctSearchString + "</b>"))
                                        .positiveText(getString(R.string.correct_dialog_positive_button))
                                        .negativeText(getString(R.string.correct_dialog_negative_button))
                                        .callback(new MaterialDialog.ButtonCallback() {
                                            @Override
                                            public void onPositive(MaterialDialog dialog) {
                                                ContentValues contentValues = new ContentValues();
                                                contentValues.put(ClinicalTrialsSQLiteHelper.COLUMN_STRING,
                                                        correctSearchString);

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

                                                sqLiteDatabase.delete(ClinicalTrialsSQLiteHelper.TABLE,
                                                        ClinicalTrialsSQLiteHelper.COLUMN_STRING + " = "
                                                                + mTools.sqe(searchString) + " COLLATE NOCASE",
                                                        null);
                                                sqLiteDatabase.insert(ClinicalTrialsSQLiteHelper.TABLE, null,
                                                        contentValues);

                                                sqLiteDatabase.close();

                                                mToolbar.setTitle(
                                                        getString(R.string.clinicaltrials_cards_search) + ": \""
                                                                + correctSearchString + "\"");

                                                mProgressBar.setVisibility(View.VISIBLE);

                                                mNoClinicalTrialsLayout.setVisibility(View.GONE);
                                                mSwipeRefreshLayout.setVisibility(View.VISIBLE);

                                                search(correctSearchString, true);
                                            }
                                        }).contentColorRes(R.color.black).positiveColorRes(R.color.dark_blue)
                                        .negativeColorRes(R.color.black).show();
                            }
                        } catch (Exception e) {
                            Log.e("ClinicalTrialsCards", Log.getStackTraceString(e));
                        }
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Log.e("ClinicalTrialsCards", error.toString());
                    }
                });

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

        requestQueue.add(jsonObjectRequest);
    } catch (Exception e) {
        Log.e("ClinicalTrialsCards", Log.getStackTraceString(e));
    }
}

From source file:com.confidentsoftware.themebuilder.FlickrParser.java

private int addImagesFromJson(long wordId, String text, JSONObject queryResult) throws JSONException {
    JSONArray photos = queryResult.getJSONArray("photo");
    int numImages = 0;
    for (int i = 0; i < photos.length(); i++) {
        JSONObject photo = null;/* w  w w. ja  v  a  2s .c  om*/
        try {
            photo = photos.getJSONObject(i);
        } catch (JSONException e) {
            continue;
        }
        try {
            if (isPhotoOk(photo)) {
                String url = photo.getString(PHOTO_URL);
                String title = photo.getString("title");
                if (title.length() > MAX_TITLE_LENGTH) {
                    title = title.substring(0, MAX_TITLE_LENGTH - 3) + "...";
                }
                String id = photo.getString("id");
                Log.d(TAG, "Image: " + id);
                Uri imageUri = Images.findImage(mCr, Sites.CONTENT_URI_FLICKR, id);
                if (imageUri != null) {
                    Log.d(TAG, "Found existing image: " + imageUri);
                    // Just insert the mapping
                    Uri mappingUri = Dictionary.Words.CONTENT_URI.buildUpon().appendPath(String.valueOf(wordId))
                            .appendPath(Dictionary.PATH_IMAGES).appendPath(imageUri.getLastPathSegment())
                            .build();
                    Cursor c = mCr.query(mappingUri, PROJECTION_ID, null, null, null);
                    try {
                        if (!c.moveToNext()) {
                            mCr.insert(mappingUri, null);
                        }
                    } finally {
                        c.close();
                    }
                } else {
                    ContentValues values = new ContentValues();
                    values.put(Images.URL, url);
                    values.put(Images.SITE, ContentUris.parseId(Sites.CONTENT_URI_FLICKR));
                    values.put(Images.SITE_UNIQUE_NAME, id);
                    values.put(Images.WIDTH, photo.getInt(PHOTO_WIDTH));
                    values.put(Images.HEIGHT, photo.getInt(PHOTO_HEIGHT));
                    values.put(Images.THUMB_URL, photo.getString(THUMB_URL));
                    values.put(Images.NUM_FAVORITES, getNumFavorites(id));
                    imageUri = mCr.insert(Dictionary.BASE_CONTENT_URI.buildUpon()
                            .appendPath(Dictionary.PATH_WORDS).appendPath(String.valueOf(wordId))
                            .appendPath(Dictionary.PATH_IMAGES).build(), values);
                    //
                    // String ownerName = photo.getString("owner");
                    // Author author = findAuthor(ownerName);
                    // if (author == null) {
                    // author = buildAuthor(ownerName);
                    // }
                    // TODO set license
                    // image.setLicense(License.getLicenseByFlickrId(photo
                    // .getInt("license")));
                    // dbHelper.getImageDao().create(image);
                }
                // dbHelper.getWordImageDao().create(
                // new WordImage(word, image));
                numImages++;
            }
        } catch (JSONException e) {
            // Catch here so that we continue through the loop
            Log.w(TAG, "Error parsing photo: " + photo, e);
        }
    }
    return numImages;
}

From source file:com.raspi.chatapp.util.storage.MessageHistory.java

public boolean renameChat(String buddyId, String newName) {
    SQLiteDatabase db = mDbHelper.getWritableDatabase();
    ContentValues cv = new ContentValues();
    cv.put(MessageHistoryContract.ChatEntry.COLUMN_NAME_NAME, newName);
    String where = MessageHistoryContract.ChatEntry.COLUMN_NAME_BUDDY_ID + "=?";

    int res = db.update(MessageHistoryContract.ChatEntry.TABLE_NAME_ALL_CHATS, cv, where,
            new String[] { buddyId });
    db.close();/* w w  w . ja  v  a 2  s  . c  o m*/
    return (res > 0);
}

From source file:net.mutina.uclimb.ForegroundCameraLauncher.java

/**
 * Called when the camera view exits. /*from  ww w.  j  av  a2  s. c  o  m*/
 * 
 * @param requestCode       The request code originally supplied to startActivityForResult(), 
 *                          allowing you to identify who this result came from.
 * @param resultCode        The integer result code returned by the child activity through its setResult().
 * @param intent            An Intent, which can return result data to the caller (various data can be attached to Intent "extras").
 */
public void onActivityResult(int requestCode, int resultCode, Intent intent) {

    // If image available
    if (resultCode == Activity.RESULT_OK) {
        try {
            // Create an ExifHelper to save the exif data that is lost during compression
            ExifHelper exif = new ExifHelper();
            exif.createInFile(getTempDirectoryPath(ctx.getContext()) + "/Pic.jpg");
            exif.readExifData();

            // Read in bitmap of captured image
            Bitmap bitmap;
            try {
                bitmap = android.provider.MediaStore.Images.Media.getBitmap(this.ctx.getContentResolver(),
                        imageUri);
            } catch (FileNotFoundException e) {
                Uri uri = intent.getData();
                android.content.ContentResolver resolver = this.ctx.getContentResolver();
                bitmap = android.graphics.BitmapFactory.decodeStream(resolver.openInputStream(uri));
            }

            bitmap = scaleBitmap(bitmap);

            // Create entry in media store for image
            // (Don't use insertImage() because it uses default compression setting of 50 - no way to change it)
            ContentValues values = new ContentValues();
            values.put(android.provider.MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
            Uri uri = null;
            try {
                uri = this.ctx.getContentResolver()
                        .insert(android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
            } catch (UnsupportedOperationException e) {
                LOG.d(LOG_TAG, "Can't write to external media storage.");
                try {
                    uri = this.ctx.getContentResolver()
                            .insert(android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI, values);
                } catch (UnsupportedOperationException ex) {
                    LOG.d(LOG_TAG, "Can't write to internal media storage.");
                    this.failPicture("Error capturing image - no media storage found.");
                    return;
                }
            }

            // Add compressed version of captured image to returned media store Uri
            OutputStream os = this.ctx.getContentResolver().openOutputStream(uri);
            bitmap.compress(Bitmap.CompressFormat.JPEG, this.mQuality, os);
            os.close();

            // Restore exif data to file
            exif.createOutFile(getRealPathFromURI(uri, this.ctx));
            exif.writeExifData();

            // Send Uri back to JavaScript for viewing image
            this.success(new PluginResult(PluginResult.Status.OK, uri.toString()), this.callbackId);

            bitmap.recycle();
            bitmap = null;
            System.gc();

            checkForDuplicateImage();
        } catch (IOException e) {
            e.printStackTrace();
            this.failPicture("Error capturing image.");
        }
    }

    // If cancelled
    else if (resultCode == Activity.RESULT_CANCELED) {
        this.failPicture("Camera cancelled.");
    }

    // If something else
    else {
        this.failPicture("Did not complete!");
    }
}

From source file:com.notifry.android.database.NotifrySource.java

@Override
protected ContentValues flatten() {
    ContentValues values = new ContentValues();
    values.put(NotifryDatabaseAdapter.KEY_ACCOUNT_NAME, this.getAccountName());
    values.put(NotifryDatabaseAdapter.KEY_SERVER_ENABLED, this.getServerEnabled() ? 1 : 0);
    values.put(NotifryDatabaseAdapter.KEY_LOCAL_ENABLED, this.getLocalEnabled() ? 1 : 0);
    values.put(NotifryDatabaseAdapter.KEY_TITLE, this.getTitle());
    values.put(NotifryDatabaseAdapter.KEY_SERVER_ID, this.getServerId());
    values.put(NotifryDatabaseAdapter.KEY_CHANGE_TIMESTAMP, this.getChangeTimestamp());
    values.put(NotifryDatabaseAdapter.KEY_SOURCE_KEY, this.getSourceKey());
    values.put(NotifryDatabaseAdapter.KEY_USE_GLOBAL_NOTIFICATION, this.getUseGlobalNotification() ? 1 : 0);
    values.put(NotifryDatabaseAdapter.KEY_VIBRATE, this.getVibrate() ? 1 : 0);
    values.put(NotifryDatabaseAdapter.KEY_RINGTONE, this.getRingtone() ? 1 : 0);
    values.put(NotifryDatabaseAdapter.KEY_CUSTOM_RINGTONE, this.getCustomRingtone());
    values.put(NotifryDatabaseAdapter.KEY_LED_FLASH, this.getLedFlash() ? 1 : 0);
    values.put(NotifryDatabaseAdapter.KEY_SPEAK_MESSAGE, this.getSpeakMessage() ? 1 : 0);
    return values;
}

From source file:info.staticfree.android.units.UnitUsageDBHelper.java

public void loadInitialUnitUsage() {
    final SQLiteDatabase db = getWritableDatabase();
    // load the initial table in
    final ContentValues cv = new ContentValues();

    Log.d(TAG, "init all weights hash");
    final HashMap<String, Integer> allUnitWeights = new HashMap<String, Integer>(Unit.table.keySet().size());
    Log.d(TAG, "adding all known weights...");
    for (final String unitName : Unit.table.keySet()) {
        // don't add all uppercase names
        if (!unitName.toUpperCase().equals(unitName)) {
            allUnitWeights.put(unitName, 0);
        }/*from w  w w  . j ava2s.  c  o m*/
    }
    Log.d(TAG, "adding all known functions...");
    for (final String functionName : BuiltInFunction.table.keySet()) {
        allUnitWeights.put(functionName + "(", 0);
    }
    //      for (final String functionName: TabularFunction.table.keySet()){
    //         allUnitWeights.put(functionName + "(", 0);
    //      }
    //      for (final String functionName: ComputedFunction.table.keySet()){
    //         allUnitWeights.put(functionName + "(", 0);
    //      }
    for (final String functionName : DefinedFunction.table.keySet()) {
        allUnitWeights.put(functionName + "(", 0);
    }
    Log.d(TAG, "adding common weights");
    addAll(loadInitialWeights(R.raw.common_weights), allUnitWeights);
    Log.d(TAG, "adding regional weights");
    addAll(loadInitialWeights(R.raw.regional_weights), allUnitWeights);

    // This is so that things of common weight end up in non-random order
    // without having to do an SQL order-by.
    final ArrayList<String> sortedUnits = new ArrayList<String>(allUnitWeights.keySet());
    Log.d(TAG, "Sorting units...");
    Collections.sort(sortedUnits);
    Log.d(TAG, "Adding all sorted units...");

    final HashMap<String, String> fingerprints = loadFingerprints();

    db.beginTransaction();
    for (final String unitName : sortedUnits) {
        cv.put(UsageEntry._UNIT, unitName);
        cv.put(UsageEntry._USE_COUNT, allUnitWeights.get(unitName));

        final String fpr = fingerprints.containsKey(unitName) ? fingerprints.get(unitName)
                : getFingerprint(unitName);

        fingerprints.put(unitName, fpr);
        cv.put(UsageEntry._FACTOR_FPRINT, fpr);
        db.insert(DB_USAGE_TABLE, null, cv);
    }
    db.setTransactionSuccessful();
    db.endTransaction();
    db.close();

    context.getContentResolver().notifyChange(UsageEntry.CONTENT_URI, null);

    // If we have the right permissons, save the fingerprints file to a JSON file
    // which can then be imported into the app to speed up initial fingerpint loading.
    if (context.checkCallingOrSelfPermission(
            Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
        final File externalStorage = Environment.getExternalStorageDirectory();
        final File fprintsOutput = new File(externalStorage, "units_fingerprints.json");
        final JSONObject jo = new JSONObject(fingerprints);
        try {
            final FileWriter fw = new FileWriter(fprintsOutput);
            fw.write(jo.toString(1));
            fw.close();
            Log.i(TAG, "fingerprints written to: " + fprintsOutput.getCanonicalPath());

        } catch (final Exception e) {
            e.printStackTrace();
        }
    }
    Log.d(TAG, "done!");
}