Example usage for android.database Cursor getColumnIndex

List of usage examples for android.database Cursor getColumnIndex

Introduction

In this page you can find the example usage for android.database Cursor getColumnIndex.

Prototype

int getColumnIndex(String columnName);

Source Link

Document

Returns the zero-based index for the given column name, or -1 if the column doesn't exist.

Usage

From source file:fr.bde_eseo.eseomega.profile.ViewProfileFragment.java

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == INTENT_GALLERY_ID && resultCode == RESULT_OK && data != null) {

        Uri profPicture = data.getData();
        String[] filePathColumn = { MediaStore.Images.Media.DATA };
        Cursor cursor = getActivity().getContentResolver().query(profPicture, filePathColumn, null, null, null);
        if (cursor != null) {
            cursor.moveToFirst();//from   w w  w  .j a v a  2 s . c o m
            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String picturePath = cursor.getString(columnIndex);
            cursor.close();
            if (profile != null) { // cas impossible, mais au cas o ...
                profile.setPicturePath(picturePath);
                profile.registerProfileInPrefs(getActivity());
                setImageView();
                mOnUserProfileChange.OnUserProfileChange(profile);
            }
        } else {
            Toast.makeText(getActivity(), "Erreur lors du traitement de l'image.", Toast.LENGTH_SHORT).show();
        }
    }
}

From source file:edu.pdx.cecs.orcycle.NoteUploader.java

private JSONArray getNoteResponsesJSON(long noteId) throws JSONException {

    // Create a JSON array to hold all of the answers
    JSONArray jsonAnswers = new JSONArray();

    mDb.openReadOnly();/*w w  w . j av  a 2s  .c om*/
    try {
        Cursor answers = mDb.fetchNoteAnswers(noteId);

        int questionId = answers.getColumnIndex(DbAdapter.K_NOTE_ANSWER_QUESTION_ID);
        int answerId = answers.getColumnIndex(DbAdapter.K_NOTE_ANSWER_ANSWER_ID);
        int otherText = answers.getColumnIndex(DbAdapter.K_NOTE_ANSWER_OTHER_TEXT);
        String text;

        // Cycle thru the database entries
        while (!answers.isAfterLast()) {

            // For each row, construct a JSON object
            JSONObject json = new JSONObject();

            try {
                // Place values into the JSON object
                json.put(FID_QUESTION_ID, answers.getInt(questionId));
                json.put(FID_ANSWER_ID, answers.getInt(answerId));

                if (null != (text = answers.getString(otherText))) {
                    text = text.trim();
                    if (!text.equals("")) {
                        json.put(FID_ANSWER_OTHER_TEXT, text);
                    }
                }
                // Place JSON objects into the JSON array
                jsonAnswers.put(json);
            } catch (Exception ex) {
                Log.e(MODULE_TAG, ex.getMessage());
            }
            // Move to next row
            answers.moveToNext();
        }
        answers.close();
    } catch (Exception ex) {
        Log.e(MODULE_TAG, ex.getMessage());
    } finally {
        mDb.close();
    }
    return jsonAnswers;
}

From source file:org.openbmap.activities.DialogPreferenceCatalogs.java

/**
 * Initialises download manager for GINGERBREAD and newer
 *//* w  w  w .j  av a 2s  .  c o  m*/
@SuppressLint("NewApi")
private void initDownloadManager() {
    mDownloadManager = (DownloadManager) getContext().getSystemService(Context.DOWNLOAD_SERVICE);

    mReceiver = new BroadcastReceiver() {
        @SuppressLint("NewApi")
        @Override
        public void onReceive(final Context context, final Intent intent) {
            final String action = intent.getAction();
            if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
                final long downloadId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, 0);
                final DownloadManager.Query query = new DownloadManager.Query();
                query.setFilterById(downloadId);
                final Cursor c = mDownloadManager.query(query);
                if (c.moveToFirst()) {
                    final int columnIndex = c.getColumnIndex(DownloadManager.COLUMN_STATUS);
                    if (DownloadManager.STATUS_SUCCESSFUL == c.getInt(columnIndex)) {
                        // we're not checking download id here, that is done in handleDownloads
                        final String uriString = c
                                .getString(c.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
                        handleDownloads(uriString);
                    } else {
                        final int reason = c.getInt(c.getColumnIndex(DownloadManager.COLUMN_REASON));
                        Log.e(TAG, "Download failed: " + reason);
                    }
                }
            }
        }
    };

    getContext().registerReceiver(mReceiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
}

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

