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:com.taxicop.sync.SyncAdapter.java

public ArrayList<Complaint> query(ContentProviderClient provider, int FROM) {
    ArrayList<Complaint> reports = new ArrayList<Complaint>();
    try {/*  w  w  w . j a v  a2s  . c o  m*/
        Cursor c = provider.query(PlateContentProvider.URI_REPORT, null, Fields.ID_KEY + " > " + FROM + "",
                null, null);
        if (c.moveToFirst()) {
            do {
                float rank = c.getFloat(c.getColumnIndex(Fields.RANKING));
                String plate = "" + (c.getString(c.getColumnIndex(Fields.CAR_PLATE)));
                String desc = "" + (c.getString(c.getColumnIndex(Fields.DESCRIPTION)));
                String date = "" + (c.getString(c.getColumnIndex(Fields.DATE_REPORT)));
                Log.d(TAG, "plate=" + plate);
                reports.add(new Complaint(rank, plate, desc, USER, date));
            } while (c.moveToNext());
        }
        c.close();
    } catch (Exception e) {
        Log.e(TAG, "query= " + e.getMessage());
    }

    return reports;
}

From source file:com.nextgis.maplibui.formcontrol.Counter.java

@Override
public void init(JSONObject element, List<Field> fields, Bundle savedState, Cursor featureCursor,
        SharedPreferences preferences) throws JSONException {

    JSONObject attributes = element.getJSONObject(JSON_ATTRIBUTES_KEY);
    mFieldName = attributes.getString(JSON_FIELD_NAME_KEY);
    mIsShowLast = true;/*ww w . j a va2 s .co  m*/

    String value = null;
    if (null != featureCursor) { // feature exists
        int column = featureCursor.getColumnIndex(mFieldName);
        if (column >= 0)
            value = featureCursor.getString(column);
    } else if (ControlHelper.hasKey(savedState, mFieldName)) {
        mIncremented = savedState.getLong(ControlHelper.getSavedStateKey(mFieldName));
        value = getNewValue(attributes);
    } else { // new feature
        String last = preferences.getString(mFieldName, null);
        if (last == null)
            last = attributes.getInt(JSON_INIT_VALUE_KEY) - 1 + "";

        int inc = attributes.getInt(INCREMENT);
        mIncremented = Long.valueOf(last) + inc;
        value = getNewValue(attributes);
    }

    setEnabled(false);
    setText(value);
    setSingleLine(true);
}

From source file:com.yuntongxun.ecdemo.storage.IMessageSqlManager.java

/**
 * ?getItem/*  ww  w  .j  a va  2 s.co  m*/
 *
 * @param cursor
 * @return
 */
