Example usage for android.database Cursor getPosition

List of usage examples for android.database Cursor getPosition

Introduction

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

Prototype

int getPosition();

Source Link

Document

Returns the current position of the cursor in the row set.

Usage

From source file:it.imwatch.nfclottery.MainActivity.java

/**
 * Draws a winner from the stored contacts in the ContentProvider
 * that haven't already won.//w w  w. ja v a  2  s. c  o  m
 */
public void drawWinner() {
    ContentResolver cr = getContentResolver();
    Cursor c = cr.query(NFCMLContent.Geeks.CONTENT_URI, NFCMLContent.Geeks.PROJECTION,
            NFCMLContent.Geeks.Columns.TIMEWINNER.getName() + "=0", null, null);

    int count = c != null ? c.getCount() : 0;
    if (count == 0) {
        // There is nobody to draw from
        if (c != null) {
            c.close();
        }

        showCroutonNao(getString(R.string.no_more_nonwinning_contacts), Style.ALERT);
        return;
    }

    int winnerPosition = (new Random()).nextInt(count);
    c.moveToPosition(winnerPosition);

    String winnerEmail = c.getString(NFCMLContent.Geeks.Columns.EMAIL.getIndex());
    String winnerName = c.getString(NFCMLContent.Geeks.Columns.NAME.getIndex());

    if (DEBUG) {
        Log.d(TAG, String.format("The winner is %s (position: %d)", DataHelper.cleanupSeparators(winnerEmail),
                c.getPosition()));
    }
    c.close();

    showWinner(winnerPosition, winnerEmail, winnerName);
}

From source file:com.enadein.carlogbook.adapter.FuelRateAdapter.java

@Override
public void bindView(View view, Context context, Cursor cursor) {
    FuelRateViewBean bean = new FuelRateViewBean();
    bean.populate(cursor);/*from  w  w w  .  j  a  v a  2 s  .  c o  m*/

    FuelRateHolder holder = (FuelRateHolder) view.getTag();
    holder.logo.setBackgroundResource(R.drawable.fuel);
    holder.nameView.setText(bean.getStation() + "(" + bean.getFuelType() + ")\n");
    unitFacade.appendConsumUnit(holder.nameView, true);

    int consum = unitFacade.getConsumptionValue();
    String min = (consum == 2) ? CommonUtils.formatDistance(bean.getMinRate())
            : CommonUtils.formatFuel(bean.getMinRate(), unitFacade);
    String cur = (consum == 2) ? CommonUtils.formatDistance(bean.getRate())
            : CommonUtils.formatFuel(bean.getRate(), unitFacade);
    String max = (consum == 2) ? CommonUtils.formatDistance(bean.getMaxRate())
            : CommonUtils.formatFuel(bean.getMaxRate(), unitFacade);
    String avg = (consum == 2) ? CommonUtils.formatDistance(bean.getAvg())
            : CommonUtils.formatFuel(bean.getAvg(), unitFacade);

    holder.valueView
            .setText(cur + unitFacade.getConsumPostfix() + " (" + context.getString(R.string.last) + ")");
    holder.valueMinView
            .setText(min + unitFacade.getConsumPostfix() + " (" + context.getString(R.string.min) + ")");
    holder.valueMaxView
            .setText(max + unitFacade.getConsumPostfix() + " (" + context.getString(R.string.max) + ")");
    holder.valueAvgView
            .setText(avg + unitFacade.getConsumPostfix() + " (" + context.getString(R.string.avg) + ")");

    int pos = cursor.getPosition();
    CommonUtils.runAnimation(mlastPos, pos, view, UnitFacade.animSize);
    mlastPos = pos;
}

From source file:org.totschnig.myexpenses.fragment.CategoryList.java

