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:com.zrlh.llkc.funciton.Http_Utility.java

/**
 * Get a HttpClient object which is setting correctly .
 * /*from   w  w w .java2  s  .c om*/
 * @param context
 *            : context of activity
 * @return HttpClient: HttpClient object
 */
public static HttpClient getHttpClient(Context context) {
    BasicHttpParams httpParameters = new BasicHttpParams();
    // Set the default socket timeout (SO_TIMEOUT) // in
    // milliseconds which is the timeout for waiting for data.
    HttpConnectionParams.setConnectionTimeout(httpParameters, Http_Utility.SET_CONNECTION_TIMEOUT);
    HttpConnectionParams.setSoTimeout(httpParameters, Http_Utility.SET_SOCKET_TIMEOUT);
    HttpClient client = new DefaultHttpClient(httpParameters);
    WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
    WifiInfo info = wifiManager.getConnectionInfo();
    if (!wifiManager.isWifiEnabled() || -1 == info.getNetworkId()) {
        // ??APN?
        Uri uri = Uri.parse("content://telephony/carriers/preferapn");
        Cursor mCursor = context.getContentResolver().query(uri, null, null, null, null);
        if (mCursor != null && mCursor.moveToFirst()) {
            // ???
            String proxyStr = mCursor.getString(mCursor.getColumnIndex("proxy"));
            if (proxyStr != null && proxyStr.trim().length() > 0) {
                HttpHost proxy = new HttpHost(proxyStr, 80);
                client.getParams().setParameter(ConnRouteParams.DEFAULT_PROXY, proxy);
            }
            mCursor.close();
        }
    }
    return client;
}

From source file:com.smarthome.deskclock.Alarms.java

public static Alarm calculateNextAlert(final Context context) {
    Alarm alarm = null;/*w  w w . j av  a 2 s. c  om*/
    long minTime = Long.MAX_VALUE;
    long now = System.currentTimeMillis();
    Cursor cursor = getFilteredAlarmsCursor(context.getContentResolver());
    if (cursor != null) {
        if (cursor.moveToFirst()) {
            do {
                Alarm a = new Alarm(cursor);
                // A time of 0 indicates this is a repeating alarm, so
                // calculate the time to get the next alert.
                if (a.time == 0) {
                    a.time = calculateAlarm(a);
                } else if (a.time < now) {
                    Log.v("Disabling expired alarm set for " + Log.formatTime(a.time));
                    // Expired alarm, disable it and move along.
                    enableAlarmInternal(context, a, false);
                    continue;
                }
                if (a.time < minTime) {
                    minTime = a.time;
                    alarm = a;
                }
            } while (cursor.moveToNext());
        }
        cursor.close();
    }
    return alarm;
}

From source file:com.smarthome.deskclock.Alarms.java

/**
 * Disables non-repeating alarms that have passed.  Called at
 * boot./*from  w  ww.j  a v  a2s  .  co m*/
 */
public static void disableExpiredAlarms(final Context context) {
    Cursor cur = getFilteredAlarmsCursor(context.getContentResolver());
    long now = System.currentTimeMillis();

    if (cur.moveToFirst()) {
        do {
            Alarm alarm = new Alarm(cur);
            // A time of 0 means this alarm repeats. If the time is
            // non-zero, check if the time is before now.
            if (alarm.time != 0 && alarm.time < now) {
                Log.v("Disabling expired alarm set for " + Log.formatTime(alarm.time));
                enableAlarmInternal(context, alarm, false);
            }
        } while (cur.moveToNext());
    }
    cur.close();
}

From source file:org.zoumbox.mh_dla_notifier.sp.PublicScriptsProxy.java

