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.polyvi.xface.extension.telephony.XTelephonyExt.java

/**
 * Cursor?JSON/*from  ww  w  .  j a  v  a  2s .  c om*/
 */
private JSONObject getCallRecordFromCursor(Cursor cursor) {
    String callRecordId = cursor.getString(cursor.getColumnIndex(CallLog.Calls._ID));
    String callRecordAddress = cursor.getString(cursor.getColumnIndex(CallLog.Calls.NUMBER));
    String callRecordName = cursor.getString(cursor.getColumnIndex(CallLog.Calls.CACHED_NAME));
    int callRecordTypeInt = cursor.getInt(cursor.getColumnIndex(CallLog.Calls.TYPE));
    long startTime = cursor.getLong(cursor.getColumnIndex(CallLog.Calls.DATE));
    long durationSeconds = cursor.getLong(cursor.getColumnIndex(CallLog.Calls.DURATION));
    JSONObject callRecord = new JSONObject();
    try {
        callRecord.put("callRecordId", callRecordId);
        callRecord.put("callRecordAddress", callRecordAddress);
        callRecord.put("callRecordName", callRecordName);
        callRecord.put("callRecordType", getCallRecordTypeStr(callRecordTypeInt));
        callRecord.put("startTime", startTime);
        callRecord.put("durationSeconds", durationSeconds);
    } catch (JSONException e) {
        XLog.e(CLASS_NAME, e.toString());
    }
    return callRecord;
}

From source file:com.prey.json.actions.RecentCallsList.java

public HttpDataService run(Context ctx, List<ActionResult> lista, JSONObject parameters) {

    HttpDataService data = new HttpDataService("recent_calls_list");
    HashMap<String, String> parametersMap = new HashMap<String, String>();

    final String[] projection = null;
    final String selection = null;
    final String[] selectionArgs = null;
    final String sortOrder = android.provider.CallLog.Calls.DATE + " DESC";
    Cursor cursor = null;
    try {//from   w w w.j a v  a  2s. c  o  m
        cursor = ctx.getContentResolver().query(Uri.parse("content://call_log/calls"), projection, selection,
                selectionArgs, sortOrder);
        int i = 0;
        while (cursor.moveToNext()) {
            // String callLogID =
            // cursor.getString(cursor.getColumnIndex(android.provider.CallLog.Calls._ID));
            String callNumber = cursor.getString(cursor.getColumnIndex(android.provider.CallLog.Calls.NUMBER));
            String callDate = cursor.getString(cursor.getColumnIndex(android.provider.CallLog.Calls.DATE));
            String callType = cursor.getString(cursor.getColumnIndex(android.provider.CallLog.Calls.TYPE));
            // String isCallNew =
            // cursor.getString(cursor.getColumnIndex(android.provider.CallLog.Calls.NEW));
            String duration = cursor.getString(cursor.getColumnIndex(android.provider.CallLog.Calls.DURATION));
            parametersMap.put(i + "][number", callNumber);
            parametersMap.put(i + "][date", callDate);
            parametersMap.put(i + "][type", callType);
            parametersMap.put(i + "][duration", duration);
            i++;
        }
        data.setList(true);
        data.addDataListAll(parametersMap);

    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        cursor.close();
    }

    return data;
}

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

public static synchronized long isReadMsg(String msgId) {
    long count = 0;
    String sql = "select * from " + DatabaseHelper.TABLES_NAME_IM_MESSAGE + " where msgid = '" + msgId + "'";
    Cursor cursor = getInstance().sqliteDB().rawQuery(sql, null);
    if (cursor != null && cursor.getCount() > 0) {
        if (cursor.moveToFirst()) {
            count = cursor.getInt(cursor.getColumnIndex("readcount"));
            cursor.close();// w  ww.j a va  2s. c  o  m
            cursor = null;
        }
    }
    return count;
}

From source file:com.hybris.mobile.lib.commerce.loader.ContentAdapterLoader.java