private void setData(Cursor c, ArrayList<Integer> colors) {
    chartDisplaysSubs = c != mGroupCursor;
    ArrayList<Entry> entries1 = new ArrayList<>();
    ArrayList<String> xVals = new ArrayList<>();
    if (c != null && c.moveToFirst()) {
        do {//from  ww w  .j av  a  2 s  .  c  om
            long sum = c.getLong(c.getColumnIndex(DatabaseConstants.KEY_SUM));
            xVals.add(c.getString(c.getColumnIndex(DatabaseConstants.KEY_LABEL)));
            entries1.add(new Entry((float) sum, c.getPosition()));
        } while (c.moveToNext());
        PieDataSet ds1 = new PieDataSet(entries1, "");

        ds1.setColors(colors);
        ds1.setSliceSpace(2f);
        ds1.setDrawValues(false);
        mChart.setData(new PieData(xVals, ds1));
        mChart.getLegend().setEnabled(false);
        // undo all highlights
        mChart.highlightValues(null);
        mChart.invalidate();
    } else {
        mChart.clear();
    }
}

From source file:com.money.manager.ex.adapter.AllDataAdapter.java

@SuppressWarnings({})
@Override/*from   w w w . ja  v  a 2s .co m*/
public void bindView(View view, Context context, Cursor cursor) {
    // take a pointer of object UI
    LinearLayout linDate = (LinearLayout) view.findViewById(R.id.linearLayoutDate);
    TextView txtDay = (TextView) view.findViewById(R.id.textViewDay);
    TextView txtMonth = (TextView) view.findViewById(R.id.textViewMonth);
    TextView txtYear = (TextView) view.findViewById(R.id.textViewYear);
    TextView txtStatus = (TextView) view.findViewById(R.id.textViewStatus);
    TextView txtAmount = (TextView) view.findViewById(R.id.textViewAmount);
    TextView txtPayee = (TextView) view.findViewById(R.id.textViewPayee);
    TextView txtAccountName = (TextView) view.findViewById(R.id.textViewAccountName);
    TextView txtCategorySub = (TextView) view.findViewById(R.id.textViewCategorySub);
    TextView txtNotes = (TextView) view.findViewById(R.id.textViewNotes);
    TextView txtBalance = (TextView) view.findViewById(R.id.textViewBalance);
    // header index
    if (!mHeadersAccountIndex.containsKey(cursor.getInt(cursor.getColumnIndex(ACCOUNTID)))) {
        mHeadersAccountIndex.put(cursor.getInt(cursor.getColumnIndex(ACCOUNTID)), cursor.getPosition());
    }
    // write status
    txtStatus.setText(mApplication.getStatusAsString(cursor.getString(cursor.getColumnIndex(STATUS))));
    // color status
    int colorBackground = getBackgroundColorFromStatus(cursor.getString(cursor.getColumnIndex(STATUS)));
    linDate.setBackgroundColor(colorBackground);
    txtStatus.setTextColor(Color.GRAY);
    // date group
    try {
        Date date = new SimpleDateFormat("yyyy-MM-dd").parse(cursor.getString(cursor.getColumnIndex(DATE)));
        txtMonth.setText(new SimpleDateFormat("MMM").format(date));
        txtYear.setText(new SimpleDateFormat("yyyy").format(date));
        txtDay.setText(new SimpleDateFormat("dd").format(date));
    } catch (ParseException e) {
        Log.e(AllDataAdapter.class.getSimpleName(), e.getMessage());
    }
    // take transaction amount
    double amount = cursor.getDouble(cursor.getColumnIndex(AMOUNT));
    // set currency id
    setCurrencyId(cursor.getInt(cursor.getColumnIndex(CURRENCYID)));
    // manage transfer and change amount sign
    if ((cursor.getString(cursor.getColumnIndex(TRANSACTIONTYPE)) != null)
            && (Constants.TRANSACTION_TYPE_TRANSFER
                    .equalsIgnoreCase(cursor.getString(cursor.getColumnIndex(TRANSACTIONTYPE))))) {
        if (getAccountId() != cursor.getInt(cursor.getColumnIndex(TOACCOUNTID))) {
            amount = -(amount); // -total
        } else if (getAccountId() == cursor.getInt(cursor.getColumnIndex(TOACCOUNTID))) {
            amount = cursor.getDouble(cursor.getColumnIndex(TOTRANSAMOUNT)); // to account = account
            setCurrencyId(cursor.getInt(cursor.getColumnIndex(TOCURRENCYID)));
        }
    }
    // check amount sign
    CurrencyUtils currencyUtils = new CurrencyUtils(mContext);
    txtAmount.setText(currencyUtils.getCurrencyFormatted(getCurrencyId(), amount));
    // text color amount
    if (Constants.TRANSACTION_TYPE_TRANSFER
            .equalsIgnoreCase(cursor.getString(cursor.getColumnIndex(TRANSACTIONTYPE)))) {
        txtAmount.setTextColor(Color.GRAY);
    } else if (Constants.TRANSACTION_TYPE_DEPOSIT
            .equalsIgnoreCase(cursor.getString(cursor.getColumnIndex(TRANSACTIONTYPE)))) {
        txtAmount.setTextColor(mCore.resolveColorAttribute(R.attr.holo_green_color_theme));
    } else {
        txtAmount.setTextColor(mCore.resolveColorAttribute(R.attr.holo_red_color_theme));
    }
    // compose payee description
    txtPayee.setText(cursor.getString(cursor.getColumnIndex(PAYEE)));
    // compose account name
    if (isShowAccountName()) {
        if (mHeadersAccountIndex.containsValue(cursor.getPosition())) {
            txtAccountName.setText(cursor.getString(cursor.getColumnIndex(ACCOUNTNAME)));
            txtAccountName.setVisibility(View.VISIBLE);
        } else {
            txtAccountName.setVisibility(View.GONE);
        }
    } else {
        txtAccountName.setVisibility(View.GONE);
    }
    // write ToAccountName
    if ((!TextUtils.isEmpty(cursor.getString(cursor.getColumnIndex(TOACCOUNTNAME))))) {
        if (getAccountId() != cursor.getInt(cursor.getColumnIndex(TOACCOUNTID)))
            txtPayee.setText(cursor.getString(cursor.getColumnIndex(TOACCOUNTNAME)));
        else
            txtPayee.setText(cursor.getString(cursor.getColumnIndex(ACCOUNTNAME)));
    }
    // compose category description
    String categorySub = cursor.getString(cursor.getColumnIndex(CATEGORY));
    // check sub category
    if (!(TextUtils.isEmpty(cursor.getString(cursor.getColumnIndex(SUBCATEGORY))))) {
        categorySub += " : <i>" + cursor.getString(cursor.getColumnIndex(SUBCATEGORY)) + "</i>";
    }
    // write category/subcategory format html
    if (!TextUtils.isEmpty(categorySub)) {
        txtCategorySub.setText(Html.fromHtml(categorySub));
    } else {
        txtCategorySub.setText("");
    }
    // notes
    if (!TextUtils.isEmpty(cursor.getString(cursor.getColumnIndex(NOTES)))) {
        txtNotes.setText(
                Html.fromHtml("<small>" + cursor.getString(cursor.getColumnIndex(NOTES)) + "</small>"));
        txtNotes.setVisibility(View.VISIBLE);
    } else {
        txtNotes.setVisibility(View.GONE);
    }
    // check if item is checked
    if (mCheckedPosition.get(cursor.getPosition(), false)) {
        view.setBackgroundResource(R.color.holo_blue_light);
    } else {
        view.setBackgroundResource(android.R.color.transparent);
    }
    // balance account or days left
    if (mTypeCursor == TypeCursor.ALLDATA) {
        if (isShowBalanceAmount() && getDatabase() != null) {
            int transId = cursor.getInt(cursor.getColumnIndex(ID));
            // create thread for calculate balance amount
            BalanceAmount balanceAmount = new BalanceAmount();
            balanceAmount.setAccountId(getAccountId());
            balanceAmount.setDate(cursor.getString(cursor.getColumnIndex(DATE)));
            balanceAmount.setTextView(txtBalance);
            balanceAmount.setContext(mContext);
            balanceAmount.setDatabase(getDatabase());
            balanceAmount.setTransId(transId);
            // execute thread
            balanceAmount.execute();
        } else {
            txtBalance.setVisibility(View.GONE);
        }
    } else {
        int daysLeft = cursor.getInt(cursor.getColumnIndex(QueryBillDeposits.DAYSLEFT));
        if (daysLeft == 0) {
            txtBalance.setText(R.string.inactive);
        } else {
            txtBalance.setText(Integer.toString(Math.abs(daysLeft)) + " "
                    + context.getString(daysLeft > 0 ? R.string.days_remaining : R.string.days_overdue));
        }
        txtBalance.setVisibility(View.VISIBLE);
    }
}