public Contribution fromCursor(Cursor cursor) {
    // Hardcoding column positions!
    //Check that cursor has a value to avoid CursorIndexOutOfBoundsException
    if (cursor.getCount() > 0) {
        int index;
        if (cursor.getColumnIndex(Table.COLUMN_LICENSE) == -1) {
            index = 15;//from  w  w w. ja va 2  s . c  o m
        } else {
            index = cursor.getColumnIndex(Table.COLUMN_LICENSE);
        }
        Contribution contribution = new Contribution(
                uriForId(cursor.getInt(cursor.getColumnIndex(Table.COLUMN_ID))),
                cursor.getString(cursor.getColumnIndex(Table.COLUMN_FILENAME)),
                parseUri(cursor.getString(cursor.getColumnIndex(Table.COLUMN_LOCAL_URI))),
                cursor.getString(cursor.getColumnIndex(Table.COLUMN_IMAGE_URL)),
                parseTimestamp(cursor.getLong(cursor.getColumnIndex(Table.COLUMN_TIMESTAMP))),
                cursor.getInt(cursor.getColumnIndex(Table.COLUMN_STATE)),
                cursor.getLong(cursor.getColumnIndex(Table.COLUMN_LENGTH)),
                parseTimestamp(cursor.getLong(cursor.getColumnIndex(Table.COLUMN_UPLOADED))),
                cursor.getLong(cursor.getColumnIndex(Table.COLUMN_TRANSFERRED)),
                cursor.getString(cursor.getColumnIndex(Table.COLUMN_SOURCE)),
                cursor.getString(cursor.getColumnIndex(Table.COLUMN_DESCRIPTION)),
                cursor.getString(cursor.getColumnIndex(Table.COLUMN_CREATOR)),
                cursor.getInt(cursor.getColumnIndex(Table.COLUMN_MULTIPLE)) == 1,
                cursor.getInt(cursor.getColumnIndex(Table.COLUMN_WIDTH)),
                cursor.getInt(cursor.getColumnIndex(Table.COLUMN_HEIGHT)), cursor.getString(index));

        String wikidataEntityId = cursor.getString(cursor.getColumnIndex(COLUMN_WIKI_DATA_ENTITY_ID));
        if (!StringUtils.isBlank(wikidataEntityId)) {
            contribution.setWikiDataEntityId(wikidataEntityId);
        }

        return contribution;
    }

    return null;
}

From source file:org.openbmap.activities.DialogPreferenceMaps.java

/**
 * Initialises download manager for GINGERBREAD and newer
 *///from  w w w  . j  a  va 2s.c  o m
@SuppressLint("NewApi")
private void initDownloadManager() {

    mDownloadManager = (DownloadManager) getContext().getSystemService(Context.DOWNLOAD_SERVICE);

    mReceiver = new BroadcastReceiver() {
        @SuppressLint("NewApi")
        @Override
        public void onReceive(final Context context, final Intent intent) {
            final String action = intent.getAction();
            if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
                final long downloadId = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, 0);
                final DownloadManager.Query query = new DownloadManager.Query();
                query.setFilterById(downloadId);
                final Cursor c = mDownloadManager.query(query);
                if (c.moveToFirst()) {
                    final int columnIndex = c.getColumnIndex(DownloadManager.COLUMN_STATUS);
                    if (DownloadManager.STATUS_SUCCESSFUL == c.getInt(columnIndex)) {
                        // we're not checking download id here, that is done in handleDownloads
                        final String uriString = c
                                .getString(c.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
                        handleDownloads(uriString);
                    } else {
                        final int reason = c.getInt(c.getColumnIndex(DownloadManager.COLUMN_REASON));
                        Log.e(TAG, "Download failed: " + reason);
                    }
                }
            }
        }
    };

    getContext().registerReceiver(mReceiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
}

From source file:com.winsuk.pebbletype.WatchCommunication.java

