Example usage for android.content ContentValues put

List of usage examples for android.content ContentValues put

Introduction

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

Prototype

public void put(String key, byte[] value) 

Source Link

Document

Adds a value to the set.

Usage

From source file:com.citrus.sdk.database.DBHandler.java

public void addBankOptions(JSONArray netbankingOption) {
    SQLiteDatabase db = this.getWritableDatabase();

    for (int i = 0; i < netbankingOption.length(); i++) {
        ContentValues loadValue = new ContentValues();
        try {/*from  w w w . j a v a  2 s. c  o  m*/
            JSONObject bankOption = netbankingOption.getJSONObject(i);
            loadValue.put(BANK, bankOption.getString("bankName"));
            loadValue.put(BANK_CID, bankOption.getString("issuerCode"));
        } catch (JSONException e) {

        }
        db.insert(BANK_TABLE, null, loadValue);
    }
}

From source file:com.citrus.sdk.database.DBHandler.java

public void addPayOption(JSONArray paymentArray) {
    SQLiteDatabase db = this.getWritableDatabase();
    for (int i = 0; i < paymentArray.length(); i++) {
        ContentValues loadValue = new ContentValues();
        try {/*from  www .j a  v a 2 s  . c  o  m*/
            JSONObject payOption = paymentArray.getJSONObject(i);
            loadValue.put(MMID, payOption.getString(MMID));
            loadValue.put(SCHEME, payOption.getString(SCHEME));
            loadValue.put(EXPDATE, payOption.getString(EXPDATE));
            loadValue.put(NAME, payOption.getString(NAME));
            loadValue.put(OWNER, payOption.getString(OWNER));
            loadValue.put(BANK, payOption.getString(BANK));
            loadValue.put(NUMBER, payOption.getString(NUMBER));
            loadValue.put(TYPE, payOption.getString(TYPE).toUpperCase());
            loadValue.put(IMPS_REGISTERED, payOption.getString(IMPS_REGISTERED));
            loadValue.put(TOKEN_ID, payOption.getString(TOKEN_ID));
        } catch (JSONException e) {
            throw new RuntimeException(e);
        }
        db.insert(PAYOPTION_TABLE, null, loadValue);

    }

}

From source file:com.mobshep.shepherdlogin.MainActivity.java

public void submitClicked(View v) {

    if (username.getText().toString().equals("") || password.getText().toString().equals("")) {
        Toast blank = Toast.makeText(MainActivity.this, "Blank Fields Detected!", Toast.LENGTH_SHORT);
        blank.show();//  w  w  w  . j a va2s .co  m
        return;
    }

    ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
    postParameters.add(new BasicNameValuePair("login", username.getText().toString()));
    postParameters.add(new BasicNameValuePair("pwd", password.getText().toString()));

    try {

        SharedPreferences SP = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
        String address = SP.getString("server_preference", "NA");

        String res = CustomHttpClient.executeHttpPost(address + "/mobileLogin", postParameters);

        JSONObject jObject = new JSONObject(res);

        String response = jObject.getString("JSESSIONID");

        System.out.println("SessionId: " + response);

        response = response.replaceAll("\\s+", "");

        Toast responseError = Toast.makeText(MainActivity.this, response, Toast.LENGTH_SHORT);
        responseError.show();

        Log.i(TAG, "Server Response:" + response);

        if (response.contains(" ERROR ")) {
            tvResponse.setText("Invalid username or password");
        }

        if (res != null) {
            Toast valid = Toast.makeText(MainActivity.this, "Logged In!", Toast.LENGTH_SHORT);
            valid.show();

            storedPref = getSharedPreferences("Sessions", MODE_PRIVATE);
            toEdit = storedPref.edit();
            toEdit.putString("sessionId", response);
            toEdit.commit();

            //store the session in content provider
            ContentValues values = new ContentValues();
            values.put(SessionProvider.sessionValue, response);

            // Provides access to other applications Content Providers
            Uri uri = getContentResolver().insert(SessionProvider.CONTENT_URL, values);

            Intent intent = new Intent(MainActivity.this, LoggedIn.class);
            startActivity(intent);

        } else {
            Toast.makeText(getBaseContext(), "Invalid Credentials!", Toast.LENGTH_SHORT).show();
        }
    } catch (Exception e) {

        if (e.toString().contains("ERROR")) {
            tvResponse.setText("Invalid Credentials");
        }

        else {

            Toast responseError = Toast.makeText(MainActivity.this, e.toString(), Toast.LENGTH_LONG);
            responseError.show();

            tvResponse.setText(e.toString());
        }
    }

}

From source file:com.bt.download.android.gui.UniversalScanner.java

