如何解决空指针引用错误首次安装时

问题描述:

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());} 


} 
+0

是.size是零。因为第一如果表空的跳过并移动其他条件(改变你的代码添加其他条件手动添加数组数据),但显示错误光标c = db.report();线。 –

+0

如果表格为空,c不会返回null。你必须检查getCount()的值是否大于0.请按照上述步骤操作。 – tahsinRupam

+0

我试过先生同样的错误happen.code不读下一行。(因为行== 0).so代码不会跳过if条件。游标c = db.report();击中此行。 –

您的问题是空查询不会从查询返回。相反,在没有提取数据的情况下,光标将是空的。

这可以使用光标getCount()方法进行检查。但是,通过检查移动的返回值(true或false),就可以轻松地进行检查。方法如moveToNextMoveToNext也可用于在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。

+0

是.size为零。因为第一次安装应用程序那个时间表empty.sorry问清楚。我试着如果表空跳过并移动其他条件。但显示错误光标c = db.report();线。 –

+0

我想得到c == null.it表示从dbhelper返回null –

+0

如果表空然后返回c什么将返回c表示null或int 0.如何设置条件if(c == null)then ... else ...或任何其他。 –