public static ECMessage packageMessage(Cursor cursor) {
    long id = cursor.getLong(cursor.getColumnIndex(IMessageColumn.ID));
    String sender = cursor.getString(cursor.getColumnIndexOrThrow(IMessageColumn.sender));
    String msgId = cursor.getString(cursor.getColumnIndexOrThrow(IMessageColumn.MESSAGE_ID));
    // long ownThreadId =
    // cursor.getLong(cursor.getColumnIndexOrThrow(IMessageColumn.OWN_THREAD_ID));
    long createDate = cursor.getLong(cursor.getColumnIndexOrThrow(IMessageColumn.CREATE_DATE));
    int version = cursor.getInt(cursor.getColumnIndexOrThrow(IMessageColumn.VERSION));
    String userData = cursor.getString(cursor.getColumnIndexOrThrow(IMessageColumn.USER_DATA));
    int read = cursor.getInt(cursor.getColumnIndexOrThrow(IMessageColumn.READ_STATUS));
    int boxType = cursor.getInt(cursor.getColumnIndexOrThrow(IMessageColumn.BOX_TYPE));
    int msgType = cursor.getInt(cursor.getColumnIndexOrThrow(IMessageColumn.MESSAGE_TYPE));
    int sendStatus = cursor.getInt(cursor.getColumnIndexOrThrow(IMessageColumn.SEND_STATUS));

    ECMessage ecMessage = ECMessage.createECMessage(ECMessage.Type.NONE);
    if (msgType == ECMessage.Type.TXT.ordinal() || msgType == Type.NONE.ordinal()) {
        String content = cursor.getString(cursor.getColumnIndexOrThrow(IMessageColumn.BODY));
        ecMessage.setType(ECMessage.Type.TXT);
        ECTextMessageBody textBody = new ECTextMessageBody(content);
        ecMessage.setBody(textBody);
    } else if (msgType == Type.CALL.ordinal()) {
        String content = cursor.getString(cursor.getColumnIndexOrThrow(IMessageColumn.BODY));
        ECCallMessageBody body = new ECCallMessageBody(content);
        ecMessage.setType(Type.CALL);
        ecMessage.setBody(body);
    } else if (msgType == ECMessage.Type.LOCATION.ordinal()) {
        String content = cursor.getString(cursor.getColumnIndexOrThrow(IMessageColumn.BODY));
        ecMessage.setType(ECMessage.Type.LOCATION);

        String lon;
        String lat;
        try {
            JSONObject jsonObject = new JSONObject(content);
            lon = jsonObject.getString("lon");
            lat = jsonObject.getString("lat");
            ECLocationMessageBody textBody = new ECLocationMessageBody(Double.parseDouble(lat),
                    Double.parseDouble(lon));
            textBody.setTitle(jsonObject.getString("title"));
            ecMessage.setBody(textBody);
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    else {
        String fileUrl = cursor.getString(cursor.getColumnIndexOrThrow(IMessageColumn.FILE_URL));
        String fileLocalPath = cursor.getString(cursor.getColumnIndexOrThrow(IMessageColumn.FILE_PATH));

        if (msgType == ECMessage.Type.VOICE.ordinal()) {
            ecMessage.setType(ECMessage.Type.VOICE);
            int duration = cursor.getInt(cursor.getColumnIndexOrThrow(IMessageColumn.DURATION));
            ECVoiceMessageBody voiceBody = new ECVoiceMessageBody(new File(fileLocalPath), 0);
            voiceBody.setRemoteUrl(fileUrl);
            ecMessage.setBody(voiceBody);
            voiceBody.setDuration(duration);
        } else if (msgType == ECMessage.Type.IMAGE.ordinal() || msgType == ECMessage.Type.VIDEO.ordinal()
                || msgType == ECMessage.Type.FILE.ordinal()) {
            ECFileMessageBody fileBody = new ECFileMessageBody();
            if (msgType == ECMessage.Type.FILE.ordinal()) {
                ecMessage.setType(ECMessage.Type.FILE);
            } else if (msgType == ECMessage.Type.IMAGE.ordinal()) {
                fileBody = new ECImageMessageBody();
                ecMessage.setType(ECMessage.Type.IMAGE);
            } else {
                fileBody = new ECVideoMessageBody();
                ecMessage.setType(ECMessage.Type.VIDEO);
            }
            fileBody.setLocalUrl(fileLocalPath);
            fileBody.setRemoteUrl(fileUrl);
            fileBody.setFileName(DemoUtils.getFileNameFormUserdata(userData));
            ecMessage.setBody(fileBody);
        } else if (msgType == Type.RICH_TEXT.ordinal()) {
            {
                ECPreviewMessageBody body = new ECPreviewMessageBody();
                ecMessage.setType(Type.RICH_TEXT);
                String content = cursor.getString(cursor.getColumnIndexOrThrow(IMessageColumn.BODY));
                body.setTitle(content);
                body.setLocalUrl(cursor.getString(cursor.getColumnIndexOrThrow(IMessageColumn.FILE_PATH)));
                body.setUrl(cursor.getString(cursor.getColumnIndexOrThrow(IMessageColumn.FILE_URL)));
                ecMessage.setBody(body);
            }
            //            return null;
        }
    }
    ecMessage.setId(id);
    ecMessage.setFrom(sender);
    ecMessage.setMsgId(msgId);
    ecMessage.setMsgTime(createDate);
    ecMessage.setUserData(userData);
    if (sendStatus == ECMessage.MessageStatus.SENDING.ordinal()) {
        ecMessage.setMsgStatus(ECMessage.MessageStatus.SENDING);
    } else if (sendStatus == ECMessage.MessageStatus.RECEIVE.ordinal() || sendStatus == 4) {
        // sendStatus == 4 ?
        ecMessage.setMsgStatus(ECMessage.MessageStatus.RECEIVE);
    } else if (sendStatus == ECMessage.MessageStatus.SUCCESS.ordinal()) {
        ecMessage.setMsgStatus(ECMessage.MessageStatus.SUCCESS);
    } else if (sendStatus == ECMessage.MessageStatus.FAILED.ordinal()) {
        ecMessage.setMsgStatus(ECMessage.MessageStatus.FAILED);
    }
    ecMessage.setDirection(getMessageDirect(boxType));

    return ecMessage;
}

From source file:me.kartikarora.transfersh.activities.TransferActivity.java

private void uploadFile(Uri uri) throws IOException {
    final ProgressDialog dialog = new ProgressDialog(TransferActivity.this);
    dialog.setMessage(getString(R.string.uploading_file));
    dialog.setCancelable(false);/*  www .j av  a 2  s.c o m*/
    dialog.show();
    Cursor cursor = getContentResolver().query(uri, null, null, null, null);
    if (cursor != null) {
        cursor.moveToFirst();
        int nameIndex = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
        final String name = cursor.getString(nameIndex);
        final String mimeType = getContentResolver().getType(uri);
        Log.d(this.getClass().getSimpleName(), cursor.getString(0));
        Log.d(this.getClass().getSimpleName(), name);
        Log.d(this.getClass().getSimpleName(), mimeType);
        InputStream inputStream = getContentResolver().openInputStream(uri);
        OutputStream outputStream = openFileOutput(name, MODE_PRIVATE);
        if (inputStream != null) {
            IOUtils.copy(inputStream, outputStream);
            final File file = new File(getFilesDir(), name);
            TypedFile typedFile = new TypedFile(mimeType, file);
            TransferClient.getInterface().uploadFile(typedFile, name, new ResponseCallback() {
                @Override
                public void success(Response response) {
                    BufferedReader reader;
                    StringBuilder sb = new StringBuilder();
                    try {
                        reader = new BufferedReader(new InputStreamReader(response.getBody().in()));
                        String line;
                        try {
                            while ((line = reader.readLine()) != null) {
                                sb.append(line);
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    String result = sb.toString();
                    Snackbar.make(mCoordinatorLayout, name + " " + getString(R.string.uploaded),
                            Snackbar.LENGTH_SHORT).show();

                    ContentValues values = new ContentValues();
                    values.put(FilesContract.FilesEntry.COLUMN_NAME, name);
                    values.put(FilesContract.FilesEntry.COLUMN_TYPE, mimeType);
                    values.put(FilesContract.FilesEntry.COLUMN_URL, result);
                    values.put(FilesContract.FilesEntry.COLUMN_SIZE, String.valueOf(file.getTotalSpace()));
                    getContentResolver().insert(FilesContract.BASE_CONTENT_URI, values);
                    getSupportLoaderManager().restartLoader(BuildConfig.VERSION_CODE, null,
                            TransferActivity.this);
                    FileUtils.deleteQuietly(file);
                    if (dialog.isShowing())
                        dialog.hide();
                }

                @Override
                public void failure(RetrofitError error) {
                    error.printStackTrace();
                    if (dialog.isShowing())
                        dialog.hide();
                    Snackbar.make(mCoordinatorLayout, R.string.something_went_wrong, Snackbar.LENGTH_INDEFINITE)
                            .setAction(R.string.report, new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                    // TODO add feedback code
                                }
                            }).show();
                }
            });
        } else
            Snackbar.make(mCoordinatorLayout, R.string.unable_to_read, Snackbar.LENGTH_SHORT).show();
    }
}

From source file:de.escoand.readdaily.DownloadHandler.java

@Override
public void onReceive(final Context context, final Intent intent) {
    final DownloadManager manager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
    final Database db = Database.getInstance(context);
    final Cursor downloads = db.getDownloads();

    LogHandler.log(Log.WARN, "receive starting");

    while (downloads.moveToNext()) {
        final long id = downloads.getLong(downloads.getColumnIndex(Database.COLUMN_ID));
        final String name = downloads.getString(downloads.getColumnIndex(Database.COLUMN_SUBSCRIPTION));
        final String mime = downloads.getString(downloads.getColumnIndex(Database.COLUMN_TYPE));
        final Cursor download = manager.query(new DownloadManager.Query().setFilterById(id));

        // download exists
        if (!download.moveToFirst())
            continue;

        // download finished
        if (download.getInt(
                download.getColumnIndex(DownloadManager.COLUMN_STATUS)) != DownloadManager.STATUS_SUCCESSFUL)
            continue;

        // import file in background
        new Thread(new Runnable() {
            @Override/*from   ww w.  j a  va2s.  c  o m*/
            public void run() {
                try {
                    LogHandler.log(Log.WARN, "import starting of " + name);

                    final FileInputStream stream = new ParcelFileDescriptor.AutoCloseInputStream(
                            manager.openDownloadedFile(id));
                    final String mimeServer = manager.getMimeTypeForDownloadedFile(id);

                    LogHandler.log(Log.INFO, "id: " + String.valueOf(id));
                    LogHandler.log(Log.INFO, "manager: " + manager.toString());
                    LogHandler.log(Log.INFO, "stream: " + stream.toString());
                    LogHandler.log(Log.INFO, "mime: " + mime);
                    LogHandler.log(Log.INFO, "mimeServer: " + mimeServer);

                    switch (mime != null ? mime : (mimeServer != null ? mimeServer : "")) {

                    // register feedback
                    case "application/json":
                        final byte[] buf = new byte[256];
                        final int len = stream.read(buf);
                        LogHandler.log(Log.WARN, "register feedback: " + new String(buf, 0, len));
                        break;

                    // csv data
                    case "text/plain":
                        db.importCSV(name, stream);
                        break;

                    // xml data
                    case "application/xml":
                    case "text/xml":
                        db.importXML(name, stream);
                        break;

                    // zipped data
                    case "application/zip":
                        db.importZIP(name, stream);
                        break;

                    // do nothing
                    default:
                        LogHandler.log(new IntentFilter.MalformedMimeTypeException());
                        break;
                    }

                    stream.close();
                    LogHandler.log(Log.WARN, "import finished (" + name + ")");
                }

                // file error
                catch (FileNotFoundException e) {
                    LogHandler.logAndShow(e, context, R.string.message_download_open);
                }

                // stream error
                catch (IOException e) {
                    LogHandler.logAndShow(e, context, R.string.message_download_read);
                }

                // xml error
                catch (XmlPullParserException e) {
                    LogHandler.logAndShow(e, context, R.string.message_download_xml);
                }

                // clean
                finally {
                    manager.remove(id);
                    db.removeDownload(id);
                    LogHandler.log(Log.WARN, "clean finished");
                }
            }
        }).start();
    }

    downloads.close();
    LogHandler.log(Log.WARN, "receiving done");
}

From source file:edu.auburn.ppl.cyclecolumbus.NoteUploader.java

/******************************************************************************************
 * Generates JSONObject form of a note to be uploaded
 ******************************************************************************************
 * @param noteId Unique note ID to be uploaded
 * @return JSONObject of the note//from  w  ww . j a  v  a  2 s  .  com
 * @throws JSONException
 ******************************************************************************************/
private JSONObject getNoteJSON(long noteId) throws JSONException {
    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    mDb.openReadOnly();
    Cursor noteCursor = mDb.fetchNote(noteId);

    Map<String, Integer> fieldMap = new HashMap<String, Integer>();
    fieldMap.put(NOTE_RECORDED, noteCursor.getColumnIndex(DbAdapter.K_NOTE_RECORDED));
    fieldMap.put(NOTE_LAT, noteCursor.getColumnIndex(DbAdapter.K_NOTE_LAT));
    fieldMap.put(NOTE_LGT, noteCursor.getColumnIndex(DbAdapter.K_NOTE_LGT));
    fieldMap.put(NOTE_HACC, noteCursor.getColumnIndex(DbAdapter.K_NOTE_ACC));
    fieldMap.put(NOTE_VACC, noteCursor.getColumnIndex(DbAdapter.K_NOTE_ACC));
    fieldMap.put(NOTE_ALT, noteCursor.getColumnIndex(DbAdapter.K_NOTE_ALT));
    fieldMap.put(NOTE_SPEED, noteCursor.getColumnIndex(DbAdapter.K_NOTE_SPEED));
    fieldMap.put(NOTE_TYPE, noteCursor.getColumnIndex(DbAdapter.K_NOTE_TYPE));
    fieldMap.put(NOTE_DETAILS, noteCursor.getColumnIndex(DbAdapter.K_NOTE_DETAILS));
    fieldMap.put(NOTE_IMGURL, noteCursor.getColumnIndex(DbAdapter.K_NOTE_IMGURL));

    JSONObject note = new JSONObject();

    note.put(NOTE_RECORDED, df.format(noteCursor.getDouble(fieldMap.get(NOTE_RECORDED))));
    note.put(NOTE_LAT, noteCursor.getDouble(fieldMap.get(NOTE_LAT)) / 1E6);
    note.put(NOTE_LGT, noteCursor.getDouble(fieldMap.get(NOTE_LGT)) / 1E6);
    note.put(NOTE_HACC, noteCursor.getDouble(fieldMap.get(NOTE_HACC)));
    note.put(NOTE_VACC, noteCursor.getDouble(fieldMap.get(NOTE_VACC)));
    note.put(NOTE_ALT, noteCursor.getDouble(fieldMap.get(NOTE_ALT)));
    note.put(NOTE_SPEED, noteCursor.getDouble(fieldMap.get(NOTE_SPEED)));
    note.put(NOTE_TYPE, noteCursor.getInt(fieldMap.get(NOTE_TYPE)));
    note.put(NOTE_DETAILS, noteCursor.getString(fieldMap.get(NOTE_DETAILS)));
    note.put(NOTE_IMGURL, noteCursor.getString(fieldMap.get(NOTE_IMGURL)));

    if (noteCursor.getString(fieldMap.get(NOTE_IMGURL)).equals("")) {
        imageDataNull = true;
    } else {
        imageDataNull = false;
        imageData = noteCursor.getBlob(noteCursor.getColumnIndex(DbAdapter.K_NOTE_IMGDATA));
    }

    noteCursor.close();
    mDb.close();
    return note;
}

From source file:com.zegoggles.smssync.mail.MessageConverter.java

private Map<String, String> getMessageMap(Cursor cursor) {
    final String[] columns = cursor.getColumnNames();
    final Map<String, String> msgMap = new HashMap<String, String>(columns.length);
    for (String column : columns) {
        String value;//from ww  w .j  ava  2  s.co  m
        try {
            final int index = cursor.getColumnIndex(column);
            if (index != -1) {
                value = cursor.getString(index);
            } else {
                continue;
            }
        } catch (SQLiteException ignored) {
            // this can happen in case of BLOBS in the DB
            // column type checking is API level >= 11
            value = "[BLOB]";
        }
        msgMap.put(column, value);
    }
    return msgMap;
}

From source file:org.blanco.techmun.android.MensajesActivity.java

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == 0 && resultCode == RESULT_OK) {
        Cursor c = managedQuery(android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI, null,
                "_id = " + 1, null, null);
        if (c != null && c.moveToNext()) {
            Uri selectedImage = data.getData();
            String[] filePathColumn = { MediaStore.Images.Media.DATA };

            Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
            cursor.moveToFirst();/*from  w  w w  . ja  v  a 2s.c  om*/

            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String filePath = cursor.getString(columnIndex);
            cursor.close();

            attachImage = BitmapFactory.decodeFile(filePath);
            //Mark the button as image attached
            btnAddImage.setBackgroundColor(Color.YELLOW);
            Log.i("techmun", "selected image" + filePath + " Loaded.");

        }
        Log.d("techmun", "Returned from image pick");

    }
    super.onActivityResult(requestCode, resultCode, data);
}

From source file:com.odoo.support.provider.OContentProvider.java

@Override
public int update(Uri uri, ContentValues values, String where, String[] whereArgs) {
    reInitModel();//from w  w w .  j  av a 2  s. c o  m
    SelectionBuilder builder = new SelectionBuilder();
    final SQLiteDatabase db = model.getWritableDatabase();
    final int match = matcher.match(uri);
    int count;
    switch (match) {
    case COLLECTION:
        Cursor cr = query(uri, new String[] { OColumn.ROW_ID }, where, whereArgs, null);
        while (cr.moveToNext()) {
            int id = cr.getInt(cr.getColumnIndex(OColumn.ROW_ID));
            handleManyToMany(getManyToManyRecords(values), id);
        }
        cr.close();

        count = builder.table(model.getTableName()).where(where, whereArgs).update(db, values);
        break;
    case SINGLE_ROW:
        String id = uri.getLastPathSegment();
        handleManyToMany(getManyToManyRecords(values), Integer.parseInt(id));
        count = builder.table(model.getTableName()).where(where, whereArgs).where(OColumn.ROW_ID + "=?", id)
                .where(where, whereArgs).update(db, values);
        break;
    default:
        throw new UnsupportedOperationException("Unknown uri: " + uri);
    }
    Context ctx = getContext();
    assert ctx != null;
    ctx.getContentResolver().notifyChange(uri, null, false);
    return count;
}

From source file:it.ms.theing.loquitur.functions.PhoneDir.java

/**
 * This function returns the full phone directory
 * @return/*from  w  w  w .  j  a  v a 2  s . co m*/
 * a Json array of phone / email fields
 * structure : [ { name:... , phone: ... , email: ... }, ..... ]
 */
@JavascriptInterface
public String list() {
    Cursor cursor = null;
    try {
        JSONArray obj = new JSONArray();
        cursor = context.getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null, null, null,
                null);
        while (cursor.moveToNext()) {

            String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
            String ID = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
            String phone = getPhone(ID);
            String email = getEmail(ID);

            JSONObject jo = new JSONObject();
            jo.put("name", name.toLowerCase());
            jo.put("phone", phone);
            jo.put("email", email);
            obj.put(jo);

        }
        cursor.close();
        cursor = null;
        return obj.toString();
    } catch (Exception e) {
        Utils.safe(e);
    }

    if (cursor != null) {
        try {
            cursor.close();
        } catch (Exception e) {
        }
    }
    return "";
}