我正在尝试使用listview作为菜单,并在用户点击时触发活动(这是在谷歌眼镜上)我已经通过了上下文,但由于某种原因,空指针异常不断弹出。想知道为什么会这样。
代码:
public class HeadListView extends ListView implements SensorEventListener {
private static final float INVALID_X = 10;
private Sensor mSensor;
private int mLastAccuracy;
private SensorManager mSensorManager;
private float mStartX = INVALID_X;
private static final int SENSOR_RATE_uS = 200000;
private static final float VELOCITY = (float) (Math.PI / 180 * 2); // scroll one item per 2°
public int location;
Context myContext;
public HeadListView(Context context, AttributeSet attrs, int defStyle)
{
super(context, attrs, defStyle);
myContext=context;
init();
}
public int getLocation()
{
return location;
}
public void setLocation(int location)
{
this.location = location;
}
public HeadListView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public HeadListView(Context context) {
super(context);
init();
}
public void init() {
mSensorManager = (SensorManager) getContext().getSystemService(Context.SENSOR_SERVICE);
mSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ROTATION_VECTOR);
}
public void activate() {
if (mSensor == null)
return;
mStartX = INVALID_X;
mSensorManager.registerListener(this, mSensor, SENSOR_RATE_uS);
}
public void deactivate() {
mSensorManager.unregisterListener(this);
mStartX = INVALID_X;
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
mLastAccuracy = accuracy;
}
public boolean onKeyDown(int keycode, KeyEvent event)
{
if (keycode == KeyEvent.KEYCODE_DPAD_CENTER)
{
// user tapped touchpad, should get and store the idd ItemsDto, and the byteArray
try
{
Log.e("Position: ", String.valueOf(location));
//declare intent
if(location==0)
{
Intent intn_test = new Intent("de.tud.ess.ANACTIVITY");
myContext.startActivity(intn_test);
}
}
catch (Exception e)
{
Log.e("MenuScreen:onCreate", e.toString());
}
//overridePendingTransition(R.layout.fade_in, R.layout.fade_out); //fade in/out transition
return true;
}
if (keycode == KeyEvent.KEYCODE_BACK)
{
//goes back to the previous activity, in this case the scanner
return true;
}
return false;
}
抛出空指针异常的部分是onKeyDown。这让我感到困惑,因为我(我以为我是正确的)在清单中声明了活动。
<activity
android:name="de.tud.ess.AnActivity"
android:label="@string/title_activity_an" >
<intent-filter>
<action android:name="de.tud.ess.ANACTIVITY" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
我唯一的想法是listview在一个单独的线程上运行,我可能不得不使用ui函数运行来获得正确触发活动的意图。任何帮助,将不胜感激。
答案 0 :(得分:1)
您的两个构造函数没有为myContext
赋值。如果这些构造函数中的任何一个是Android用于创建View的构造函数,myContext
将为null并在onKeyDown()
中导致NullPointerException。
您可能希望在所有三个构造函数中为myContext
赋值,因此您应该更新这两个:
public HeadListView(Context context, AttributeSet attrs) {
super(context, attrs);
myContext = context;
init();
}
public HeadListView(Context context) {
super(context);
myContext = context;
init();
}