0

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.

1
  • Do you call setContentView in your Activity before showing the Fragment? Commented Jul 30, 2013 at 17:00

2 Answers 2

2

Try this:

Drawable red = getResources().getDrawable(R.drawable.icon_0);

For all your resources that are not declared views in your xml

Sign up to request clarification or add additional context in comments.

Comments

1

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.

4 Comments

I did that, and now I'm getting an IllegalStateException stating that the fragment is not properly attached to the activity.
The getActivity was what was causing the NullPointerException earlier though... :/
Yeah, it caused a NullPointerException.
Never mind, fixed it myself. I made red a default variable and then initialized it from the main activity's onCreate.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.