From source file:de.elanev.studip.android.app.frontend.news.NewsListFragment.java

public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
    if (getActivity() == null) {
        return;//from  w w  w.  ja  v  a2s .  c om
    }

    int idColumnIdx = 0;
    int titleColumnIdx = 0;

    int newsSelector = loader.getId();

    switch (newsSelector) {
    case NewsTabsAdapter.NEWS_COURSES:
        idColumnIdx = cursor.getColumnIndex(CoursesContract.Columns.Courses.COURSE_ID);

        titleColumnIdx = cursor.getColumnIndex(CoursesContract.Columns.Courses.COURSE_TITLE);

        break;
    case NewsTabsAdapter.NEWS_INSTITUTES:
        idColumnIdx = cursor.getColumnIndex(InstitutesContract.Columns.INSTITUTE_ID);

        titleColumnIdx = cursor.getColumnIndex(InstitutesContract.Columns.INSTITUTE_NAME);

        break;
    case NewsTabsAdapter.NEWS_GLOBAL:
        idColumnIdx = -1;
        titleColumnIdx = -1;
        break;
    }

    List<SectionedCursorAdapter.Section> sections = new ArrayList<SectionedCursorAdapter.Section>();
    if (idColumnIdx != -1 || titleColumnIdx != -1) {
        cursor.moveToFirst();
        String previousId = null;
        String currentId;
        while (!cursor.isAfterLast()) {

            currentId = cursor.getString(idColumnIdx);

            if (!TextUtils.equals(previousId, currentId)) {

                SectionedCursorAdapter.Section section = new SectionedCursorAdapter.Section(
                        cursor.getPosition(), cursor.getString(titleColumnIdx));

                sections.add(section);
            }
            previousId = currentId;
            cursor.moveToNext();
        }
    }

    mNewsAdapter.setSections(sections);
    mNewsAdapter.swapCursor(cursor);

    setLoadingViewVisible(false);
}

