Example usage for android.database Cursor moveToFirst

List of usage examples for android.database Cursor moveToFirst

Introduction

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

Prototype

boolean moveToFirst();

Source Link

Document

Move the cursor to the first row.

Usage

From source file:edu.stanford.mobisocial.dungbeetle.DBIdentityProvider.java

public String userProfile() {
    Cursor c = mHelper.getReadableDatabase().rawQuery("SELECT * FROM " + MyInfo.TABLE, new String[] {});

    try {//from   w  w  w .  j ava  2  s  .c  om
        c.moveToFirst();
        JSONObject obj = new JSONObject();
        try {
            obj.put("name", c.getString(c.getColumnIndexOrThrow(MyInfo.NAME)));
        } catch (JSONException e) {
        }
        return JSON.fastAddBase64(obj.toString(), "picture",
                c.getBlob(c.getColumnIndexOrThrow(MyInfo.PICTURE)));
    } finally {
        c.close();
    }
}

From source file:com.clutch.ClutchStats.java

public ArrayList<ABRow> getABLogs() {
    SQLiteDatabase db = getReadableDatabase();
    String[] args = {};/*www.j a va 2 s  .com*/
    ArrayList<ABRow> res = new ArrayList<ABRow>();
    Cursor cur = db.rawQuery("SELECT uuid, ts, data FROM ablog ORDER BY ts", args);
    cur.moveToFirst();
    while (!cur.isAfterLast()) {
        String uuid = cur.getString(0);
        double ts = cur.getDouble(1);
        JSONObject data;
        try {
            data = new JSONObject(cur.getString(2));
        } catch (JSONException e) {
            Log.w(TAG, "Could not serialize to JSON: " + cur.getString(3));
            cur.moveToNext();
            continue;
        }
        res.add(new ABRow(uuid, ts, data));
        cur.moveToNext();
    }
    db.close();
    return res;
}

From source file:edu.stanford.mobisocial.dungbeetle.DBIdentityProvider.java

public Contact contactForUser() {
    Cursor c = mHelper.getReadableDatabase().rawQuery("SELECT * FROM " + MyInfo.TABLE, new String[] {});
    try {//www .j a v  a  2  s  . c om
        c.moveToFirst();
        long id = Contact.MY_ID;
        String name = c.getString(c.getColumnIndexOrThrow(MyInfo.NAME));
        String email = c.getString(c.getColumnIndexOrThrow(MyInfo.EMAIL));
        String about = c.getString(c.getColumnIndexOrThrow(MyInfo.ABOUT));
        //hack, make about info the status field of the contact class
        Contact contact = new Contact(id, mPubKeyTag, name, email, 0, 0, false, null, about, null, null, 0);
        byte[] picdata = c.getBlob(c.getColumnIndexOrThrow(MyInfo.PICTURE));
        if (picdata != null) {
            contact.picture = BitmapFactory.decodeByteArray(picdata, 0, picdata.length);
        }
        return contact;
    } finally {
        c.close();
    }
}

From source file:com.polyvi.xface.extension.XStorageExt.java

/**
 * ?.//from w ww.ja  v  a 2 s .c  o  m
 *
 * @param cur
 *            
 * @param tx_id
 *             id
 * @param callbackCtx
 *            
 */
private void processResults(Cursor cur, String tx_id, XCallbackContext callbackCtx) {

    String result = "[]";

    if (cur.moveToFirst()) {
        JSONArray fullresult = new JSONArray();
        String key = "";
        String value = "";
        int colCount = cur.getColumnCount();

        do {
            JSONObject row = new JSONObject();
            try {
                for (int i = 0; i < colCount; ++i) {
                    key = cur.getColumnName(i);
                    value = cur.getString(i);
                    row.put(key, value);
                }
                fullresult.put(row);

            } catch (JSONException e) {
                e.printStackTrace();
            }

        } while (cur.moveToNext());

        result = fullresult.toString();
    }

    String jsScript = "xFace.require('xFace/extension/android/storage').completeQuery('" + tx_id + "', "
            + result + ");";
    mWebContext.getApplication().loadJavascript(jsScript);
}

From source file:com.googlecode.android_scripting.facade.SmsFacade.java

