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:za.co.neilson.alarm.database.Database.java

public static long create(String name, String time, String tone, int difficulty, boolean vibrate,
        String[] days) {/*from  ww w .j a  va2s .  c  o m*/
    ContentValues cv = new ContentValues();
    cv.put(COLUMN_ALARM_ACTIVE, true);
    cv.put(COLUMN_ALARM_TIME, time);
    Alarm.Day[] enumDays = new Alarm.Day[days.length];

    for (int i = 0; i < days.length; i++) {
        enumDays[i] = Alarm.Day.valueOf(days[i]);
    }

    try {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ObjectOutputStream oos = null;
        oos = new ObjectOutputStream(bos);
        oos.writeObject(enumDays);
        byte[] buff = bos.toByteArray();

        cv.put(COLUMN_ALARM_DAYS, buff);

    } catch (Exception e) {
    }

    cv.put(COLUMN_ALARM_DIFFICULTY, difficulty);
    cv.put(COLUMN_ALARM_TONE, tone);
    cv.put(COLUMN_ALARM_VIBRATE, vibrate);
    cv.put(COLUMN_ALARM_NAME, name);

    return getDatabase().insert(ALARM_TABLE, null, cv);
}

From source file:com.mpower.daktar.android.tasks.DownloadFormsTask.java

@Override
protected HashMap<String, String> doInBackground(final ArrayList<FormDetails>... values) {
    final ArrayList<FormDetails> toDownload = values[0];

    final int total = toDownload.size();
    int count = 1;

    final HashMap<String, String> result = new HashMap<String, String>();

    for (int i = 0; i < total; i++) {
        final FormDetails fd = toDownload.get(i);
        publishProgress(fd.formName, Integer.valueOf(count).toString(), Integer.valueOf(total).toString());

        String message = "";

        try {//  w  ww  .jav  a2  s .c o  m
            // get the xml file
            // if we've downloaded a duplicate, this gives us the file
            final File dl = downloadXform(fd.formName, fd.downloadUrl);

            final String[] projection = { BaseColumns._ID, FormsColumns.FORM_FILE_PATH };
            final String[] selectionArgs = { dl.getAbsolutePath() };
            final String selection = FormsColumns.FORM_FILE_PATH + "=?";
            final Cursor alreadyExists = MIntel.getInstance().getContentResolver()
                    .query(FormsColumns.CONTENT_URI, projection, selection, selectionArgs, null);

            Uri uri = null;
            if (alreadyExists.getCount() <= 0) {
                // doesn't exist, so insert it
                final ContentValues v = new ContentValues();
                v.put(FormsColumns.FORM_FILE_PATH, dl.getAbsolutePath());

                final HashMap<String, String> formInfo = FileUtils.parseXML(dl);
                v.put(FormsColumns.DISPLAY_NAME, formInfo.get(FileUtils.TITLE));
                v.put(FormsColumns.MODEL_VERSION, formInfo.get(FileUtils.MODEL));
                v.put(FormsColumns.UI_VERSION, formInfo.get(FileUtils.UI));
                v.put(FormsColumns.JR_FORM_ID, formInfo.get(FileUtils.FORMID));
                v.put(FormsColumns.SUBMISSION_URI, formInfo.get(FileUtils.SUBMISSIONURI));
                uri = MIntel.getInstance().getContentResolver().insert(FormsColumns.CONTENT_URI, v);
            } else {
                alreadyExists.moveToFirst();
                uri = Uri.withAppendedPath(FormsColumns.CONTENT_URI,
                        alreadyExists.getString(alreadyExists.getColumnIndex(BaseColumns._ID)));
            }

            if (fd.manifestUrl != null) {
                final Cursor c = MIntel.getInstance().getContentResolver().query(uri, null, null, null, null);
                if (c.getCount() > 0) {
                    // should be exactly 1
                    c.moveToFirst();

                    final String error = downloadManifestAndMediaFiles(
                            c.getString(c.getColumnIndex(FormsColumns.FORM_MEDIA_PATH)), fd, count, total);
                    if (error != null) {
                        message += error;
                    }
                }
            } else {
                // TODO: manifest was null?
                Log.e(t, "Manifest was null.  PANIC");
            }
        } catch (final SocketTimeoutException se) {
            se.printStackTrace();
            message += se.getMessage();
        } catch (final Exception e) {
            e.printStackTrace();
            if (e.getCause() != null) {
                message += e.getCause().getMessage();
            } else {
                message += e.getMessage();
            }
        }
        count++;
        if (message.equalsIgnoreCase("")) {
            message = MIntel.getInstance().getString(R.string.success);
        }
        result.put(fd.formName, message);
    }

    return result;
}

