I am currently trying to implement a ScrollView whereby I want the included ImageView to be scrolled through a RotationVectorSensor and a SensorEventListener.
This is my code so far:
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.view.Menu;
import android.widget.HorizontalScrollView;
import android.widget.Toast;
public class MainActivity extends Activity implements SensorEventListener {
private SensorManager sensorManager;
private Sensor sensor;
private HorizontalScrollView scrollView;
private String TAG = MainActivity.class.getSimpleName();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensor = sensorManager.getDefaultSensor(Sensor.TYPE_ROTATION_VECTOR);
if (sensor != null) {
sensorManager.registerListener(this, sensor,
SensorManager.SENSOR_DELAY_NORMAL);
Log.d(TAG, "Sensor found.");
} else {
Log.e(TAG, "Sensor NOT found.");
Toast.makeText(this, "ROTATION_VECTOR Sensor not found",
Toast.LENGTH_LONG).show();
finish();
}
scrollView = (HorizontalScrollView) findViewById(R.id.panoramaScrollView);
Log.d(TAG, "Panorama Scroll View found.");
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// TODO Auto-generated method stub
}
@Override
public void onSensorChanged(SensorEvent event) {
Toast.makeText(this, "rotating Yippi!", Toast.LENGTH_LONG).show();
if (event.sensor.getType() == Sensor.TYPE_ROTATION_VECTOR) {
final float angle = event.values[2];
scrollView.post(new Runnable() {
public void run() {
if (scrollView != null) {
scrollView.scrollTo((int)angle, scrollView.getBottom());
Log.d(TAG, "scrollTo executed.");
}
}
});
}
}
@Override
public void onResume() {
super.onResume();
sensorManager.registerListener(this, sensor, SensorManager.SENSOR_DELAY_NORMAL);
Log.d(TAG, "SensorListener registered");
}
@Override
public void onPause() {
super.onPause();
if (sensor != null) {
sensorManager.unregisterListener(this);
Log.d(TAG, "SensorListener unregistered");
}
}
}
The Nullpointer occurs directly after the sensor is initialized:
sensor = sensorManager.getDefaultSensor(Sensor.TYPE_ROTATION_VECTOR);
Therefor the app exits and prints: "Sensor NOT found"...
Is there anything I've forgotten?
Thanks in advance!
I found the solution. The following lines were missing in the android manifest: