检索sqlite数据库的最后一条记录

时间:2016-11-18 06:27:36

标签: android

 public class PlaceCallActivity extends BaseActivity {
    private static final String SELECT_SQL = "SELECT * FROM numbers";
    protected void onCreate(Bundle savedInstanceState) {
             opendatabase();
     c = db.rawQuery(SELECT_SQL, null);
            c.moveToLast();
        userNo.setText(c.getString(c.getColumnIndex("number")));
        }
    public void opendatabase(){
            db=openOrCreateDatabase("NumberDB", Context.MODE_PRIVATE, null);
 }

我想从“数字”列设置最后检索数据的文本 在运行时,我收到了以下错误:

CursorIndexOutOfBoundsException: Index -1 requested, with a size of 0

错误在我设置文本的位置。

“userNo.setText(c.getString(c.getColumnIndex(”number“)));”

2 个答案:

答案 0 :(得分:1)

您收到此错误,因为游标中没有数据,在从光标获取数据之前,您必须先检查它的数量。

if(c.getCount()!=0)
{
    if(c.moveToLast())
    {
    }
}

答案 1 :(得分:0)

public class PlaceCallActivity extends BaseActivity {
private static final String SELECT_SQL = "SELECT * FROM numbers";
protected void onCreate(Bundle savedInstanceState) {
         opendatabase();
 c = db.rawQuery(SELECT_SQL, null);
   if(c.getCount()>0)
      {
        c.moveToLast();
    userNo.setText(c.getString(c.getColumnIndex("number")));
  }  
  }
public void opendatabase(){
        db=openOrCreateDatabase("NumberDB", Context.MODE_PRIVATE, null);
}