2012-12-17 52 views
0

我在程序中動態創建對象並從array.xml中填充它們。 在array.xml中我有一系列工具和值,我需要將它們加載到每個項目的類值中。將數組值加載到類中

這是我在課堂上的;

public class ToolImporter extends Application{ 

public static Tool[] tools; 
private String[] aTool; 
private int i; 

public ToolImporter() { 

    aTool = getResources().getStringArray(R.array.tools); //null pointer? 

    // TODO Auto-generated constructor stub 
} 

這是我的array.xml;

<array name="tools"> 
     <item name="SAW"> 
      <id>1</id> 
      <image>R.drawable.image_saw100x60px</image> 
      <boxX>100</boxX> 
      <boxY>100</boxY> 
      <worktopX>200</worktopX> 
      <worktopY>200</worktopY> 
     </item> 
     <item name="SCREWDRIVER"> 
      <id>2</id> 
      <image>R.drawable.image_screwdriver100x60px</image> 
      <boxX>150</boxX> 
      <boxY>100</boxY> 
      <worktopX>250</worktopX> 
      <worktopY>200</worktopY> 
     </item> 
     <item name="HAMMER"> 
      <id>3</id> 
      <image>R.drawable.image_hammer100x60px</image> 
      <boxX>200</boxX> 
      <boxY>100</boxY> 
      <worktopX>300</worktopX> 
      <worktopY>200</worktopY> 
     </item> 
    </array> 

但是,它會在「//空指針?」上拋出一個空指針。線。 任何人都可以提供意見我做錯了導入它?

回答

1

根據這一post

你不應該叫getResources(),除非的onCreate()回調被觸發。

public class StackStackActivity extends Activity 
{ 

    String[] myArray = getResources().getStringArray(R.array.glenns); // This returns null 

    public StackStackActivity() 
    { 

     myArray = getResources().getStringArray(R.array.glenns); // This returns null also 
    } 

    @Override 
    public void onCreate(Bundle savedInstanceState) 
    { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 

     myArray = getResources().getStringArray(R.array.glenns); // Returns an array from resources 
    } 
} 
+0

看問題,他正試圖訪問,而不是活動的應用類中資源 –

+0

我的聲明仍然有效。 – Woot4Moo

+0

我將嘗試在活動中導入數組並將其傳遞給導入器類 – Intern87

1

在您的Application類中創建字段變量,然後在您的主要活動類的onCreate方法內初始化它們。

+0

這工作,並在我的評論@ Woot4Moo的帖子 – Intern87

0

在ToolImporter類中創建一個'Context'字段。將活動的上下文傳遞給ToolImporter構造函數中的ToolImporter類。

使用上下文字段訪問getResources()

aTool = context.getResources().getStringArray(R.array.tools);