Solved OnClickListener Bug!

Took me a lot of stacked overflowing but I finally solved the bug. It turns out that the Pager Adapter I was using wasn’t creating the layouts until I swiped to view them. Thus I was getting a null pointer exception because I was trying to call a button that didn’t exist. So now I inflate the views before I call the onClickListener and voilà! Now on to the hard part.

BEFORE:

<pre><code>@Override
public Object instantiateItem(View collection, int position) {
    LayoutInflater inflater = (LayoutInflater) collection.getContext()
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    int resId = 0;
    switch (position) {

    case 0:
        resId = R.layout.splash2;
        b = (Button) collection.findViewById(R.id.splashB);
        b.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                                    //setContentView(r.layout.someLayout);
            }
        });
        break;</code>

AFTER:

</pre>
public Object instantiateItem(View collection, int position) {
 LayoutInflater inflater = (LayoutInflater) collection.getContext()
 .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

View view = null;
 switch (position) {

case 0:
 view = inflater.inflate(R.layout.splash2, null);
 b1 = (Button) view.findViewById(R.id.splashB1);
 b1.setOnClickListener(new OnClickListener() {

@Override
 public void onClick(View v) {
 // TODO Auto-generated method stub
 v.getContext().startActivity(i);

}
 });
 break;

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s