private void scanDocument(String filePath) {
    File file = new File(filePath);

    if (documentExists(filePath, file.length())) {
        return;//www. ja va 2s  .  c  om
    }

    String displayName = FilenameUtils.getBaseName(file.getName());

    ContentResolver cr = context.getContentResolver();

    ContentValues values = new ContentValues();

    values.put(DocumentsColumns.DATA, filePath);
    values.put(DocumentsColumns.SIZE, file.length());
    values.put(DocumentsColumns.DISPLAY_NAME, displayName);
    values.put(DocumentsColumns.TITLE, displayName);
    values.put(DocumentsColumns.DATE_ADDED, System.currentTimeMillis());
    values.put(DocumentsColumns.DATE_MODIFIED, file.lastModified());
    values.put(DocumentsColumns.MIME_TYPE, UIUtils.getMimeType(filePath));

    Uri uri = cr.insert(Documents.Media.CONTENT_URI, values);

    FileDescriptor fd = new FileDescriptor();
    fd.fileType = Constants.FILE_TYPE_DOCUMENTS;
    fd.id = Integer.valueOf(uri.getLastPathSegment());

    shareFinishedDownload(fd);
}

From source file:fr.free.nrw.commons.contributions.ContributionDao.java

ContentValues toContentValues(Contribution contribution) {
    ContentValues cv = new ContentValues();
    cv.put(Table.COLUMN_FILENAME, contribution.getFilename());
    if (contribution.getLocalUri() != null) {
        cv.put(Table.COLUMN_LOCAL_URI, contribution.getLocalUri().toString());
    }//from w w  w  .ja  v a  2 s . c  o  m
    if (contribution.getImageUrl() != null) {
        cv.put(Table.COLUMN_IMAGE_URL, contribution.getImageUrl());
    }
    if (contribution.getDateUploaded() != null) {
        cv.put(Table.COLUMN_UPLOADED, contribution.getDateUploaded().getTime());
    }
    cv.put(Table.COLUMN_LENGTH, contribution.getDataLength());
    //This was always meant to store the date created..If somehow date created is not fetched while actually saving the contribution, lets save today's date
    cv.put(Table.COLUMN_TIMESTAMP, contribution.getDateCreated() == null ? System.currentTimeMillis()
            : contribution.getDateCreated().getTime());
    cv.put(Table.COLUMN_STATE, contribution.getState());
    cv.put(Table.COLUMN_TRANSFERRED, contribution.getTransferred());
    cv.put(Table.COLUMN_SOURCE, contribution.getSource());
    cv.put(Table.COLUMN_DESCRIPTION, contribution.getDescription());
    cv.put(Table.COLUMN_CREATOR, contribution.getCreator());
    cv.put(Table.COLUMN_MULTIPLE, contribution.getMultiple() ? 1 : 0);
    cv.put(Table.COLUMN_WIDTH, contribution.getWidth());
    cv.put(Table.COLUMN_HEIGHT, contribution.getHeight());
    cv.put(Table.COLUMN_LICENSE, contribution.getLicense());
    cv.put(Table.COLUMN_WIKI_DATA_ENTITY_ID, contribution.getWikiDataEntityId());
    return cv;
}

From source file:com.mwebster.exchange.EasOutboxService.java

/**
 * Send a single message via EAS/*from   w  w  w .ja  va  2s . c o m*/
 * Note that we mark messages SEND_FAILED when there is a permanent failure, rather than an
 * IOException, which is handled by SyncManager with retries, backoffs, etc.
 *
 * @param cacheDir the cache directory for this context
 * @param msgId the _id of the message to send
 * @throws IOException
 */