private void sendThreadList(Context context) {
    Cursor msgCursor = context.getContentResolver().query(Uri.parse("content://sms/inbox"), null, null, null,
            null);/*from  w ww .j  a  v  a2 s. c  o m*/
    Activity act = new Activity();
    act.startManagingCursor(msgCursor);
    ArrayList<SMSThread> threads = new ArrayList<SMSThread>();

    if (msgCursor.moveToFirst()) {
        for (int i = 0; i < msgCursor.getCount(); i++) {
            int thread_id = msgCursor.getInt(msgCursor.getColumnIndexOrThrow("thread_id"));
            SMSThread th = null;
            for (int t = 0; t < threads.size(); t++) {
                SMSThread existingTh = threads.get(t);
                if (existingTh.thread_id == thread_id) {
                    th = existingTh;
                }
            }

            if (th == null) {
                String address = msgCursor.getString(msgCursor.getColumnIndexOrThrow("address")).toString();
                String name = "";

                Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, address);
                Cursor contactCursor = context.getContentResolver().query(uri,
                        new String[] { PhoneLookup.DISPLAY_NAME }, null, null, null);
                if (contactCursor.moveToFirst()) {
                    name = contactCursor.getString(contactCursor.getColumnIndex(PhoneLookup.DISPLAY_NAME));
                    contactCursor.close();
                }

                th = new SMSThread();
                th.thread_id = thread_id;
                th.address = address;
                th.name = name;
                //th.messages = new ArrayList<String>();
                threads.add(th);
            }

            /* TODO: this line is causing crashes on select few devices
            String body = msgCursor.getString(msgCursor.getColumnIndexOrThrow("body")).toString();
            if (th.messages.size() < 5) {
               th.messages.add(body);
            }
            */

            msgCursor.moveToNext();
        }
    }
    msgCursor.close();

    int limit = (threads.size() <= THREAD_LIMIT ? threads.size() : THREAD_LIMIT);
    String output = "";

    if (limit > 0) {
        // Calculate how many characters names can take up
        int availibleCharacters = 120;
        for (int i = 0; i < limit; i++) {
            availibleCharacters -= threads.get(i).address.length();
            availibleCharacters -= 2; //for ; and \n
        }
        int maxNameLength = availibleCharacters / limit - 3;

        for (int i = 0; i < limit; i++) {
            SMSThread thread = threads.get(i);

            String name = "";
            if (thread.name.length() < maxNameLength) {
                name = thread.name;
            } else {
                name = thread.name.substring(0, maxNameLength - 1);
                name += "";
            }

            output = output + thread.address + ";" + name + "\n";

            /* List messages
            for (int ii = 0; ii < thread.messages.size(); ii++) {
               output = output + thread.messages.get(ii) + "\n";
            }*/
        }
    }
    PebbleDictionary data = new PebbleDictionary();
    data.addString(KEY_THREAD_LIST, output);
    PebbleKit.sendDataToPebble(context, PEBBLE_APP_UUID, data);
}

From source file:com.wodify.cordova.plugin.filepicker.FilePicker.java

/**
 * Gets details of file stored externally, e.g. from Google Drive or Dropbox
 * /*  w  ww  .  jav  a 2s.co  m*/
 * @param  uri 
 *         Uri of picked file
 */
private JSONArray getFileDetails(Uri uri) {
    Cursor cursor = this.cordova.getActivity().getContentResolver().query(uri, null, null, null, null);

    if (cursor != null && cursor.moveToFirst()) {
        String name = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));

        cursor.close();

        try {
            InputStream is = this.cordova.getActivity().getContentResolver().openInputStream(uri);
            if (is != null) {
                try {
                    byte[] bytesOfFile = IOUtils.toByteArray(is);
                    return formatFileDetails(bytesOfFile, name);
                } catch (IOException e) {
                    return null;
                } catch (NullPointerException e) {
                    return null;
                }
            } else
                return null;
        } catch (FileNotFoundException e) {
            return null;
        }
    } else
        return null;
}

From source file:io.github.protino.codewatch.ui.ProfileActivity.java

@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
    if (data != null) {
        if (data.moveToFirst()) {
            profileItem.setName(//from  w w w  .ja va 2  s.  c  o  m
                    data.getString(data.getColumnIndex(LeaderContract.LeaderEntry.COLUMN_DISPLAY_NAME)));
            profileItem.setDailyAverage(
                    data.getInt(data.getColumnIndex(LeaderContract.LeaderEntry.COLUMN_DAILY_AVERAGE)));
            profileItem.setLocation(
                    data.getString(data.getColumnIndex(LeaderContract.LeaderEntry.COLUMN_LOCATION)));
            profileItem
                    .setWebsite(data.getString(data.getColumnIndex(LeaderContract.LeaderEntry.COLUMN_WEBSITE)));
            profileItem.setEmail(data.getString(data.getColumnIndex(LeaderContract.LeaderEntry.COLUMN_EMAIL)));
            profileItem.setLanguageStats(
                    data.getString(data.getColumnIndex(LeaderContract.LeaderEntry.COLUMN_LANGUAGE_STATS)));
            profileItem
                    .setPhotoUrl(data.getString(data.getColumnIndex(LeaderContract.LeaderEntry.COLUMN_PHOTO)));
            profileItem.setRank(data.getInt(data.getColumnIndex(LeaderContract.LeaderEntry.COLUMN_RANK)));
            bindViews();
        }
    }
}

