滑动时出现Nullpointer异常

时间:2012-12-13 15:36:14

标签: java android nullpointerexception swipe-gesture

我在刷卡时得到NullPointerException。有什么问题以及如何纠正?方法onTouchEvent由语句return gestureDetector.onTouchEvent(event);

触发异常

此活动(List8)在Tabs3类中被称为TabActivity,它也是为了完整而提供的。

package myapp.tabnavui;

import myapp.tabnavui.R;

import android.app.ListActivity;
import android.content.Context;
import android.os.Bundle;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.AbsListView;
import android.widget.Toast;

import java.util.ArrayList;


/**
 * A list view that demonstrates the use of setEmptyView. This example alos uses
 * a custom layout file that adds some extra buttons to the screen.
 */
public class List8 extends ListActivity {

    private GestureDetector gestureDetector;
    PhotoAdapter mAdapter;

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

        // Use a custom layout file
        setContentView(R.layout.list_8);

        // Tell the list view which view to display when the list is empty
        getListView().setEmptyView(findViewById(R.id.empty));

        // Set up our adapter
        mAdapter = new PhotoAdapter(this);
        setListAdapter(mAdapter);

        // Wire up the clear button to remove all photos
        Button clear = (Button) findViewById(R.id.clear);
        clear.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                mAdapter.clearPhotos();
            } });

        // Wire up the add button to add a new photo
        Button add = (Button) findViewById(R.id.add);
        add.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                mAdapter.addPhotos();
            } });
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        return gestureDetector.onTouchEvent(event);
    }


    /**
     * A simple adapter which maintains an ArrayList of photo resource Ids. 
     * Each photo is displayed as an image. This adapter supports clearing the
     * list of photos and adding a new photo.
     *
     */
    public class PhotoAdapter extends BaseAdapter {

        private Integer[] mPhotoPool = {
                R.drawable.sample_thumb_0, R.drawable.sample_thumb_1, R.drawable.sample_thumb_2,
                R.drawable.sample_thumb_3, R.drawable.sample_thumb_4, R.drawable.sample_thumb_5,
                R.drawable.sample_thumb_6, R.drawable.sample_thumb_7};

        private ArrayList<Integer> mPhotos = new ArrayList<Integer>();

        public PhotoAdapter(Context c) {
            mContext = c;
        }

        public int getCount() {
            return mPhotos.size();
        }

        public Object getItem(int position) {
            return position;
        }

        public long getItemId(int position) {
            return position;
        }

        public View getView(int position, View convertView, ViewGroup parent) {
            // Make an ImageView to show a photo
            ImageView i = new ImageView(mContext);

            i.setImageResource(mPhotos.get(position));
            i.setAdjustViewBounds(true);
            i.setLayoutParams(new AbsListView.LayoutParams(LayoutParams.WRAP_CONTENT,
                    LayoutParams.WRAP_CONTENT));
            // Give it a nice background
            i.setBackgroundResource(R.drawable.picture_frame);
            return i;
        }

        private Context mContext;

        public void clearPhotos() {
            mPhotos.clear();
            notifyDataSetChanged();
        }

        public void addPhotos() {
            int whichPhoto = (int)Math.round(Math.random() * (mPhotoPool.length - 1));
            int newPhoto = mPhotoPool[whichPhoto];
            mPhotos.add(newPhoto);
            notifyDataSetChanged();
        }

    }

    class MyGestureDetector extends SimpleOnGestureListener {
          private static final int SWIPE_MAX_OFF_PATH = 200;
          private static final int SWIPE_MIN_DISTANCE = 50;
          private static final int SWIPE_THRESHOLD_VELOCITY = 200;

        @Override
        public boolean onDown (MotionEvent e) {
            return true;
        }

          @Override
          public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
               if (Math.abs(e1.getY() - e2.getY()) > SWIPE_MAX_OFF_PATH)
                   return false;
               // left to right swipe and right to left swipe
               if (e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE
                 && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
                    // left swipe
                    Toast t = Toast.makeText(List8.this, "Left swipe", Toast.LENGTH_LONG);
                    t.show();
                    startActivity(Tabs3.tab1);
                    return true;
               } else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE
                 && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
                    // right swipe
                    Toast t = Toast.makeText(List8.this, "Right swipe", Toast.LENGTH_LONG);
                    t.show();
                    startActivity(Tabs3.tab3);
                    return true;
               }
               return false;
          }    
    }    
}

这是Tabs3:

package myapp.tabnavui;

import android.os.Bundle;
import android.util.Log;
import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.MotionEvent;
import android.view.View;
import android.widget.TabHost;
import android.widget.Toast;
import android.app.TabActivity;
import android.content.Intent;

/**
 * An example of tab content that launches an activity via {@link android.widget.TabHost.TabSpec#setContent(android.content.Intent)}
 */
public class Tabs3 extends TabActivity {

    private GestureDetector gestureDetector;
    // View.OnTouchListener gestureListener;
    // Intent go;
    public static Intent tab1, tab2, tab3; 

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

        final TabHost tabHost = getTabHost();

        tab1 = new Intent(this, List1.class);
        tabHost.addTab(tabHost.newTabSpec("tab1")
                .setIndicator("list")
                .setContent(tab1));

        tab2 = new Intent(this, List8.class);
        tabHost.addTab(tabHost.newTabSpec("tab2")
                .setIndicator("photo list")
                .setContent(tab2));

        // This tab sets the intent flag so that it is recreated each time
        // the tab is clicked.
        tab3 = new Intent(this, Controls2.class);
        tabHost.addTab(tabHost.newTabSpec("tab3")
                .setIndicator("destroy")
                .setContent(tab3
                        .addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)));
    }
}

1 个答案:

答案 0 :(得分:0)

原因

Tabs3.gestureDetectorList8.gestureDetector永远不会设置,因此它们是null

这就是为什么当您尝试在NullPointerException

使用时gestureDetector.onTouchEvent(event);

解决方案

根据this question,您需要在创建时使用GestureDetector进行设置:

@Override
public void onCreate(Bundle savedInstanceState) {
    // code
    gestureDetector = new GestureDetector(new MyGestureDetector());
    // code
}