From source file:com.roamprocess1.roaming4world.ui.messages.ConversationsAdapter.java

@SuppressLint("SdCardPath")
@Override/*from   w w w .  j ava2s. co m*/
public void bindView(View view, Context context, Cursor cursor) {
    super.bindView(view, context, cursor);

    System.out.println("Conversationlist:bindView");
    final ConversationListItemViews tagView = (ConversationListItemViews) view.getTag();
    String nbr = cursor.getString(cursor.getColumnIndex(SipMessage.FIELD_FROM));
    String fromFull = cursor.getString(cursor.getColumnIndex(SipMessage.FIELD_FROM_FULL));
    String to_number = cursor.getString(cursor.getColumnIndex(SipMessage.FIELD_TO));
    int read = cursor.getInt(cursor.getColumnIndex(SipMessage.FIELD_READ));
    long date = cursor.getLong(cursor.getColumnIndex(SipMessage.FIELD_DATE));

    DBProvider db = new DBProvider();
    Cursor cr = db.allMessage(to_number, fromFull, context);
    cr.moveToLast();
    SipMessage msg1 = new SipMessage(cr);
    String lastMessage = msg1.getBodyContent();

    if (lastMessage.contains("[Offline message -") && !nbr.equals("sip:registrar@kamailio.org")) {
        System.out.println("offline message");
        String[] finalMessage = lastMessage.split("]");
        lastMessage = finalMessage[finalMessage.length - 1];
    }

    TextView txtview = (TextView) view.findViewById(R.id.subject);

    if (lastMessage.startsWith("R4WIMGTOCONTACTCHATSEND@@")) {
        txtview.setText("Image");
    } else {
        txtview.setText(lastMessage);
    }

    tagView.fromFull = fromFull;
    tagView.to = to_number;
    tagView.from = nbr;
    tagView.position = cursor.getPosition();

    /*
    Drawable background = (read == 0)?
        context.getResources().getDrawable(R.drawable.conversation_item_background_unread) :
        context.getResources().getDrawable(R.drawable.conversation_item_background_read);
            
    view.setBackgroundDrawable(background);
     */
    String number = cursor.getString(cursor.getColumnIndex(SipMessage.FIELD_FROM_FULL));
    CallerInfo info = CallerInfo.getCallerInfoFromSipUri(mContext, number);

    // Photo
    tagView.quickContactView.assignContactUri(info.contactContentUri);
    Log.setLogLevel(6);
    Log.d("Conversation adapter number", number);
    String nu = StaticValues.getStripNumber(number);
    String path = "/sdcard/R4W/ProfilePic/" + nu + ".png";
    System.out.println("msg adp out - path=" + path);
    File imageFile = new File(path);
    if (imageFile.exists()) {
        try {
            Bitmap bm = BitmapFactory.decodeFile(path);
            bm = ImageHelperCircular.getRoundedCornerBitmap(bm, bm.getWidth());
            tagView.quickContactView.getImageView().setImageBitmap(bm);
        } catch (Exception e) {
            // TODO: handle exception
            try {
                tagView.quickContactView.getImageView().setImageURI(Uri.parse(path));

            } catch (Exception e2) {
                ContactsAsyncHelper.updateImageViewWithContactPhotoAsync(mContext,
                        tagView.quickContactView.getImageView(), info, R.drawable.ic_contact_picture_holo_dark);
                // TODO: handle exception
            }
        }
    } else {

        ContactsAsyncHelper.updateImageViewWithContactPhotoAsync(mContext,
                tagView.quickContactView.getImageView(), info, R.drawable.ic_contact_picture_holo_dark);
    }

    // From
    System.out.println("formatMessage(cursor):" + formatMessage(cursor));
    tagView.fromView.setText(formatMessage(cursor));

    //Date
    // Set the date/time field by mixing relative and absolute times.
    int flags = DateUtils.FORMAT_ABBREV_RELATIVE;
    tagView.dateView.setText(DateUtils.getRelativeTimeSpanString(date, System.currentTimeMillis(),
            DateUtils.MINUTE_IN_MILLIS, flags));

}