protected static int computeRequestCount(Context context, ScriptCategory category, String trollId) {

    MhDlaSQLHelper helper = new MhDlaSQLHelper(context);
    SQLiteDatabase database = helper.getReadableDatabase();

    Calendar instance = Calendar.getInstance();
    instance.add(Calendar.HOUR_OF_DAY, -24);
    Date sinceDate = instance.getTime();

    Cursor cursor = database.rawQuery(SQL_COUNT,
            new String[] { trollId, category.name(), "" + sinceDate.getTime() });
    int result = 0;
    if (cursor.getCount() > 0) {
        cursor.moveToFirst();
        result = cursor.getInt(0);//w  w w. j ava  2 s. c om
    }

    cursor.close();
    database.close();

    String format = "Quota for category %s and troll=%s since '%s' is: %d";
    String message = String.format(format, category, trollId, sinceDate, result);
    Log.d(TAG, message);

    return result;
}

From source file:Main.java

public static Cursor getContactCursor(ContentResolver contactHelper, String startsWith) {
    String[] projection = { ContactsContract.CommonDataKinds.Phone._ID,
            ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
            ContactsContract.CommonDataKinds.Phone.NUMBER };

    Cursor cur = null;
    try {/*from w  ww . j a va2  s  .c o  m*/
        if (startsWith != null && !startsWith.equals("")) {
            cur = contactHelper.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, projection,
                    ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " like \"" + startsWith + "%\"", null,
                    ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC");
        } else {
            cur = contactHelper.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, projection, null,
                    null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC");
        }
        cur.moveToFirst();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return cur;
}

From source file:com.zrlh.llkc.funciton.Http_Utility.java

public static HttpClient getNewHttpClient(Context context) {
    try {//ww w .j  a va2 s .  co m
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);

        SSLSocketFactory sf = new MySSLSocketFactory(trustStore);
        sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

        HttpParams params = new BasicHttpParams();

        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);

        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        registry.register(new Scheme("https", sf, 443));

        ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);
        // Set the default socket timeout (SO_TIMEOUT) // in
        // milliseconds which is the timeout for waiting for data.
        HttpConnectionParams.setConnectionTimeout(params, Http_Utility.SET_CONNECTION_TIMEOUT);
        HttpConnectionParams.setSoTimeout(params, Http_Utility.SET_SOCKET_TIMEOUT);
        HttpClient client = new DefaultHttpClient(ccm, params);

        WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        WifiInfo info = wifiManager.getConnectionInfo();
        if (!wifiManager.isWifiEnabled() || -1 == info.getNetworkId()) {
            // ??APN?
            Uri uri = Uri.parse("content://telephony/carriers/preferapn");
            Cursor mCursor = context.getContentResolver().query(uri, null, null, null, null);
            if (mCursor != null && mCursor.moveToFirst()) {
                // ???
                String proxyStr = mCursor.getString(mCursor.getColumnIndex("proxy"));
                if (proxyStr != null && proxyStr.trim().length() > 0) {
                    HttpHost proxy = new HttpHost(proxyStr, 80);
                    client.getParams().setParameter(ConnRouteParams.DEFAULT_PROXY, proxy);
                }
                mCursor.close();
            }
        }
        return client;
    } catch (Exception e) {
        return new DefaultHttpClient();
    }
}

From source file:org.zoumbox.mh_dla_notifier.sp.PublicScriptsProxy.java

public static Date geLastUpdate(Context context, PublicScript script, String trollId) {

    MhDlaSQLHelper helper = new MhDlaSQLHelper(context);
    SQLiteDatabase database = helper.getReadableDatabase();

    Cursor cursor = database.rawQuery(SQL_LAST_UPDATE,
            new String[] { trollId, script.name(), MhDlaSQLHelper.STATUS_SUCCESS });
    Date result = null;//from w ww  .  java  2s  . c  om
    if (cursor.getCount() > 0) {
        cursor.moveToFirst();
        long resultTimestamp = cursor.getLong(0);
        result = new Date(resultTimestamp);
    }

    cursor.close();
    database.close();

    String format = "Last update for category %s (script=%s) and troll=%s is: '%s'";
    String message = String.format(format, script.category, script, trollId, result);
    Log.d(TAG, message);

    return result;
}

From source file:edu.stanford.mobisocial.dungbeetle.model.DbObject.java