From source file:heartware.com.heartware_master.DBAdapter.java

public int updateProfile(HashMap<String, String> queryValues) {
    SQLiteDatabase database = this.getWritableDatabase();
    ContentValues values = new ContentValues();
    values.put(USERNAME, queryValues.get(USERNAME));
    values.put(PASSWORD, queryValues.get(PROFILE_ID));
    values.put(DIFFICULTY, queryValues.get(DIFFICULTY));
    values.put(DISABILITY, queryValues.get(DISABILITY));
    // update(TableName, ContentValueForTable, WhereClause, ArgumentForWhereClause)
    return database.update(PROFILES_TABLE, values, PROFILE_ID + " = ?",
            new String[] { queryValues.get(PROFILE_ID) });
}

From source file:com.manning.androidhacks.hack023.dao.TodoDAO.java

public int deleteTodo(ContentResolver contentResolver, Long id) {
    int ret = 0;//from  w  w w  .  j  ava  2 s  . co m

    /* Using the local id */
    int status = getTodoStatus(contentResolver, id);

    switch (status) {
    case StatusFlag.ADD:
        ret = contentResolver.delete(TodoContentProvider.CONTENT_URI, TodoContentProvider.COLUMN_ID + "=" + id,
                null);
        break;
    case StatusFlag.MOD:
    case StatusFlag.CLEAN:
        ContentValues cv = new ContentValues();
        cv.put(TodoContentProvider.COLUMN_STATUS_FLAG, StatusFlag.DELETE);
        contentResolver.update(TodoContentProvider.CONTENT_URI, cv, TodoContentProvider.COLUMN_ID + "=" + id,
                null);
        break;
    default:
        throw new RuntimeException("Tried to delete a todo with invalid status");
    }

    return ret;
}

From source file:com.clearcenter.mobile_demo.mdSyncAdapter.java