@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {

    if (mOnRequestListener != null) {
        mOnRequestListener.afterRequestBeforeResponse();
    }/*from w ww .ja  va 2  s.  c om*/

    boolean isDataSynced = false;

    if (data != null) {
        Log.i(TAG, "Loader finished to load " + data.getCount() + " result(s)");

        mCursorAdapter.swapCursor(data);

        if (data.getCount() > 0) {
            isDataSynced = data.getInt(data.getColumnIndex(
                    CatalogContract.DataBaseDataSimple.ATT_STATUS)) == CatalogContract.SyncStatus.UPTODATE
                            .getValue();
        }

    } else {
        isDataSynced = true;
    }

    if (mOnRequestListener != null) {
        mOnRequestListener.afterRequest(isDataSynced);
    }

}

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

/**
 * get the music info/*  w  ww. j  a  v a  2 s  .co m*/
 * 
 * @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.yuntongxun.ecdemo.storage.IMessageSqlManager.java

public static String getMsgReadStatus(String msgId) {
    String sql = "select * from " + DatabaseHelper.TABLES_NAME_IM_MESSAGE + " where msgid = '" + msgId + "'";
    Cursor cursor = getInstance().sqliteDB().rawQuery(sql, null);
    if (cursor != null && cursor.getCount() > 0) {
        if (cursor.moveToFirst()) {
            String text = cursor.getString(cursor.getColumnIndex("isRead"));
            cursor.close();//from  w w w. j ava 2s.  co  m
            cursor = null;
            return text;
        }
    }
    return "0";
}

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

/**
 * @return//from   ww  w . j  av a 2  s .  c om
 */
public static int getMaxVersion() {
    String sql = "select max(version) as maxVersion from " + DatabaseHelper.TABLES_NAME_IM_MESSAGE;
    Cursor cursor = getInstance().sqliteDB().rawQuery(sql, null);
    if (cursor != null && cursor.getCount() > 0) {
        if (cursor.moveToFirst()) {
            int maxVersion = cursor.getInt(cursor.getColumnIndex("maxVersion"));
            cursor.close();
            ;
            return maxVersion;
        }
    }
    return 0;
}

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

/**
 * ????//from   w ww .  ja  v  a 2 s . c  o  m
 *
 * @return
 */
public static boolean isFireMsg(String msgId) {
    String sql = "select * from " + DatabaseHelper.TABLES_NAME_IM_MESSAGE + " where msgid = '" + msgId + "'";
    Cursor cursor = getInstance().sqliteDB().rawQuery(sql, null);
    if (cursor != null && cursor.getCount() > 0) {
        if (cursor.moveToFirst()) {
            String text = cursor.getString(cursor.getColumnIndex("text"));
            cursor.close();
            cursor = null;
            return "fireMessage".equals(text);
        }
    }
    return false;
}

From source file:com.ibm.commerce.worklight.android.search.SearchSuggestionsProvider.java

/**
 * Performs the search by projections and selection arguments
 * @param uri The URI to be used// w w  w  .j  a va 2s .c o m
 * @param projection The string array for the search
 * @param selection The selection string
 * @param selectionArgs The selection arguments
 * @param sortOrder The sort order
 * @return The cursor containing the suggestions
 */
@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
    final String METHOD_NAME = CLASS_NAME + ".query()";
    boolean loggingEnabled = Log.isLoggable(LOG_TAG, Log.DEBUG);
    if (loggingEnabled) {
        Log.d(METHOD_NAME, "ENTRY");
    }

    int id = 1;
    MatrixCursor suggestionCursor = new MatrixCursor(COLUMNS);
    Cursor recentSearchCursor = null;

    try {
        recentSearchCursor = super.query(uri, projection, selection, selectionArgs, sortOrder);
        // get search history
        if (recentSearchCursor != null) {
            int searchTermIndex = recentSearchCursor.getColumnIndex(SearchManager.SUGGEST_COLUMN_TEXT_1);
            while (recentSearchCursor.moveToNext() && id <= MAX_RECENT_TERM) {
                suggestionCursor.addRow(createRecentRow(id, recentSearchCursor.getString(searchTermIndex)));
                id++;
            }
        }
    } finally {
        if (recentSearchCursor != null) {
            recentSearchCursor.close();
            recentSearchCursor = null;
        }
    }

    // get search suggestion
    if (selectionArgs[0] != null && !selectionArgs[0].equals("")) {
        List<String> suggestionList = getSearchTermSuggestions(selectionArgs[0]);
        if (suggestionList != null) {
            for (String aSuggestion : suggestionList) {
                suggestionCursor.addRow(createSuggestionRow(id, aSuggestion));
                id++;
            }
        }
    }

    if (loggingEnabled) {
        Log.d(METHOD_NAME, "EXIT");
    }

    return suggestionCursor;
}