/**
 * @param v the view to bind//w w w. j av a  2 s  .  co m
 * @param context standard activity context
 * @param c the cursor source for the object in the db object table.
 * Must include _id in the projection.
 * 
 * @param allowInteractions controls whether the bound view is
 * allowed to intercept touch events and do its own processing.
 */
public static void bindView(View v, final Context context, Cursor cursor, boolean allowInteractions) {
    TextView nameText = (TextView) v.findViewById(R.id.name_text);
    ViewGroup frame = (ViewGroup) v.findViewById(R.id.object_content);
    frame.removeAllViews();

    // make sure we have all the columns we need
    Long objId = cursor.getLong(cursor.getColumnIndexOrThrow(DbObj.COL_ID));
    String[] projection = null;
    String selection = DbObj.COL_ID + " = ?";
    String[] selectionArgs = new String[] { Long.toString(objId) };
    String sortOrder = null;
    Cursor c = context.getContentResolver().query(DbObj.OBJ_URI, projection, selection, selectionArgs,
            sortOrder);
    if (!c.moveToFirst()) {
        Log.w(TAG, "could not find obj " + objId);
        c.close();
        return;
    }
    DbObj obj = App.instance().getMusubi().objForCursor(c);
    if (obj == null) {
        nameText.setText("Failed to access database.");
        Log.e("DbObject", "cursor was null for bindView of DbObject");
        return;
    }
    DbUser sender = obj.getSender();
    Long timestamp = c.getLong(c.getColumnIndexOrThrow(DbObj.COL_TIMESTAMP));
    Long hash = obj.getHash();
    short deleted = c.getShort(c.getColumnIndexOrThrow(DELETED));
    String feedName = obj.getFeedName();
    String type = obj.getType();
    Date date = new Date(timestamp);
    c.close();
    c = null;

    if (sender == null) {
        nameText.setText("Message from unknown contact.");
        return;
    }
    nameText.setText(sender.getName());

    final ImageView icon = (ImageView) v.findViewById(R.id.icon);
    if (sViewProfileAction == null) {
        sViewProfileAction = new OnClickViewProfile((Activity) context);
    }
    icon.setTag(sender.getLocalId());
    if (allowInteractions) {
        icon.setOnClickListener(sViewProfileAction);
        v.setTag(objId);
    }
    icon.setImageBitmap(sender.getPicture());

    if (deleted == 1) {
        v.setBackgroundColor(sDeletedColor);
    } else {
        v.setBackgroundColor(Color.TRANSPARENT);
    }

    TextView timeText = (TextView) v.findViewById(R.id.time_text);
    timeText.setText(RelativeDate.getRelativeDate(date));

    frame.setTag(objId); // TODO: error prone! This is database id
    frame.setTag(R.id.object_entry, cursor.getPosition()); // this is cursor id
    FeedRenderer renderer = DbObjects.getFeedRenderer(type);
    if (renderer != null) {
        renderer.render(context, frame, obj, allowInteractions);
    }

    if (!allowInteractions) {
        v.findViewById(R.id.obj_attachments_icon).setVisibility(View.GONE);
        v.findViewById(R.id.obj_attachments).setVisibility(View.GONE);
    } else {
        if (!MusubiBaseActivity.isDeveloperModeEnabled(context)) {
            v.findViewById(R.id.obj_attachments_icon).setVisibility(View.GONE);
            v.findViewById(R.id.obj_attachments).setVisibility(View.GONE);
        } else {
            ImageView attachmentCountButton = (ImageView) v.findViewById(R.id.obj_attachments_icon);
            TextView attachmentCountText = (TextView) v.findViewById(R.id.obj_attachments);
            attachmentCountButton.setVisibility(View.VISIBLE);

            if (hash == 0) {
                attachmentCountButton.setVisibility(View.GONE);
            } else {
                //int color = DbObject.colorFor(hash);
                boolean selfPost = false;
                DBHelper helper = new DBHelper(context);
                try {
                    Cursor attachments = obj.getSubfeed().query("type=?", new String[] { LikeObj.TYPE });
                    try {
                        attachmentCountText.setText("+" + attachments.getCount());

                        if (attachments.moveToFirst()) {
                            while (!attachments.isAfterLast()) {
                                if (attachments.getInt(attachments.getColumnIndex(CONTACT_ID)) == -666) {
                                    selfPost = true;
                                    break;
                                }
                                attachments.moveToNext();

                            }
                        }
                    } finally {
                        attachments.close();
                    }
                } finally {
                    helper.close();
                }
                if (selfPost) {
                    attachmentCountButton.setImageResource(R.drawable.ic_menu_love_red);
                } else {
                    attachmentCountButton.setImageResource(R.drawable.ic_menu_love);
                }
                attachmentCountText.setTag(R.id.object_entry, hash);
                attachmentCountText.setTag(R.id.feed_label, Feed.uriForName(feedName));
                attachmentCountText.setOnClickListener(LikeListener.getInstance(context));
            }
        }
    }
}