@Rpc(description = "Returns message attributes.")
public JSONObject smsGetMessageById(@RpcParameter(name = "id", description = "message ID") Integer id,
        @RpcParameter(name = "attributes") @RpcOptional JSONArray attributes) throws JSONException {
    JSONObject result = new JSONObject();
    Uri uri = buildMessageUri(id);//from   w w w  . j av  a2s.  co  m
    String[] columns;
    if (attributes == null || attributes.length() == 0) {
        // In case no attributes are specified we set the default ones.
        columns = new String[] { "_id", "address", "date", "body", "read" };
    } else {
        // Convert selected attributes list into usable string list.
        columns = new String[attributes.length()];
        for (int i = 0; i < attributes.length(); i++) {
            columns[i] = attributes.getString(i);
        }
    }
    Cursor cursor = mContentResolver.query(uri, columns, null, null, null);
    if (cursor != null) {
        cursor.moveToFirst();
        for (int i = 0; i < columns.length; i++) {
            result.put(columns[i], cursor.getString(i));
        }
        cursor.close();
    } else {
        result = null;
    }
    return result;
}

From source file:DictionaryDatabase.java

public long findWordID(String word) {
    long returnVal = -1;
    SQLiteDatabase db = getReadableDatabase();

    Cursor cursor = db.rawQuery("SELECT _id FROM " + TABLE_DICTIONARY + " WHERE " + FIELD_WORD + " = ?",
            new String[] { word });
    Log.i("findWordID", "getCount()=" + cursor.getCount());
    if (cursor.getCount() == 1) {
        cursor.moveToFirst();
        returnVal = cursor.getInt(0);/*from  w ww.  j  a  v a  2  s.  c om*/
    }
    return returnVal;
}

From source file:com.android.emailcommon.internet.Rfc822Output.java

/**
 * Write the entire message to an output stream.  This method provides buffering, so it is
 * not necessary to pass in a buffered output stream here.
 *
 * @param context system context for accessing the provider
 * @param messageId the message to write out
 * @param out the output stream to write the message to
 * @param useSmartReply whether or not quoted text is appended to a reply/forward
 *//*from   ww w.  j a v a2  s .c om*/
public static void writeTo(Context context, long messageId, OutputStream out, boolean useSmartReply,
        boolean sendBcc) throws IOException, MessagingException {
    Message message = Message.restoreMessageWithId(context, messageId);
    if (message == null) {
        // throw something?
        return;
    }

    OutputStream stream = new BufferedOutputStream(out, 1024);
    Writer writer = new OutputStreamWriter(stream);

    // Write the fixed headers.  Ordering is arbitrary (the legacy code iterated through a
    // hashmap here).

    String date = DATE_FORMAT.format(new Date(message.mTimeStamp));
    writeHeader(writer, "Date", date);

    writeEncodedHeader(writer, "Subject", message.mSubject);

    writeHeader(writer, "Message-ID", message.mMessageId);

    writeAddressHeader(writer, "From", message.mFrom);
    writeAddressHeader(writer, "To", message.mTo);
    writeAddressHeader(writer, "Cc", message.mCc);
    // Address fields.  Note that we skip bcc unless the sendBcc argument is true
    // SMTP should NOT send bcc headers, but EAS must send it!
    if (sendBcc) {
        writeAddressHeader(writer, "Bcc", message.mBcc);
    }
    writeAddressHeader(writer, "Reply-To", message.mReplyTo);
    writeHeader(writer, "MIME-Version", "1.0");

    // Analyze message and determine if we have multiparts
    Body body = Body.restoreBodyWithMessageId(context, message.mId);
    String[] bodyText = buildBodyText(body, message.mFlags, useSmartReply);

    Uri uri = ContentUris.withAppendedId(Attachment.MESSAGE_ID_URI, messageId);
    Cursor attachmentsCursor = context.getContentResolver().query(uri, Attachment.CONTENT_PROJECTION,
            WHERE_NOT_SMART_FORWARD, null, null);

    try {
        int attachmentCount = attachmentsCursor.getCount();
        boolean multipart = attachmentCount > 0;
        String multipartBoundary = null;
        String multipartType = "mixed";

        // Simplified case for no multipart - just emit text and be done.
        if (!multipart) {
            writeTextWithHeaders(writer, stream, bodyText);
        } else {
            // continue with multipart headers, then into multipart body
            multipartBoundary = getNextBoundary();

            // Move to the first attachment; this must succeed because multipart is true
            attachmentsCursor.moveToFirst();
            if (attachmentCount == 1) {
                // If we've got one attachment and it's an ics "attachment", we want to send
                // this as multipart/alternative instead of multipart/mixed
                int flags = attachmentsCursor.getInt(Attachment.CONTENT_FLAGS_COLUMN);
                if ((flags & Attachment.FLAG_ICS_ALTERNATIVE_PART) != 0) {
                    multipartType = "alternative";
                }
            }

            writeHeader(writer, "Content-Type",
                    "multipart/" + multipartType + "; boundary=\"" + multipartBoundary + "\"");
            // Finish headers and prepare for body section(s)
            writer.write("\r\n");

            // first multipart element is the body
            if (bodyText[INDEX_BODY_TEXT] != null) {
                writeBoundary(writer, multipartBoundary, false);
                writeTextWithHeaders(writer, stream, bodyText);
            }

            // Write out the attachments until we run out
            do {
                writeBoundary(writer, multipartBoundary, false);
                Attachment attachment = Attachment.getContent(attachmentsCursor, Attachment.class);
                writeOneAttachment(context, writer, stream, attachment);
                writer.write("\r\n");
            } while (attachmentsCursor.moveToNext());

            // end of multipart section
            writeBoundary(writer, multipartBoundary, true);
        }
    } finally {
        attachmentsCursor.close();
    }

    writer.flush();
    out.flush();
}