public void onPerformSync(Account account, Bundle extras, String authority, ContentProviderClient provider,
        SyncResult syncResult) {/*  w ww  . j a  va 2 s. c  om*/
    String authtoken = null;
    Log.i(TAG, "Starting sync operation...");

    try {
        mdSSLUtil.DisableSecurity();

        // Use the account manager to request the AuthToken we'll need
        // to talk to our sample server.  If we don't have an AuthToken
        // yet, this could involve a round-trip to the server to request
        // an AuthToken.
        authtoken = account_manager.blockingGetAuthToken(account, mdConstants.AUTHTOKEN_TYPE,
                NOTIFY_AUTH_FAILURE);

        final String hostname = account_manager.getUserData(account, "hostname");

        long _last_sample = -1;
        if (last_sample.containsKey(account.name))
            _last_sample = last_sample.get(account.name);

        // Get sync data from server...
        final String data = mdRest.GetSystemInfo(hostname, authtoken, _last_sample);

        // Something went wrong :^(
        if (TextUtils.isEmpty(data))
            return;

        if (_last_sample < 0) {
            int count = provider.delete(mdDeviceSamples.CONTENT_URI, mdDeviceSamples.NICKNAME + " = ?",
                    new String[] { account.name });

            Log.d(TAG, "Reset database, purged " + count + " samples.");
        }

        try {
            JSONObject json_data = new JSONObject(data);
            if (json_data.has("time"))
                _last_sample = Long.valueOf(json_data.getString("time"));
            Log.d(TAG, account.name + ": last sample time-stamp: " + _last_sample);
        } catch (JSONException e) {
            Log.e(TAG, "JSONException", e);
            return;
        }

        last_sample.put(account.name, _last_sample);

        ContentValues values = new ContentValues();
        values.put(mdDeviceSamples.NICKNAME, account.name);
        values.put(mdDeviceSamples.DATA, data);

        provider.insert(mdDeviceSamples.CONTENT_URI, values);

        String projection[] = new String[] { mdDeviceSamples.SAMPLE_ID };

        Cursor cursor = provider.query(mdDeviceSamples.CONTENT_URI, projection,
                mdDeviceSamples.NICKNAME + " = ?", new String[] { account.name }, mdDeviceSamples.SAMPLE_ID);

        int rows = cursor.getCount();
        Log.d(TAG, "Rows: " + rows);
        if (rows <= mdConstants.MAX_SAMPLES) {
            cursor.close();
            return;
        }

        Log.d(TAG, "Samples to purge: " + (rows - mdConstants.MAX_SAMPLES));
        cursor.move(rows - mdConstants.MAX_SAMPLES);

        int top_id = cursor.getInt(cursor.getColumnIndex(mdDeviceSamples.SAMPLE_ID));
        Log.d(TAG, "Top ID: " + top_id);

        cursor.close();

        int count = provider.delete(mdDeviceSamples.CONTENT_URI,
                mdDeviceSamples.SAMPLE_ID + " <= ? AND " + mdDeviceSamples.NICKNAME + " = ?",
                new String[] { String.valueOf(top_id), account.name });

        Log.d(TAG, "Purged " + count + " samples.");

    } catch (final RemoteException e) {
        Log.e(TAG, "RemoteException", e);
        syncResult.stats.numParseExceptions++;
    } catch (final AuthenticatorException e) {
        Log.e(TAG, "AuthenticatorException", e);
        syncResult.stats.numParseExceptions++;
    } catch (final OperationCanceledException e) {
        Log.e(TAG, "OperationCanceledExcetpion", e);
    } catch (final IOException e) {
        Log.e(TAG, "IOException", e);
        syncResult.stats.numIoExceptions++;
    } catch (final ParseException e) {
        Log.e(TAG, "ParseException", e);
        syncResult.stats.numParseExceptions++;
    } catch (final AuthenticationException e) {
        Log.e(TAG, "AuthenticationException", e);
        syncResult.stats.numAuthExceptions++;
        account_manager.invalidateAuthToken(mdConstants.AUTHTOKEN_TYPE, authtoken);
    } catch (GeneralSecurityException e) {
        Log.e(TAG, "GeneralSecurityException", e);
    } catch (final JSONException e) {
        Log.e(TAG, "JSONException", e);
        syncResult.stats.numParseExceptions++;
    }
}

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

@Override
protected ContentValues getContentValues(final Commentaire commentaire) {
    final ContentValues values = new ContentValues();
    values.put(CommentaireTable.CODE_LIGNE, commentaire.getCodeLigne());
    values.put(CommentaireTable.CODE_SENS, commentaire.getCodeSens());
    values.put(CommentaireTable.CODE_ARRET, commentaire.getCodeArret());
    values.put(CommentaireTable.MESSAGE, commentaire.getMessage());
    values.put(CommentaireTable.SOURCE, commentaire.getSource());
    values.put(CommentaireTable.TIMESTAMP, commentaire.getTimestamp());
    return values;
}

From source file:com.goliathonline.android.kegbot.io.RemoteTapHandler.java

private static ContentValues queryTapDetails(Uri uri, ContentResolver resolver) {
    final ContentValues values = new ContentValues();
    final Cursor cursor = resolver.query(uri, TapsQuery.PROJECTION, null, null, null);
    try {/*from   w  w w.  j  a  v a  2 s. c  o m*/
        if (cursor.moveToFirst()) {
            values.put(SyncColumns.UPDATED, cursor.getLong(TapsQuery.UPDATED));
        } else {
            values.put(SyncColumns.UPDATED, KegbotContract.UPDATED_NEVER);
        }
    } finally {
        cursor.close();
    }
    return values;
}

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  .  c om*/
        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:io.vit.vitio.Managers.ConnectDatabase.java

