【发布时间】:2014-06-18 19:01:04
【问题描述】:
我正在尝试将列表视图用作菜单,并在用户点击时触发一个活动(这是在谷歌玻璃上)我已经通过了上下文,但由于某种原因,空指针异常不断弹出。想知道为什么会这样。
代码:
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>
我唯一的想法是列表视图在单独的线程上运行,我可能必须使用在 ui 上运行的函数来获得正确触发活动的意图。任何帮助,将不胜感激。
【问题讨论】:
-
你能提供你的 logcat 输出吗?
标签: java android android-intent android-listview