Utkarsh Dubey Utkarsh Dubey - 3 months ago 23
Android Question

java.lang.NullPointerException error during runtime

I have created an andrpid application in which I use ViewFlipper to flip images while clicking on the screen .

There is no error being shown in eclipse but when I run the app in the Emulator
and click on the screen to flip the image the Application crashes and this error comes in the logcat:

08-16 07:27:32.690: E/AndroidRuntime(1321): FATAL EXCEPTION: main
08-16 07:27:32.690: E/AndroidRuntime(1321): Process: com.utkarsh.thenewdelhi, PID: 1321
08-16 07:27:32.690: E/AndroidRuntime(1321): java.lang.NullPointerException
08-16 07:27:32.690: E/AndroidRuntime(1321): at com.utkarsh.thenewdelhi.Flipper.onClick(Flipper.java:32)
08-16 07:27:32.690: E/AndroidRuntime(1321): at android.view.View.performClick(View.java:4438)
08-16 07:27:32.690: E/AndroidRuntime(1321): at android.view.View$PerformClick.run(View.java:18422)
08-16 07:27:32.690: E/AndroidRuntime(1321): at android.os.Handler.handleCallback(Handler.java:733)
08-16 07:27:32.690: E/AndroidRuntime(1321): at android.os.Handler.dispatchMessage(Handler.java:95)
08-16 07:27:32.690: E/AndroidRuntime(1321): at android.os.Looper.loop(Looper.java:136)
08-16 07:27:32.690: E/AndroidRuntime(1321): at android.app.ActivityThread.main(ActivityThread.java:5017)
enter code here08-16 07:27:32.690: E/AndroidRuntime(1321): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)


etc etc

my class file is as follows:

public class Flipper extends Activity implements OnClickListener{`
ViewFlipper flippy;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.flipper);`
ViewFlipper flippy=(ViewFlipper)findViewById(R.id.viewFlipper1);
flippy.setOnClickListener(this);
@Override
public void onClick(View arg0) {`
flippy.showNext();
}
}


My XML file is as follows:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
<ViewFlipper
android:id="@+id/viewFlipper1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
>
<TextView
android:id="@+id/T5"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="hello" />
<TextView
android:id="@+id/T4"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="how" />
<TextView
android:id="@+id/Tv3"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="are" />
</ViewFlipper>
</LinearLayout>


So what should I do to remove this error ?

Answer

Change

ViewFlipper flippy=(ViewFlipper)findViewById(R.id.viewFlipper1);

to

flippy=(ViewFlipper)findViewById(R.id.viewFlipper1);

so you're initializing the member you're accessing in onClick() instead of a local variable.