From source file:org.zoumbox.mh_dla_notifier.sp.PublicScriptsProxy.java

public static Map<PublicScript, Date> geLastUpdates(Context context, String trollId,
        Set<PublicScript> scripts) {

    MhDlaSQLHelper helper = new MhDlaSQLHelper(context);
    SQLiteDatabase database = helper.getReadableDatabase();

    Map<PublicScript, Date> result = new HashMap<PublicScript, Date>();

    for (PublicScript script : scripts) {

        Cursor cursor = database.rawQuery(SQL_LAST_UPDATE,
                new String[] { trollId, script.name(), MhDlaSQLHelper.STATUS_SUCCESS });
        Date lastUpdate = null;/*from  w w  w . j  a  v a2  s  .  c  o  m*/
        if (cursor.getCount() > 0) {
            cursor.moveToFirst();
            long resultTimestamp = cursor.getLong(0);
            lastUpdate = new Date(resultTimestamp);
        }

        result.put(script, lastUpdate);
        cursor.close();
    }
    database.close();

    String format = "Last updates for troll=%s are: '%s'";
    String message = String.format(format, trollId, result);
    Log.i(TAG, message);

    return result;
}

From source file:foam.zizim.android.BoskoiService.java

public static CategoriesData[] getCategoriesDetails(String categoryIds) {

    String[] categories = categoryIds.split(",");
    CategoriesData result[] = new CategoriesData[categories.length];

    int i = 0;//from  w w  w. ja v a  2s  . com

    for (String categoryId : categories) {
        Cursor cursor = BoskoiApplication.mDb.fetchCategoriesById(Integer.parseInt(categoryId));

        if (cursor.moveToFirst()) {
            int titleIndex = cursor.getColumnIndexOrThrow(BoskoiDatabase.CATEGORY_TITLE);
            int titleNL = cursor.getColumnIndexOrThrow(BoskoiDatabase.CATEGORY_TITLE_NL);
            int titleLA = cursor.getColumnIndexOrThrow(BoskoiDatabase.CATEGORY_TITLE_LA);
            int idIndex = cursor.getColumnIndexOrThrow(BoskoiDatabase.CATEGORY_ID);
            int parentId = cursor.getColumnIndexOrThrow(BoskoiDatabase.CATEGORY_PARENT_ID);
            int color = cursor.getColumnIndexOrThrow(BoskoiDatabase.CATEGORY_COLOR);
            int desc = cursor.getColumnIndexOrThrow(BoskoiDatabase.CATEGORY_DESC);

            CategoriesData cat = new CategoriesData();
            cat.setCategoryId(cursor.getInt(idIndex));
            cat.setCategoryTitle(cursor.getString(titleIndex));
            cat.setCategoryTitleNL(cursor.getString(titleNL));
            cat.setCategoryTitleLA(cursor.getString(titleLA));
            cat.setCategoryParentId(cursor.getInt(parentId));
            cat.setCategoryColor(cursor.getString(color));
            cat.setCategoryDescription(cursor.getString(desc));

            result[i] = cat;

            i++;
        }

        cursor.close();
    }
    return result;
}