user268397 user268397 - 7 months ago 98
Java Question

Android View nullPointerException cause by setVisibility() method

I'm have an issue with changing the visibility of my buttons. Whenever I use the setVisibility() method I get a nullPointerException. Here is the error I get:

04-08 15:59:02.529: E/AndroidRuntime(2807): FATAL EXCEPTION: main
04-08 15:59:02.529: E/AndroidRuntime(2807): java.lang.NullPointerException
04-08 15:59:02.529: E/AndroidRuntime(2807): at com.android.Rides.RideTracking.onClick(RideTracking.java:307)
04-08 15:59:02.529: E/AndroidRuntime(2807): at android.view.View.performClick(View.java:4204)
04-08 15:59:02.529: E/AndroidRuntime(2807): at android.view.View$PerformClick.run(View.java:17355)
04-08 15:59:02.529: E/AndroidRuntime(2807): at android.os.Handler.handleCallback(Handler.java:725)
04-08 15:59:02.529: E/AndroidRuntime(2807): at android.os.Handler.dispatchMessage(Handler.java:92)
04-08 15:59:02.529: E/AndroidRuntime(2807): at android.os.Looper.loop(Looper.java:137)
04-08 15:59:02.529: E/AndroidRuntime(2807): at android.app.ActivityThread.main(ActivityThread.java:5041)
04-08 15:59:02.529: E/AndroidRuntime(2807): at java.lang.reflect.Method.invokeNative(Native Method)
04-08 15:59:02.529: E/AndroidRuntime(2807): at java.lang.reflect.Method.invoke(Method.java:511)
04-08 15:59:02.529: E/AndroidRuntime(2807): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
04-08 15:59:02.529: E/AndroidRuntime(2807): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
04-08 15:59:02.529: E/AndroidRuntime(2807): at dalvik.system.NativeStart.main(Native Method)


Here is the code:

public View btnStart = null;
public View btnPause = null;
public View btnResume = null;

case R.id.btnPauseRide:
mLoggerServiceManager.pauseGPSLogging();

setResult( RESULT_OK, intent );
btnPause.setVisibility(View.GONE);
btnResume.setVisibility(View.VISIBLE);
break;

case R.id.btnResumeRide:
mLoggerServiceManager.resumeGPSLogging();
setResult(RESULT_OK, intent);

btnResume.setVisibility(View.GONE);
btnPause.setVisibility(View.VISIBLE);
default:
break;


Any help would be greatly appreciated.

Answer

This is because

 public View btnPause = null;

you set the button to null. You need to assign it. Assuming you have already called setContentView() and the button is in that layout

btnPause = (Button) findViewwById(R.id.button_id);

You have all of your buttons set to null then trying to call a method on them, setVisibility(), which will return null every time

If you are wanting to hide the Button that is pressed then you can just do

    case R.id.btnPauseRide:
        mLoggerServiceManager.pauseGPSLogging();

        setResult( RESULT_OK, intent );
        btnPPauseRide.setVisibility(View.GONE);
        btnResume.setVisibility(View.VISIBLE);
        break;

instead of creating these new Views unless you have something else going on

Comments