Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Kumar Bharath H N
8,324 PointsHi I'm not able to change the background color I'm getting a runtime error saying java.lang.NullPointerException
My code
public class MainActivity extends ActionBarActivity {
Random generator = new Random();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView factLabel = (TextView) findViewById(R.id.factTextView);
final RelativeLayout relative = (RelativeLayout)findViewById(R.id.relativeLayout);
Button nextFact = (Button) findViewById(R.id.nextFactButton);
View.OnClickListener listener = new View.OnClickListener() {
@Override
public void onClick(View v) {
factLabel.setText(FactBook.getFact());
relative.setBackgroundColor(Color.RED);
}
};
nextFact.setOnClickListener(listener);
}
}
and the error
02-14 19:09:03.541 32629-32629/com.example.kumar.myapplication E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.kumar.myapplication, PID: 32629
java.lang.NullPointerException
at com.example.kumar.myapplication.MainActivity$1.onClick(MainActivity.java:34)
at android.view.View.performClick(View.java:4463)
at android.view.View$PerformClick.run(View.java:18789)
at android.os.Handler.handleCallback(Handler.java:808)
at android.os.Handler.dispatchMessage(Handler.java:103)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:5299)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:825)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:641)
at dalvik.system.NativeStart.main(Native Method)
1 Answer
Steve Hunter
57,712 PointsWhich line of code is at line 34 - that's at least part of the problem?
Should the line of code, factLabel.setText(FactBook.getFact()); be using the FactBook class, or an instance of it called, perhaps, factBook?
Kumar Bharath H N
8,324 PointsKumar Bharath H N
8,324 Pointsi have made getFact as a static method and line 34 refers to relative.setBackgroundColor(Color.RED); the error is in setting the background color