From source file:com.caju.uheer.app.services.infrastructure.ContactablesLoaderCallbacks.java

@Override
public Loader<Cursor> onCreateLoader(int loaderIndex, Bundle args) {
    String query = "";
    JSONArray nearbyUsers = new JSONArray();

    Uri uri = Uri.withAppendedPath(CommonDataKinds.Contactables.CONTENT_FILTER_URI, query);

    // Sort results such that rows for the same contact stay together.
    String sortBy = CommonDataKinds.Contactables.LOOKUP_KEY;

    CursorLoader cursorLoader = new CursorLoader(mContext, // Context
            uri, // URI representing the table/resource to be queried
            null, // projection - the list of columns to return.  Null means "all"
            null, // selection - Which rows to return (condition rows must match)
            null, // selection args - can be provided separately and subbed into selection.
            sortBy); // string specifying sort order

    try {/*from   w ww. j a va 2 s . com*/
        // Parsing the JSON received from server.
        String nearbyUsersString = args.getString("jsonString");
        nearbyUsers = new JSONObject(nearbyUsersString).getJSONArray("nearbyUsers");
    } catch (JSONException e) {
        e.printStackTrace();
    }

    for (int i = 0; i < nearbyUsers.length(); i++) {
        //            Log.d("json", "" + nearbyUsers.getJSONObject(0).get("email"));
        try {
            query = nearbyUsers.getJSONObject(i).getString("email");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        //            query = args.getString("query");

        uri = Uri.withAppendedPath(CommonDataKinds.Contactables.CONTENT_FILTER_URI, query);

        cursorLoader = new CursorLoader(mContext, // Context
                uri, // URI representing the table/resource to be queried
                null, // projection - the list of columns to return.  Null means "all"
                null, // selection - Which rows to return (condition rows must match)
                null, // selection args - can be provided separately and subbed into selection.
                sortBy); // string specifying sort order

        Cursor cursor = cursorLoader.loadInBackground();

        Toast.makeText(mContext, "entrei no cursorLoader", Toast.LENGTH_LONG).show();
        if (cursor.getCount() == 0) {
            return cursorLoader;
        }

        int nameColumnIndex = cursor.getColumnIndex(CommonDataKinds.Contactables.DISPLAY_NAME);
        int lookupColumnIndex = cursor.getColumnIndex(CommonDataKinds.Contactables.LOOKUP_KEY);

        cursor.moveToFirst();

        String lookupKey = "";
        String displayName = "";
        do {
            String currentLookupKey = cursor.getString(lookupColumnIndex);
            if (!lookupKey.equals(currentLookupKey)) {
                displayName = cursor.getString(nameColumnIndex);
                lookupKey = currentLookupKey;
            }
        } while (cursor.moveToNext());

        Toast.makeText(mContext, displayName, Toast.LENGTH_LONG).show();
        try {
            JSONObject jobj = new JSONObject().put("name", displayName);
            if (!nearbyUsers.getJSONObject(i).has("channel")) {
                double[] geoPoint = new double[2];
                geoPoint[0] = nearbyUsers.getJSONObject(i).getJSONObject("geoPoint").getDouble("latitude");
                geoPoint[1] = nearbyUsers.getJSONObject(i).getJSONObject("geoPoint").getDouble("longitude");
                jobj.put("lat", geoPoint[0]);
                jobj.put("lon", geoPoint[1]);
            } else {
                String channel = nearbyUsers.getJSONObject(i).getString("channel");
                jobj.put("channel", channel);
            }
            usersFound.put(jobj);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    return cursorLoader;
}