Reputation: 479
I am dynamically creating objects in the program and populating them from an array.xml. In the array.xml I have a series of tools and values and I need to load these into the class values for each item.
Here is what I have in the class;
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
}
and this is my 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>
However, it throws a null pointer on the "//null pointer?" line. Can anyone offer advice on what i'm doing wrong to import it?
Upvotes: 0
Views: 133
Reputation: 1996
Make a 'Context' field in ToolImporter class. Pass context from your activity to ToolImporter class in ToolImporter constructor.
Use context field to access getResources()
aTool = context.getResources().getStringArray(R.array.tools);
Upvotes: 0
Reputation: 655
Create field variables in your Application class and then initialize them inside the onCreate method within your main activity class.
Upvotes: 1
Reputation: 24326
According to this post:
You shouldn't call getResources() unless onCreate() callback has been triggered.
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
}
}
Upvotes: 1