2017-12-03 127 views
-2

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如果結果集是空的,則使用該值。我希望我的應用程序不會崩潰。任何導向都會對我有幫助。

回答

0

由於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();擊中此行。 –

0

您的問題是空查詢不會從查詢返回。相反,在沒有提取數據的情況下,光標將是空的。

這可以使用光標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 ...或任何其他。 –