zoukankan      html  css  js  c++  java
  • Android Using the Cursor

    Before you access one, you should know a few things about an Android cursor: 
      A cursor is a collection of rows. 
      You need to use moveToFirst() because the cursor is positioned
    before the first row.

      You need to know the column names. 
      You need to know the column types. 
      All field-access methods are based on column number, so you must
    convert the column name to a column number first. 
      The cursor is a random cursor (you can move forward and backward,
    and you can jump). 
      Because the cursor is a random cursor, you can ask it for a row count. 
    An Android cursor has a number of methods that allow you to navigate through it.
    Listing 3–21 shows you how to check if a cursor is empty, and how to walk through the
    cursor row by row when it is not empty.
    Listing 3–21. Navigating Through a Cursor Using a while Loop
    if (cur.moveToFirst() == false)
    {
       //no rows empty cursor
       return;
    }
     
    //The cursor is already pointing to the first row
    //let's access a few columns
    int nameColumnIndex = cur.getColumnIndex(People.NAME);
    String name = cur.getString(nameColumnIndex);
     
    //let's now see how we can loop through a cursor
     
    while(cur.moveToNext())
    {
       //cursor moved successfully
       //access fields
    }
    The assumption at the beginning of Listing 3–21 is that the cursor has been positioned
    before the first row. To position the cursor on the first row, we use the moveToFirst()
    method on the cursor object. This method returns false if the cursor is empty. We then
    use the moveToNext() method repetitively to walk through the cursor.
    To help you learn where the cursor is, Android provides the following methods:
    isBeforeFirst()
    isAfterLast() 
    isClosed()
    Using these methods, you can also use a for loop as in Listing 3–22 to navigate through
    the cursor instead of the while loop used in Listing 3–21.
    Listing 3–22. Navigating Through a Cursor Using a for Loop
    for(cur.moveToFirst();!cur.isAfterLast();cur.moveToNext())
    {
       int nameColumn = cur.getColumnIndex(People.NAME); 
       int phoneColumn = cur.getColumnIndex(People.NUMBER);

     String name = cur.getString(nameColumn);
       String phoneNumber = cur.getString(phoneColumn);
    }
    To find the number of rows in a cursor, Android provides a method on the cursor object
    called getCount().

  • 相关阅读:
    LeetCode(Weekly Contest 187)题解
    2021 暑期实习招聘思之未雨绸缪
    LeetCode(Weekly Contest 185)题解
    构建私有的 docker registry
    LeetCode(Weekly Contest 182)题解
    Win10图标变白
    远程连接linux上的mysql
    IDEA复制粘贴html文件打不进war包问题
    Git命令
    数据源收集
  • 原文地址:https://www.cnblogs.com/enricozhang/p/1750286.html
Copyright © 2011-2022 走看看