如何解决空指针引用错误首次安装时
我dbhelper.java有方法如何解决空指针引用错误首次安装时
public Cursor report(){     SQLiteDatabase db = this.getReadableDatabase(); 
    Cursor c = db.rawQuery("SELECT * FROM Employees", null); 
    return c; 
} 
Mainactivity.java
private List<Front1> viewReport(){     List<Front1> employeeList1 = new ArrayList<>(); 
    Cursor c = db.report(); 
if (c != null && c.getCount() > 0) {   // Add the addition condition 
if (c.moveToFirst()) { 
    do{ 
     String ids=c.getString(c.getColumnIndex("e_ids")); 
     String name=c.getString(c.getColumnIndex("e_name")); 
     Front1 front1=new Front1(ids,name1); 
     employeeList1.add(front1); 
    }while (c.moveToNext());} 
}else{ 
Front1 front1=new Front1("101","suran"); 
     employeeList1.add(front1); 
} 
我有员工table.first时应用程序安装我的表有空如此应用程序崩溃。如果我添加dumny数据停止应用程序崩溃,但用户再次删除虚拟数据应用程序crash.how解决null对象参考初始阶段。它意味着选择sta如果结果集是空的,则使用该值。我希望我的应用程序不会崩溃。任何导向都会对我有帮助。
回答:
由于Cursor不会返回null,如果表为空,则应该使用getCount()函数来解决您的问题。您的代码应如下所示:
if (c != null && c.getCount() > 0) {   // Add the addition condition     if (c.moveToFirst()) { 
     do{ 
      String ids=c.getString(c.getColumnIndex("e_ids")); 
      String name=c.getString(c.getColumnIndex("e_name")); 
      Front1 front1=new Front1(ids,name1); 
      employeeList1.add(front1); 
     }while (c.moveToNext());} 
} 
回答:
您的问题是空查询不会从查询返回。相反,在没有提取数据的情况下,光标将是空的。
这可以使用光标getCount()方法进行检查。但是,通过检查移动的返回值(true或false),就可以轻松地进行检查。方法如moveToNext。 MoveToNext也可用于在while循环中遍历多行。因此,也许最简单的解决方案是使用: -
if (c.moveToNext()) {     String ids=c.getString(c.getColumnIndex("e_ids")); 
    String name=c.getString(c.getColumnIndex("e_name")); 
    Front1 front1=new Front1(ids,name1); 
    employeeList1.add(front1); 
} 
显然,你可能需要检查返回列表的大小,因为它的规模可能为0。
以上是 如何解决空指针引用错误首次安装时 的全部内容, 来源链接: utcz.com/qa/260216.html