public void saveCourses(List<Course> courses) {
    try {/*from w ww.jav a  2 s. c  o 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();
        }
    }

}

From source file:com.jimandreas.popularmovies.FetchMovieListTask.java

/**
 * Take the String representing the complete movie info in JSON Format and
 * pull out the data we need to construct the Strings needed for the presentation.
 *
 * Fortunately parsing is easy:  constructor takes the JSON string and converts it
 * into an Object hierarchy for us./*w  w w .  j  a v a  2 s  . c  o  m*/
 */
private void getMovieListFromJson(String movieListJsonStr, String whatToDo) throws JSONException {

    // These are the names of the JSON objects that need to be extracted.

    //  COLUMNS:  id, overview, poster_path, release date, title, vote_average, vote_count

    final String MOVIEDB_RESULTS = "results";

    final String MOVIEDB_ID = "id";
    final String MOVIEDB_OVERVIEW = "overview";
    final String MOVIEDB_POSTER_PATH = "poster_path";
    final String MOVIEDB_RELEASE_DATE = "release_date";
    final String MOVIEDB_POPULARITY = "popularity";
    final String MOVIEDB_TITLE = "title";
    final String MOVIEDB_VOTE_AVERAGE = "vote_average";
    final String MOVIEDB_VOTE_COUNT = "vote_count";

    try {
        JSONObject movieListJson = new JSONObject(movieListJsonStr);
        JSONArray movieListArray = movieListJson.getJSONArray(MOVIEDB_RESULTS);
        Vector<ContentValues> cVVector = new Vector<ContentValues>(movieListArray.length());
        Uri uri = null;

        for (int i = 0; i < movieListArray.length(); i++) {
            // These are the values that will be collected.

            int id;
            String overview;
            String poster_path;
            String release_date;
            String popularity;
            String title;
            String vote_average;
            String vote_count;

            JSONObject movieInfo = movieListArray.getJSONObject(i);

            id = movieInfo.getInt(MOVIEDB_ID);
            overview = movieInfo.getString(MOVIEDB_OVERVIEW);
            poster_path = movieInfo.getString(MOVIEDB_POSTER_PATH);
            release_date = movieInfo.getString(MOVIEDB_RELEASE_DATE);
            popularity = movieInfo.getString(MOVIEDB_POPULARITY);
            title = movieInfo.getString(MOVIEDB_TITLE);
            vote_average = movieInfo.getString(MOVIEDB_VOTE_AVERAGE);
            vote_count = movieInfo.getString(MOVIEDB_VOTE_COUNT);

            ContentValues movieValues = new ContentValues();

            if (whatToDo.contains(FETCH_TOP_RATED)) {

                uri = MovieTopRated.CONTENT_URI;
                movieValues.put(MovieTopRated.COLUMN_MOVIE_ID, id);
                movieValues.put(MovieTopRated.COLUMN_POPULAR_INDEX, popularity);

                movieValues.put(MovieTopRated.COLUMN_OVERVIEW, overview);
                movieValues.put(MovieTopRated.COLUMN_POSTER_PATH, poster_path);
                movieValues.put(MovieTopRated.COLUMN_RELEASE_DATE, release_date);
                movieValues.put(MovieTopRated.COLUMN_TITLE, title);
                movieValues.put(MovieTopRated.COLUMN_VOTE_AVERAGE, vote_average);
                movieValues.put(MovieTopRated.COLUMN_VOTE_COUNT, vote_count);
                movieValues.put(MovieTopRated.COLUMN_MYNAME, "toprated");

            } else {
                uri = MoviePopular.CONTENT_URI;
                movieValues.put(MoviePopular.COLUMN_MOVIE_ID, id);
                movieValues.put(MoviePopular.COLUMN_POPULAR_INDEX, popularity);

                movieValues.put(MoviePopular.COLUMN_OVERVIEW, overview);
                movieValues.put(MoviePopular.COLUMN_POSTER_PATH, poster_path);
                movieValues.put(MoviePopular.COLUMN_RELEASE_DATE, release_date);
                movieValues.put(MoviePopular.COLUMN_TITLE, title);
                movieValues.put(MoviePopular.COLUMN_VOTE_AVERAGE, vote_average);
                movieValues.put(MoviePopular.COLUMN_VOTE_COUNT, vote_count);
                movieValues.put(MoviePopular.COLUMN_MYNAME, "popular");

            }

            cVVector.add(movieValues);
        }

        if (whatToDo.contains(FETCH_POPULAR)) {
            mTM.buildPopularMoviesListToUpdate();
        }

        int inserted = 0;
        // add to database
        if (cVVector.size() > 0) {
            ContentValues[] cvArray = new ContentValues[cVVector.size()];
            cVVector.toArray(cvArray);
            inserted = mContext.getContentResolver().bulkInsert(uri, cvArray);
        }

        if (EXTRA_VERBOSE)
            Timber.i("download complete. " + inserted + " Inserted");

    } catch (JSONException e) {
        Timber.i(e.getMessage(), e);
        e.printStackTrace();
    }
}