From source file:co.nerdart.ourss.adapter.FeedsCursorAdapter.java

@Override
protected void bindGroupView(View view, Context context, Cursor cursor, boolean isExpanded) {
    ImageView indicatorImage = (ImageView) view.findViewById(R.id.indicator);

    if (cursor.getInt(isGroupPosition) == 1) {
        long feedId = cursor.getLong(idPosition);
        if (feedId == mSelectedFeedId) {
            view.setBackgroundResource(android.R.color.holo_blue_dark);
        } else {/*  w  w w  . java  2 s  . c o m*/
            view.setBackgroundResource(android.R.color.transparent);
        }

        indicatorImage.setVisibility(View.VISIBLE);

        TextView textView = ((TextView) view.findViewById(android.R.id.text1));
        textView.setEnabled(true);
        textView.setText(cursor.getString(namePosition));
        textView.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null);

        int unreadCount;
        synchronized (mUnreadItemsByFeed) {
            unreadCount = mUnreadItemsByFeed.get(feedId);
        }

        textView.setText(cursor.getString(namePosition) + (unreadCount > 0 ? " (" + unreadCount + ")" : ""));

        view.findViewById(android.R.id.text2).setVisibility(View.GONE);

        View sortView = view.findViewById(R.id.sortitem);
        if (!sortViews.contains(sortView)) { // as we are reusing views, this is fine
            sortViews.add(sortView);
        }
        sortView.setVisibility(feedSort ? View.VISIBLE : View.GONE);

        final int groupPosition = cursor.getPosition();
        if (!mGroupInitDone.get(groupPosition)) {
            mGroupInitDone.put(groupPosition, true);

            boolean savedExpandedState = cursor.getInt(isGroupCollapsedPosition) != 1;
            if (savedExpandedState && !isExpanded) {
                mActivity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mListView.expandGroup(groupPosition);
                    }
                });
            }

            if (savedExpandedState)
                indicatorImage.setImageResource(R.drawable.group_expanded);
            else
                indicatorImage.setImageResource(R.drawable.group_collapsed);
        } else {
            if (isExpanded)
                indicatorImage.setImageResource(R.drawable.group_expanded);
            else
                indicatorImage.setImageResource(R.drawable.group_collapsed);
        }
    } else {
        bindChildView(view, context, cursor);
        indicatorImage.setVisibility(View.GONE);
    }
}