int sendMessage(File cacheDir, long msgId) throws IOException, MessagingException {
    int result;
    sendCallback(msgId, null, EmailServiceStatus.IN_PROGRESS);
    File tmpFile = File.createTempFile("eas_", "tmp", cacheDir);
    // Write the output to a temporary file
    try {
        String[] cols = getRowColumns(Message.CONTENT_URI, msgId, MessageColumns.FLAGS, MessageColumns.SUBJECT);
        int flags = Integer.parseInt(cols[0]);
        String subject = cols[1];

        boolean reply = (flags & Message.FLAG_TYPE_REPLY) != 0;
        boolean forward = (flags & Message.FLAG_TYPE_FORWARD) != 0;
        // The reference message and mailbox are called item and collection in EAS
        String itemId = null;
        String collectionId = null;
        if (reply || forward) {
            // First, we need to get the id of the reply/forward message
            cols = getRowColumns(Body.CONTENT_URI, BODY_SOURCE_PROJECTION, WHERE_MESSAGE_KEY,
                    new String[] { Long.toString(msgId) });
            if (cols != null) {
                long refId = Long.parseLong(cols[0]);
                // Then, we need the serverId and mailboxKey of the message
                cols = getRowColumns(Message.CONTENT_URI, refId, SyncColumns.SERVER_ID,
                        MessageColumns.MAILBOX_KEY);
                if (cols != null) {
                    itemId = cols[0];
                    long boxId = Long.parseLong(cols[1]);
                    // Then, we need the serverId of the mailbox
                    cols = getRowColumns(Mailbox.CONTENT_URI, boxId, MailboxColumns.SERVER_ID);
                    if (cols != null) {
                        collectionId = cols[0];
                    }
                }
            }
        }

        boolean smartSend = itemId != null && collectionId != null;

        // Write the message in rfc822 format to the temporary file
        FileOutputStream fileStream = new FileOutputStream(tmpFile);
        Rfc822Output.writeTo(mContext, msgId, fileStream, !smartSend, true);
        fileStream.close();

        // Now, get an input stream to our temporary file and create an entity with it
        FileInputStream inputStream = new FileInputStream(tmpFile);
        InputStreamEntity inputEntity = new InputStreamEntity(inputStream, tmpFile.length());

        // Create the appropriate command and POST it to the server
        String cmd = "SendMail&SaveInSent=T";
        if (smartSend) {
            cmd = reply ? "SmartReply" : "SmartForward";
            cmd += "&ItemId=" + itemId + "&CollectionId=" + collectionId + "&SaveInSent=T";
        }
        userLog("Send cmd: " + cmd);
        HttpResponse resp = sendHttpClientPost(cmd, inputEntity, SEND_MAIL_TIMEOUT);

        inputStream.close();
        int code = resp.getStatusLine().getStatusCode();
        if (code == HttpStatus.SC_OK) {
            userLog("Deleting message...");
            mContentResolver.delete(ContentUris.withAppendedId(Message.CONTENT_URI, msgId), null, null);
            result = EmailServiceStatus.SUCCESS;
            sendCallback(-1, subject, EmailServiceStatus.SUCCESS);
        } else {
            userLog("Message sending failed, code: " + code);
            ContentValues cv = new ContentValues();
            cv.put(SyncColumns.SERVER_ID, SEND_FAILED);
            Message.update(mContext, Message.CONTENT_URI, msgId, cv);
            // We mark the result as SUCCESS on a non-auth failure since the message itself is
            // already marked failed and we don't want to stop other messages from trying to
            // send.
            if (isAuthError(code)) {
                result = EmailServiceStatus.LOGIN_FAILED;
            } else {
                result = EmailServiceStatus.SUCCESS;
            }
            sendCallback(msgId, null, result);

        }
    } catch (IOException e) {
        // We catch this just to send the callback
        sendCallback(msgId, null, EmailServiceStatus.CONNECTION_ERROR);
        throw e;
    } finally {
        // Clean up the temporary file
        if (tmpFile.exists()) {
            tmpFile.delete();
        }
    }
    return result;
}

From source file:com.granita.contacticloudsync.syncadapter.AccountSettings.java

@SuppressWarnings("Recycle")
private void update_1_2() throws ContactsStorageException {
    /* - KEY_ADDRESSBOOK_URL ("addressbook_url"),
       - KEY_ADDRESSBOOK_CTAG ("addressbook_ctag"),
       - KEY_ADDRESSBOOK_VCARD_VERSION ("addressbook_vcard_version") are not used anymore (now stored in ContactsContract.SyncState)
       - KEY_LAST_ANDROID_VERSION ("last_android_version") has been added
    */// www.jav a  2 s  . c om

    // move previous address book info to ContactsContract.SyncState
    @Cleanup("release")
    ContentProviderClient provider = context.getContentResolver()
            .acquireContentProviderClient(ContactsContract.AUTHORITY);
    if (provider == null)
        throw new ContactsStorageException("Couldn't access Contacts provider");

    LocalAddressBook addr = new LocalAddressBook(account, provider);

    // until now, ContactsContract.Settings.UNGROUPED_VISIBLE was not set explicitly
    ContentValues values = new ContentValues();
    values.put(ContactsContract.Settings.UNGROUPED_VISIBLE, 1);
    addr.updateSettings(values);

    String url = accountManager.getUserData(account, "addressbook_url");
    if (!TextUtils.isEmpty(url))
        addr.setURL(url);
    accountManager.setUserData(account, "addressbook_url", null);

    String cTag = accountManager.getUserData(account, "addressbook_ctag");
    if (!TextUtils.isEmpty(cTag))
        addr.setCTag(cTag);
    accountManager.setUserData(account, "addressbook_ctag", null);

    accountManager.setUserData(account, KEY_SETTINGS_VERSION, "2");
}

