2011-03-10 102 views
0

我遵循教程將數據從sqlite數據庫填充到Android中的微調器(下拉菜單)中。不過,我得到的錯誤:Android微調 - 無法對靜態方法進行靜態引用幫助

Cannot make a static reference to the non-static method fetchAllCategories() from the type DatabaseAdapter 

我的代碼如下:

在EditTask:

private void fillData() { 
     Cursor categoriesCursor; 
     Spinner categoriesSpinner = (Spinner) findViewById(R.id.spinDept); 
     categoriesCursor = DatabaseAdapter.fetchAllCategories(); 

     startManagingCursor(categoriesCursor); 

     String[] from = new String[] { DatabaseAdapter.CAT_NAME }; 

     int[] to = new int[] { R.id.tvDBViewRow }; //this part hasnt been implemented in to the layout yet 

     SimpleCursorAdapter categoriesAdapter = new SimpleCursorAdapter(this, 
       R.layout.db_view_row, categoriesCursor, from, to); 

     categoriesSpinner.setAdapter(categoriesAdapter); 
    } 

在我DatabaseAdapter類我有以下幾點:

public Cursor fetchAllCategories() { 
    if (mDb == null) { 
     this.open(); 
    } 
    String tableName = "CAT_TABLE"; 
    return mDb.query(tableName, new String[] { CAT_ID, CAT_NAME }, null, 
      null, null, null, null); 
} 

違規代碼行是:

categoriesCursor = DatabaseAdapter.fetchAllCategories(); 

我很新Java/Android,所以它可能是簡單/明顯的東西,但任何幫助,非常感謝!

回答

1

您必須首先實例化一個DatabaseAdapter對象。 如:

DatabaseAdapter myDbAdapter = new DatabaseAdapter(); 
categoriesCursor = myDbAdapter.fetchAllCategories(); 
+0

感謝您的幫助,代碼的第二部分帶來了更多的錯誤,例如:「不能在靜態上下文中使用它」和「無法對非靜態字段mDb進行靜態引用」。使用第一部分還會產生以下錯誤:對於類型DatabaseAdapter,未定義fetchAllCategories()方法 – user319940 2011-03-10 21:42:32

+0

必須用您在自己的實現中使用的類名替換DatabaseAdapter。 – 2011-03-10 21:46:41

+0

classname是DatabaseAdapter,它表示構造函數需要另一個參數,所以我剛剛使用了DatabaseAdapter myDbAdapter = new DatabaseAdapter(null);這似乎已經解決了這個問題,但我仍然得到類別遊標的錯誤是:類別遊標無法解析 – user319940 2011-03-10 21:50:16

0

才能夠使你的代碼工作,你需要聲明的方法fetchAllCategoires()靜態如下:

public static Cursor fetchAllCategories() 

因爲你還沒有實例化一個DatabaseAdapter對象,除非靜態關鍵字出現在方法聲明中,否則不能通過類名引用調用其中一個方法。

+0

我以前嘗試過,但不幸的是它帶來了進一步的錯誤,如:「不能在靜態上下文中使用」和「靜態引用非靜態字段mDb「 – user319940 2011-03-10 21:40:11

+0

ahh,關於mDb錯誤,這可能是因爲mDb是一個全局變量,沒有聲明爲靜態。您應該儘可能嘗試實例化您的類並在實例上調用fetchAllCategories()方法。 – 2011-03-10 21:44:03

相關問題