From source file:org.linphone.ContactsManager.java

public Contact getContact(String id, ContentResolver contentResolver) {
    String[] projection = { ContactsContract.Data.CONTACT_ID, ContactsContract.Data.DISPLAY_NAME };
    String selection = new StringBuilder().append(ContactsContract.Data.CONTACT_ID).append(" = ?").toString();

    Cursor c = contentResolver.query(ContactsContract.Data.CONTENT_URI, projection, selection,
            new String[] { id }, null);
    if (c != null) {
        if (c.moveToFirst()) {
            Contact contact = Compatibility.getContact(contentResolver, c, c.getPosition());
            c.close();//from  ww  w  .j a va  2 s  . c o  m

            if (contact != null) {
                return contact;
            } else {
                return null;
            }
        }
        c.close();
    }
    return null;
}

From source file:com.gdgdevfest.android.apps.devfestbcn.ui.SessionLivestreamActivity.java

/**
 * Locates which item should be selected in the action bar drop-down spinner based on the
 * current active session uri//from w w w.j a  v a2s .  co  m
 * @param data The data
 * @return The row num of the item that should be selected or 0 if not found
 */
private int locateSelectedItem(Cursor data) {
    int selected = 0;
    if (data != null && (mSessionId != null || mTrackName != null)) {
        final boolean findNextSessionByTrack = mTrackName != null;
        while (data.moveToNext()) {
            if (findNextSessionByTrack) {
                if (mTrackName.equals(data.getString(SessionsQuery.TRACK_NAME))) {
                    selected = data.getPosition();
                    mTrackName = null;
                    break;
                }
            } else {
                if (mSessionId.equals(data.getString(SessionsQuery.SESSION_ID))) {
                    selected = data.getPosition();
                }
            }
        }
    }
    return selected;
}

From source file:org.linphone.ContactsManager.java

public Contact findContactWithDisplayName(String displayName) {
    String[] projection = { ContactsContract.Data.CONTACT_ID, ContactsContract.Data.DISPLAY_NAME };
    String selection = new StringBuilder().append(ContactsContract.Data.DISPLAY_NAME).append(" = ?").toString();

    Cursor c = contentResolver.query(ContactsContract.Data.CONTENT_URI, projection, selection,
            new String[] { displayName }, null);
    if (c != null) {
        if (c.moveToFirst()) {
            Contact contact = Compatibility.getContact(contentResolver, c, c.getPosition());
            c.close();//from  w w w . j  a v a2 s.  com

            if (contact != null) {
                return contact;
            } else {
                return null;
            }
        }
        c.close();
    }
    return null;
}