Reputation: 772
My project has a NullPointerException when creating the main activity. The main activity creates a fragment, which is where the exception lies. Here's the code for the part where it breaks: Fragment code:
Drawable red;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
getActivity().setContentView(R.layout.main_layout);
red = ((ImageView)this.getActivity().findViewById(R.drawable.icon_0)).getDrawable();
}
Activity code:
private ProblemFragment problemFrag;
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main_layout);
problemFrag = new ProblemFragment();
ActionBar bar = getSupportActionBar();
bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
Tab tab = bar.newTab().setText("Problem Fragment").setTabListener(new MyTabListener(this, dashboardFrag));
bar.setHomeButtonEnabled(true);
}
It crashes when it's running past the red drawable. Is this because of the "getActivity()" line? It is imperative to have these values instantiated immediately, but I can't think of a way to load them up without using findById. If it helps, they are PNG files in the res folder.
Upvotes: 0
Views: 151
Reputation: 7739
Best solution in that situation is using getResources().getDrawable()
methods like that :
red = getActivity().getResources().getDrawable(R.drawable.icon_0);
Please use it to every drawables, etc. in your res
folder.
Upvotes: 1
Reputation: 1244
Try this:
Drawable red = getResources().getDrawable(R.drawable.icon_0);
For all your resources that are not declared views in your xml
Upvotes: 2