Ashishsingh
Ashishsingh

Reputation: 742

Why is this program being unexpectedly stopped?

Why isn't this code working? I've been stuck on this for 2 days.

public  class SongsActivity extends Activity{

        DemoView demoview ;
        FinalView finalview;
        ViewFlipper c ;
        /** Called when the activity is first created. */
        @Override
        public void onCreate(Bundle savedInstanceState) {

            super.onCreate(savedInstanceState);
            demoview = new DemoView(this);
            finalview = new FinalView(this);
               // adding view to the viewflipper
            c.addView(demoview,0);
            c.addView(finalview, 1);
                ///initializing the fliiper
            c=(ViewFlipper)findViewById(R.id.viewFlipper1);

            c.setAutoStart(true);
            c.setFlipInterval(500);
            c.startFlipping();

        }

Upvotes: 1

Views: 91

Answers (2)

Squonk
Squonk

Reputation: 48871

You can't use findViewById before setting the view of your Activity using setContentView.

Although Booyakka's answer is partially correct, you're not setting the content view with anything that contains a ViewFlipper with the resId R.id.viewFlipper1.

As a result, the line...

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

Will set c to null even if you've initialized it as Booyakka's suggestion.

Why are you not using setContentView(...) with a layout xml? The fact you are trying to find a view with the resId R.id.viewFlipper1 suggests you've created the layout xml but you're not inflating it and that's part of the cause of your problem.

EDIT: Inflating a layout is taking the contents of an XML layout file and instantiating the objects it describes. Do this with setContentView(<layout-resource-id>) BEFORE attempting to use findViewById

Try changing your onCreate() method as below using the name of the layout file you created.

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Inflate the main.xml file using the following...
    setContentView(R.layout.main);

    // Move the findViewById(...) call to here...
    c=(ViewFlipper)findViewById(R.id.viewFlipper1);

    demoview = new DemoView(this);
    finalview = new FinalView(this);

    c.addView(demoview,0);
    c.addView(finalview, 1);

    c.setAutoStart(true);
    c.setFlipInterval(500);
    c.startFlipping();
}

Upvotes: 2

Booyakka
Booyakka

Reputation: 21

you are adding view before initialising.

when you call c.addView(demoview, 0); c is null because it has not been initialised. so initialise c with ViewFlipper and add the views after.

Upvotes: 2

Related Questions