From source file:it.bradipao.berengar.DbTool.java

public static JSONObject db2json(SQLiteDatabase mDB, String sDbName) {
    // vars/*w  w w .  ja  v a2 s  .co m*/
    JSONObject jsonDB = new JSONObject();
    JSONArray jsonNameTables = new JSONArray();
    JSONArray jsonTables = new JSONArray();

    // read tables
    String sqlquery = "select * from sqlite_master";
    Cursor cur = mDB.rawQuery(sqlquery, null);
    // iterate through tables
    int iTableNum = 0;
    String sTableName = "";
    String sTableSql = "";
    while (cur.moveToNext()) {
        sTableName = cur.getString(cur.getColumnIndex("name"));
        sTableSql = cur.getString(cur.getColumnIndex("sql"));
        if (GOLOG)
            Log.d(LOGTAG, "TABLE NAME : " + sTableName);
        // skip metadata, sequence, and uidx before exporting tables
        if (!sTableName.equals("android_metadata") && !sTableName.equals("sqlite_sequence")
                && !sTableName.startsWith("uidx") && !sTableName.startsWith("idx_")
                && !sTableName.startsWith("_idx")) {
            // add new table
            iTableNum++;
            jsonNameTables.put(sTableName);
            // try exporting table
            jsonTables.put(table2json(mDB, sTableName, sTableSql));
        }
    }
    cur.close();

    // final json building
    try {
        // json db format
        jsonDB.put("jsondb_format", "1");
        // database name
        if ((sDbName != null) && (!sDbName.isEmpty()))
            jsonDB.put("db_name", sDbName);
        else
            jsonDB.put("db_name", "database.sqlite");
        // tables number and name
        jsonDB.put("tables_num", String.valueOf(iTableNum));
        jsonDB.put("tables_name", jsonNameTables);
        // tables
        jsonDB.put("tables", jsonTables);
    } catch (JSONException e) {
        Log.e(LOGTAG, "error in db2json", e);
    }

    // return String
    return jsonDB;
}

From source file:com.getmarco.weatherstationviewer.gcm.StationGcmListenerService.java

/**
 * Helper method to handle insertion of a station in the database if it doesn't already exist.
 *
 * @param stationTag the station/*from   w  w  w  .  ja v a2  s  .  co m*/
 * @return the row ID of the station (new or existing)
 */
long addStation(String stationTag) {
    long stationId;

    // First, check if a station with this tag exists in the db
    Cursor stationCursor = getContentResolver().query(StationContract.StationEntry.CONTENT_URI,
            new String[] { StationContract.StationEntry._ID }, StationContract.StationEntry.COLUMN_TAG + " = ?",
            new String[] { stationTag }, null);

    if (stationCursor.moveToFirst()) {
        int stationIdIndex = stationCursor.getColumnIndex(StationContract.StationEntry._ID);
        stationId = stationCursor.getLong(stationIdIndex);
    } else {
        ContentValues locationValues = new ContentValues();
        locationValues.put(StationContract.StationEntry.COLUMN_TAG, stationTag);
        locationValues.put(StationContract.StationEntry.COLUMN_NAME, stationTag);
        locationValues.put(StationContract.StationEntry.COLUMN_TEMP_HIGH, 0.0);
        locationValues.put(StationContract.StationEntry.COLUMN_TEMP_LOW, 0.0);
        locationValues.put(StationContract.StationEntry.COLUMN_HUMIDITY_HIGH, 0.0);
        locationValues.put(StationContract.StationEntry.COLUMN_HUMIDITY_LOW, 0.0);

        // Finally, insert location data into the database.
        Uri insertedUri = getContentResolver().insert(StationContract.StationEntry.CONTENT_URI, locationValues);

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

    stationCursor.close();
    return stationId;
}