From source file:com.tcl.lzhang1.mymusic.MusicUtil.java

/**
 * get the music info/*from w w w. j  a va 2  s.com*/
 * 
 * @param musicFile
 * @return
 */
public static SongModel getMusicInfo(File musicFile) {
    SongModel model = new SongModel();
    // retrun null if music file is null or is or directory
    if (musicFile == null || !musicFile.isFile()) {
        return null;
    }

    byte[] buf = new byte[128];
    try {
        Log.d(LOG_TAG, "process music file{" + musicFile.getAbsolutePath() + "}");
        // tag_v1
        RandomAccessFile music = new RandomAccessFile(musicFile, "r");

        music.seek(music.length() - 128);
        music.read(buf);// read tag to buffer
        // tag_v2
        byte[] header = new byte[10];
        music.seek(0);
        music.read(header, 0, 10);
        // if ("ID3".equalsIgnoreCase(new String(header, 0, 3))) {
        // int ID3V2_frame_size = (int) (header[6] & 0x7F) * 0x200000
        // | (int) (header[7] & 0x7F) * 0x400
        // | (int) (header[8] & 0x7F) * 0x80
        // | (int) (header[9] & 0x7F);
        // byte[] FrameHeader = new byte[4];
        // music.seek(ID3V2_frame_size + 10);
        // music.read(FrameHeader, 0, 4);
        // model = getTimeInfo(FrameHeader, ID3V2_frame_size, musicFile);
        // } else {
        // byte[] FrameHeader = new byte[4];
        // music.read(FrameHeader, 0, 4);
        // model = getTimeInfo(FrameHeader, 0, musicFile);
        // }

        music.close();// close file
        // check length
        // if (buf.length != 128) {
        // throw new
        // ErrorMusicLength(String.format("error music info length, length is:%i",
        // buf.length));
        // }
        //
        // if (!"TAG".equalsIgnoreCase(new String(buf, 0, 3))) {
        // throw new UnknownTagException("unknown tag exception");
        // }
        String songName = null;
        // try {
        // songName = new String(buf, 3, 30, "gbk").trim();
        // } catch (UnsupportedEncodingException e) {
        // // TODO: handle exception
        // e.printStackTrace();
        // songName = new String(buf, 3, 30).trim();
        // }
        String singerName = "";
        // try {
        // singerName = new String(buf, 33, 30, "gbk").trim();
        // } catch (UnsupportedEncodingException e) {
        // // TODO: handle exception
        // singerName = new String(buf, 33, 30).trim();
        // }
        String ablum = "";
        // try {
        // ablum = new String(buf, 63, 30, "gbk").trim();
        // } catch (UnsupportedEncodingException e) {
        // // TODO: handle exception
        // ablum = new String(buf, 63, 30).trim();
        // }
        String year = "";
        // try {
        // year = new String(buf, 93, 4, "gbk").trim();
        // } catch (UnsupportedEncodingException e) {
        // year = new String(buf, 93, 4).trim();
        // // TODO: handle exception
        // }

        String reamrk = "";
        ContentResolver contentResolver = sContext.getContentResolver();
        Cursor cursor = contentResolver.query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, "_data=?",
                new String[] { musicFile.getAbsolutePath() }, null);
        cursor.moveToFirst();
        if (cursor != null && cursor.getCount() != 0) {
            try {
                if (TextUtils.isEmpty(songName)) {
                    songName = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.AudioColumns.TITLE));
                    singerName = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.AudioColumns.ARTIST));
                    ablum = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.AudioColumns.ALBUM));
                    year = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.AudioColumns.YEAR));
                }

                long secs = cursor.getLong(cursor.getColumnIndex(MediaStore.Audio.AudioColumns.DURATION));
                model.setTime(secs);
                secs /= 1000;
                model.setHours((int) secs / 3600);
                model.setMinutes(((int) secs % 3600) / 60);
                model.setSeconds(((int) secs % 3600) % 60);
                cursor.close();
            } catch (CursorIndexOutOfBoundsException e) {
                // TODO: handle exception
                if (null != cursor) {
                    cursor.close();
                    cursor = null;
                }
                Log.d(LOG_TAG, "CursorIndexOutOfBoundsException:" + e.getMessage());
                try {
                    songName = new String(buf, 3, 30, "gbk").trim();
                } catch (UnsupportedEncodingException e0) {
                    // TODO: handle exception
                    e.printStackTrace();
                    songName = new String(buf, 3, 30).trim();
                }
                try {
                    singerName = new String(buf, 33, 30, "gbk").trim();
                } catch (UnsupportedEncodingException e1) {
                    // TODO: handle exception
                    singerName = new String(buf, 33, 30).trim();
                }
                try {
                    ablum = new String(buf, 63, 30, "gbk").trim();
                } catch (UnsupportedEncodingException e2) {
                    // TODO: handle exception
                    ablum = new String(buf, 63, 30).trim();
                }
                try {
                    year = new String(buf, 93, 4, "gbk").trim();
                } catch (UnsupportedEncodingException e3) {
                    year = new String(buf, 93, 4).trim();
                    // TODO: handle exception
                }

                try {
                    reamrk = new String(buf, 97, 28, "gbk").trim();
                } catch (UnsupportedEncodingException e4) {
                    // TODO: handle exception
                    reamrk = new String(buf, 97, 28).trim();
                }

            }
        }

        //

        // get the time len

        model.setSongName(songName);
        model.setSingerName(singerName);
        model.setAblumName(ablum);
        model.setFile(musicFile.getAbsolutePath());
        model.setRemark("");
        Log.d(LOG_TAG, String.format("scaned music file[%s],album name[%s],song name[%s],singer name[%s]",
                model.getFile(), model.getAblumName(), model.getSingerName(), model.getSingerName()));

        mSongs.add(model);

        return model;
    } catch (IOException e) {
        // TODO: handle exception
        e.printStackTrace();
    }
    return model;
}

