我正在尝试使用列表视图作为菜单,并在用户点击(这在Google Glass上)时已经触发了活动,而我已跳过上下文,但是由于某些原因,空指针异常不断弹出。想知道为什么会这样。
码:
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上运行的功能才能正确启动该活动。任何帮助,将不胜感激。
最佳答案
您的两个构造函数未将值分配给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();
}