From source file:alberthsu.sunshine.app.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 ww.ja  v a 2s.  c  om
 * @param lon the longitude of the city
 * @return the row ID of the added location.
 */
private long addLocation(String locationSetting, String cityName, double lat, double lon) {

    // First, check if the location with this city name exists in the db
    Cursor cursor = mContext.getContentResolver().query(LocationEntry.CONTENT_URI,
            new String[] { LocationEntry._ID }, LocationEntry.COLUMN_LOCATION_SETTING + " = ?",
            new String[] { locationSetting }, null);

    if (cursor.moveToFirst()) {
        int locationIdIndex = cursor.getColumnIndex(LocationEntry._ID);
        return cursor.getLong(locationIdIndex);
    } else {
        ContentValues locationValues = new ContentValues();
        locationValues.put(LocationEntry.COLUMN_LOCATION_SETTING, locationSetting);
        locationValues.put(LocationEntry.COLUMN_CITY_NAME, cityName);
        locationValues.put(LocationEntry.COLUMN_COORD_LAT, lat);
        locationValues.put(LocationEntry.COLUMN_COORD_LONG, lon);

        Uri locationInsertUri = mContext.getContentResolver().insert(LocationEntry.CONTENT_URI, locationValues);

        return ContentUris.parseId(locationInsertUri);
    }
}

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

protected synchronized void addSongImpl(SQLiteDatabase db, int serverKey, String id, String absolutePath) {
    ContentValues values = new ContentValues();
    values.put(SONGS_SERVER_KEY, serverKey);
    values.put(SONGS_SERVER_ID, id);/*from ww w .j ava2 s.  c  om*/
    values.put(SONGS_COMPLETE_PATH, absolutePath);

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

From source file:io.vit.vitio.Managers.ConnectDatabase.java

public void saveCourses(List<Course> courses) {
    try {//from w w  w.  j av a  2  s .  co m
        SQLiteDatabase db = this.getWritableDatabase();

        for (int i = 0; i < courses.size(); i++) {
            Course course = courses.get(i);

            ContentValues values = new ContentValues();

            values.put(COLUMNS[0], course.getCLASS_NUMBER());
            values.put(COLUMNS[1], course.getCOURSE_TITLE());
            values.put(COLUMNS[2], course.getCOURSE_SLOT());
            values.put(COLUMNS[3], course.getCOURSE_TYPE());
            values.put(COLUMNS[4], course.getCOURSE_TYPE_SHORT());
            Log.d("type", course.getCOURSE_TYPE_SHORT());
            values.put(COLUMNS[5], course.getCOURSE_LTPC().toString());
            values.put(COLUMNS[6], course.getCOURSE_CODE());
            values.put(COLUMNS[7], course.getCOURSE_MODE());
            values.put(COLUMNS[8], course.getCOURSE_OPTION());
            values.put(COLUMNS[9], course.getCOURSE_VENUE());
            values.put(COLUMNS[10], course.getCOURSE_FACULTY().toString());
            values.put(COLUMNS[11], course.getCOURSE_REGISTRATIONSTATUS());
            values.put(COLUMNS[12], course.getCOURSE_BILL_DATE());
            values.put(COLUMNS[13], course.getCOURSE_BILL_NUMBER());
            values.put(COLUMNS[14], course.getCOURSE_PROJECT_TITLE());
            values.put(COLUMNS[15], course.getCOURSE_JSON().toString());
            values.put(COLUMNS[16], course.getCOURSE_ATTENDANCE().getJson().toString());
            values.put(COLUMNS[17], course.getCOURSE_JSON().getJSONArray("timings").toString());
            values.put(COLUMNS[18], course.getCOURSE_JSON().getJSONObject("marks").toString());
            //db.insertWithOnConflict(TABLE_COURSES, null, values, SQLiteDatabase.CONFLICT_REPLACE);
            if (check()) {
                Log.d("update", "check()");
                //onUpgrade(db,db.getVersion(),192564);
                db.replace(TABLE_COURSES, null, values);
                //db.update(TABLE_COURSES, values, null, null);
            } else {
                Log.d("insert", "check()");
                db.insert(TABLE_COURSES, null, values);
            }
        }
        db.close();
    } catch (Exception e) {
        e.printStackTrace();
        SQLiteDatabase _db = this.getWritableDatabase();
        if (_db != null && _db.isOpen()) {
            _db.close();
        }
    }

}