From source file:com.clutch.ClutchStats.java

public ArrayList<StatRow> getLogs() {
    SQLiteDatabase db = getReadableDatabase();
    String[] args = {};//from   www  . j  a  v  a2  s. c om
    ArrayList<StatRow> res = new ArrayList<StatRow>();
    Cursor cur = db.rawQuery("SELECT uuid, ts, action, data FROM stats ORDER BY ts", args);
    cur.moveToFirst();
    while (!cur.isAfterLast()) {
        String uuid = cur.getString(0);
        double ts = cur.getDouble(1);
        String action = cur.getString(2);
        JSONObject data;
        try {
            data = new JSONObject(cur.getString(3));
        } catch (JSONException e) {
            Log.w(TAG, "Could not serialize to JSON: " + cur.getString(3));
            cur.moveToNext();
            continue;
        }
        res.add(new StatRow(uuid, ts, action, data));
        cur.moveToNext();
    }
    db.close();
    return res;
}

From source file:edu.stanford.mobisocial.dungbeetle.DBIdentityProvider.java

public DBIdentityProvider(DBHelper helper) {
    mHelper = helper;/* w  w w  .ja  v a 2  s . c  o m*/
    helper.addRef();
    mUnclosedException = new Exception("Finalized without close being called. Created at...");
    Cursor c = mHelper.getReadableDatabase().rawQuery("SELECT * FROM " + MyInfo.TABLE, new String[] {});
    try {
        if (!c.moveToFirst()) {
            throw new IllegalStateException("Missing my_info entry!");
        }

        mPubKeyString = c.getString(c.getColumnIndexOrThrow(MyInfo.PUBLIC_KEY));
        mPubKey = RSACrypto.publicKeyFromString(mPubKeyString);
        mPrivKey = RSACrypto.privateKeyFromString(c.getString(c.getColumnIndexOrThrow(MyInfo.PRIVATE_KEY)));
        mName = c.getString(c.getColumnIndexOrThrow(MyInfo.NAME));
        mEmail = c.getString(c.getColumnIndexOrThrow(MyInfo.EMAIL));
        mPubKeyTag = personIdForPublicKey(mPubKey);

        Log.d(TAG, c.getCount() + " public keys");
    } finally {
        c.close();
    }
}