Here is the code I'm using to read the heart rate from a wearable :
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.support.wearable.activity.WearableActivity;
import android.util.Log;
import android.widget.TextView;
import android.hardware.*;
import android.support.wearable.view.BoxInsetLayout.*;
public class MainActivity extends WearableActivity implements SensorEventListener {
private static final String TAG = "MainActivity";
private TextView mTextViewHeart;
SensorManager mSensorManager;
Sensor mHeartRateSensor;
SensorEventListener sensorEventListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
mTextViewHeart = new TextView(this);
mTextViewHeart.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
mTextViewHeart.setText("heart rate ");
mSensorManager = ((SensorManager) getSystemService(SENSOR_SERVICE));
mHeartRateSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_HEART_RATE);
// mSensorManager.registerListener(this, mHeartRateSensor, SensorManager.SENSOR_DELAY_NORMAL);
Log.i(TAG, "LISTENER REGISTERED.");
mTextViewHeart.setText("Something here");
mSensorManager.registerListener(this, mHeartRateSensor, mSensorManager.SENSOR_DELAY_FASTEST);
// mSensorManager.registerListener(sensorEventListener, mHeartRateSensor, mSensorManager.SENSOR_DELAY_FASTEST);
}
public void onResume(){
super.onResume();
}
public void onAccuracyChanged(Sensor sensor, int accuracy) {
Log.d(TAG, "onAccuracyChanged - accuracy: " + accuracy);
}
public void onSensorChanged(SensorEvent event) {
if (event.sensor.getType() == Sensor.TYPE_HEART_RATE) {
String msg = "" + (int)event.values[0];
mTextViewHeart.setText(msg);
Log.d(TAG, msg);
}
else
Log.d(TAG, "Unknown sensor type");
}
}
main_activity.xml :
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/white">
<android.support.wearable.view.GridViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<android.support.wearable.view.DotsPageIndicator
android:id="#+id/page_indicator"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="10dp"
android:padding="5dp"
android:background="#drawable/rounded_background">
</android.support.wearable.view.DotsPageIndicator>
</RelativeLayout>
The sensor functionality seems fine. The text boxes are not being displayed on screen, instead I just receive a blank screen. How to add mTextViewHeart to the screen programmatically ? Or is required that I add it via main_activity.xml ?
Update :
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.support.wearable.activity.WearableActivity;
import android.util.Log;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.hardware.*;
import android.support.wearable.view.BoxInsetLayout.*;
public class MainActivity extends WearableActivity implements SensorEventListener {
private static final String TAG = "MainActivity";
private TextView mTextViewHeart;
SensorManager mSensorManager;
Sensor mHeartRateSensor;
SensorEventListener sensorEventListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
RelativeLayout relativeLayout = (RelativeLayout )findViewById(R.id.parent);
mTextViewHeart = new TextView(this);
mTextViewHeart.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
mTextViewHeart.setText("heart rate ");
mSensorManager = ((SensorManager) getSystemService(SENSOR_SERVICE));
mHeartRateSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_HEART_RATE);
Log.i(TAG, "LISTENER REGISTERED.");
mTextViewHeart.setText("Something here");
mSensorManager.registerListener(this, mHeartRateSensor, mSensorManager.SENSOR_DELAY_FASTEST);
relativeLayout.addView(mTextViewHeart);
}
public void onResume(){
super.onResume();
}
public void onAccuracyChanged(Sensor sensor, int accuracy) {
Log.d(TAG, "onAccuracyChanged - accuracy: " + accuracy);
}
public void onSensorChanged(SensorEvent event) {
if (event.sensor.getType() == Sensor.TYPE_HEART_RATE) {
String msg = "" + (int)event.values[0];
mTextViewHeart.setText(msg);
Log.d(TAG, msg);
}
else
Log.d(TAG, "Unknown sensor type");
}
}
main_activity.xml :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/parent"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/white">
<android.support.wearable.view.GridViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<android.support.wearable.view.DotsPageIndicator
android:id="#+id/page_indicator"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="10dp"
android:padding="5dp"
android:background="#drawable/rounded_background">
</android.support.wearable.view.DotsPageIndicator>
</RelativeLayout>
I've updated with Pavneet Singh answer but blank screen displayed.
Maybe should configure all UI via XML ?
Update2 :
Updating to use linearlayout does not have an impact :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:orientation="vertical" >
<android.support.wearable.view.GridViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<android.support.wearable.view.DotsPageIndicator
android:id="#+id/page_indicator"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="10dp"
android:padding="5dp"
android:background="#drawable/rounded_background">
</android.support.wearable.view.DotsPageIndicator>
</LinearLayout>
package com.example.android.wearable.datalayer;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.support.wearable.activity.WearableActivity;
import android.util.Log;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.hardware.*;
import android.support.wearable.view.BoxInsetLayout.*;
public class MainActivity extends WearableActivity implements SensorEventListener {
private static final String TAG = "MainActivity";
private TextView mTextViewHeart;
SensorManager mSensorManager;
Sensor mHeartRateSensor;
SensorEventListener sensorEventListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
LinearLayout relativeLayout = (LinearLayout )findViewById(R.id.parent);
mTextViewHeart = new TextView(this);
mTextViewHeart.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
mTextViewHeart.setText("heart rate ");
mSensorManager = ((SensorManager) getSystemService(SENSOR_SERVICE));
mHeartRateSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_HEART_RATE);
Log.i(TAG, "LISTENER REGISTERED.");
mTextViewHeart.setText("Something here");
mSensorManager.registerListener(this, mHeartRateSensor, mSensorManager.SENSOR_DELAY_FASTEST);
relativeLayout.addView(mTextViewHeart);
}
public void onResume(){
super.onResume();
}
public void onAccuracyChanged(Sensor sensor, int accuracy) {
Log.d(TAG, "onAccuracyChanged - accuracy: " + accuracy);
}
public void onSensorChanged(SensorEvent event) {
if (event.sensor.getType() == Sensor.TYPE_HEART_RATE) {
String msg = "" + (int)event.values[0];
mTextViewHeart.setText(msg);
Log.d(TAG, msg);
}
else
Log.d(TAG, "Unknown sensor type");
}
}
Adding an edittext field also does not display :
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="121dp"
android:ems="10"
android:text="test"
/>
Could the issue be something fundamental ?
This screen layout displays :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/linearLayout1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<Button
android:id="#+id/button1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Click me to another screen" />
<TextView
android:id="#+id/textView1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="I'm screen 1 (main.xml)"
android:textAppearance="?android:attr/textAppearanceLarge" />
</LinearLayout>
Related
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/background_dark"
tools:context="com.karanvir.stepcounter.MainActivity">
<TextView
android:id="#+id/value"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
android:textColor="#android:color/holo_orange_light"
android:textSize="50sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintHorizontal_bias="0.461"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.433"
tools:layout_constraintBottom_creator="1"
tools:layout_constraintLeft_creator="1"
tools:layout_constraintRight_creator="1"
tools:layout_constraintTop_creator="1" />
<ImageView
android:id="#+id/imageView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="65dp"
android:background="#color/colorPrimary"
app:srcCompat="#drawable/i"
tools:layout_constraintLeft_creator="1"
tools:layout_constraintTop_creator="1"
android:layout_marginTop="66dp"
app:layout_constraintTop_toBottomOf="#+id/value"
app:layout_constraintLeft_toLeftOf="parent"
android:layout_marginLeft="65dp" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="48dp"
android:background="#android:color/holo_orange_light"
android:text="How it works"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:ignore="HardcodedText"
tools:layout_constraintLeft_creator="1"
tools:layout_constraintRight_creator="1"
tools:layout_constraintTop_creator="1" />
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
tools:layout_constraintTop_creator="1"
tools:layout_constraintLeft_creator="1"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
package com.karanvir.stepcounter;
import android.content.Context;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.util.Locale;
public class MainActivity extends AppCompatActivity implements SensorEventListener{
private TextView value;
private SensorManager sensorManager;
public static DecimalFormat DECIMAL_FORMATTER;
private SensorManager mSensorManager;
Button button22;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button22=(Button) findViewById(R.id.button);
button22.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openActivity3();
}
});
mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
if (mSensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD) != null){
//
Toast.makeText(this, "Success! There's a magnetometer.", Toast.LENGTH_SHORT).show();
}
else {
// Failure! No magnetometer.
openActivity2();
}
setContentView(R.layout.activity_main);
value = (TextView) findViewById(R.id.value);
// define decimal formatter
DecimalFormatSymbols symbols = new DecimalFormatSymbols(Locale.US);
symbols.setDecimalSeparator('.');
DECIMAL_FORMATTER = new DecimalFormat("#.000", symbols);
sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
}
#Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(this,
sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD),
SensorManager.SENSOR_DELAY_NORMAL);
}
#Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(this);
}
#Override
public void onSensorChanged(SensorEvent event) {
if (event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD) {
// get values for each axes X,Y,Z
float magX = event.values[0];
float magY = event.values[1];
float magZ = event.values[2];
double magnitude = Math.sqrt((magX * magX) + (magY * magY) + (magZ * magZ));
// set value on the screen
value.setText(DECIMAL_FORMATTER.format(magnitude) + " \u00B5");
}
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
public void openActivity2(){
Intent intent=new Intent(this, Main2Activity.class);
startActivity(intent);
}
public void openActivity3(){
Intent intent=new Intent(this, Main3Activity.class);
startActivity(intent);
}
}
I have posted all the code for my project, this includes the xml and java code. im learning and just playing around with a project for fun. I have never ran into this error, I think it may have something to do with "public class MainActivity extends AppCompatActivity implements SensorEventListener" as this is my first time using something like this.
You are setting contentView 2 times.
setContentView(R.layout.activity_main);
Remove the later one.
You use setContentView(R.layout.activity_main) two times, Remove the second one.
I am trying to use the pedometer sensor in a fragment to count the number of steps that has been taken since the device last rebooted.
I can get the pedometer working in an Activity but cannot seem to get it working in the fragment. I am new to using fragments so it's probably very simple what I am doing wrong.
My class is below:
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import static com.example.application.placepicker.R.id.count;
public class Tab3 extends Fragment implements SensorEventListener {
private SensorManager sensorManager;
private TextView textView;
boolean activityRunning;
private Button buttonReturn;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.tab3, container, false);
return rootView;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
count = (TextView) getActivity().findViewById(count); **error
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE); **error
}
#Override
public void onResume() {
super.onResume();
activityRunning = true;
Sensor countSensor = sensorManager.getDefaultSensor(Sensor.TYPE_STEP_COUNTER);
if (countSensor != null) {
sensorManager.registerListener(this, countSensor, SensorManager.SENSOR_DELAY_UI);
} else {
Toast.makeText(this, "Count sensor not available!", Toast.LENGTH_LONG).show(); **error
}
}
#Override
public void onPause() {
super.onPause();
activityRunning = false;
}
#Override
public void onSensorChanged(SensorEvent event) {
if (activityRunning) {
count.setText(String.valueOf(event.values[0])); **error
}
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
}
My XML file to accompany this is:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.application.placepicker.TabbedActivity$PlaceholderFragment">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_marginTop="114dp"
android:gravity="center"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true">
<TextView
android:id="#+id/textLogin"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="Step counter"
android:textSize="40sp"
android:textColor="#color/colorAccent"
android:fontFamily="sans-serif"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="33dp"
android:layout_gravity="center_horizontal"
android:textSize="26dp"
android:text="Steps walked so far today:"
android:textColor="#color/colorAccent" />
<TextView
android:id="#+id/count"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="40dp"
android:layout_marginLeft="50dp"
android:text="---"
android:textColor="#color/colorAccent"
android:textSize="36dp" />
</LinearLayout>
You have no member variable for count
private SensorManager sensorManager;
private TextView textView;
boolean activityRunning;
private Button buttonReturn;
are examples of member variables in your fragment class
count = (TextView) getActivity().findViewById(count);
is setting a TextView to an unknown reference, please initialise count properly i.e.
TextView count = (TextView) getActivity().findViewById(count);
as a function member or:
private TextView count;
with the other class member variables
you will then need to call
sensorManager = (SensorManager) getActivity().getSystemService(Context.SENSOR_SERVICE)
as a fragment has no reference to the getSystemService method by itself, so it needs to go through it's holding activity
as well i know
you should change
count = (TextView) getActivity().findViewById(count);
to
count = (TextView)getView().findViewById(R.id.count);
cause you have to define view , don't call activity.
I am developing an android step counter that starts counting when i press a button and stops when i press the button again. The problem is that the counter always misses the first few steps i am using the step counter sensor introduced in android kitkat 4.4. I also tried the step detector sensor but had the same results.
I tried changing the delay when registering the sensor to fastest, game, normal, and I even tried to set the delay to 0 but nothing worked
Is there a way i can fix this?
this is a simple app that shows my problem
https://github.com/omaressameldin/simplestepcounter
MainActivity.java
package com.example.oessa_000.simplestepcounter;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.ToggleButton;
public class MainActivity extends AppCompatActivity implements SensorEventListener {
private SensorManager mSensorManager;
private Sensor mStepCounterSensor;
ToggleButton countToggle;
TextView stepView;
private int stepCount = 0;
boolean toggle = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
mStepCounterSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_STEP_COUNTER);
stepView = (TextView) findViewById(R.id.stepView);
countToggle = (ToggleButton) findViewById(R.id.countToggle);
;
countToggle.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
toggle = !toggle ;
if(toggle){
startListening();
}
else{
stopListening();
}
}
});
}
protected void startListening() {
mSensorManager.registerListener(this, mStepCounterSensor, SensorManager.SENSOR_DELAY_NORMAL);
}
protected void stopListening() {
mSensorManager.unregisterListener(this, mStepCounterSensor);
}
public void onResume() {
super.onResume();
}
#Override
public void onSensorChanged(SensorEvent event) {
Sensor sensor = event.sensor;
switch(sensor.getType()) {
case Sensor.TYPE_STEP_COUNTER:
if (toggle){
stepCount++;
stepView.setText("Step Count: " + stepCount);
}
break;
}
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.oessa_000.simplestepcounter.MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Step Count: 0"
android:textSize="15dp"
android:id="#+id/stepView"
/>
<ToggleButton
android:layout_width="200dp"
android:layout_height="75dp"
android:layout_centerHorizontal="true"
android:id="#+id/countToggle"
android:layout_margin="20dp"
android:textOff="Not Walking"
android:textOn="Walking"
android:layout_below="#+id/stepView"
/>
</RelativeLayout>
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.oessa_000.simplestepcounter">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<uses-feature android:name="android.hardware.sensor.stepcounter" />
</activity>
</application>
</manifest>
Edited: Added code snippets
I realized that using the predefined stepCounter sensor for small number of steps, like what i wanted, isn't the best option and implementing a counter using accelerometer would be a lot better; however it won't be recommended for building fitness apps or any app that require constant step counting for a long time because the delay in the stepcounting sensor is to neglect the false positives.
so this is my implementation of the stepcounter using accelerometer
MainActivity.java
package com.example.oessa_000.testcompass;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.NumberFormat;
import android.app.Activity;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.view.View;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.ToggleButton;
public class MainActivity extends Activity implements SensorEventListener{
// Gravity for accelerometer data
private float[] gravity = new float[3];
// smoothed values
private float[] smoothed = new float[3];
// sensor manager
private SensorManager sensorManager;
// sensor gravity
private Sensor sensorGravity;
private double bearing = 0;
private TextView acc;
private TextView stepView;
private TextView thresholdView;
private SeekBar seek;
private ToggleButton countToggle;
private int stepCount;
private boolean toggle;
private double prevY;
private double threshold;
private boolean ignore;
private int countdown;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
acc = (TextView) findViewById((R.id.accelerometer));
thresholdView = (TextView) findViewById((R.id.thresholdView));
stepView = (TextView) findViewById((R.id.stepView));
countToggle = (ToggleButton) findViewById(R.id.countToggle);
seek = (SeekBar) findViewById(R.id.seek);
seek.setProgress(0);
seek.incrementProgressBy(1);
seek.setMax(40);
// keep screen light on (wake lock light)
implementListeners();
}
protected float[] lowPassFilter( float[] input, float[] output ) {
if ( output == null ) return input;
for ( int i=0; i<input.length; i++ ) {
output[i] = output[i] + 1.0f * (input[i] - output[i]);
}
return output;
}
#Override
protected void onStart() {
super.onStart();
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensorGravity = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
// listen to these sensors
sensorManager.registerListener(this, sensorGravity,
SensorManager.SENSOR_DELAY_NORMAL);
}
#Override
protected void onStop() {
super.onStop();
// remove listeners
sensorManager.unregisterListener(this, sensorGravity);
}
#Override
public void onSensorChanged(SensorEvent event) {
// get accelerometer data
if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
// we need to use a low pass filter to make data smoothed
smoothed = lowPassFilter(event.values, gravity);
gravity[0] = smoothed[0];
gravity[1] = smoothed[1];
gravity[2] = smoothed[2];
acc.setText("x: "+gravity[0] + " y: " + gravity[1] + " z: " + gravity[2]+ "ignore: "+ ignore + "countdown: "+ countdown);
if(ignore) {
countdown--;
ignore = (countdown < 0)? false : ignore;
}
else
countdown = 22;
if(toggle && (Math.abs(prevY - gravity[1]) > threshold) && !ignore){
stepCount++;
stepView.setText("Step Count: " + stepCount);
ignore = true;
}
prevY = gravity[1];
}
}
public void implementListeners(){
seek.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress,boolean fromUser) {
threshold = ((double)seek.getProgress()) * 0.02;
thresholdView.setText("Threshold: "+ threshold);
}
});
countToggle.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
toggle = !toggle ;
if(toggle){
stepCount = 0;
countdown = 5;
ignore = true;
stepView.setText("Step Count: " + stepCount);
}
}
});
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.oessa_000.testcompass.MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
android:layout_below="#+id/degree"
android:id="#+id/accelerometer"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Step Count: 0"
android:textSize="24dp"
android:layout_centerHorizontal="true"
android:id="#+id/stepView"
android:layout_below="#+id/accelerometer"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
android:layout_marginBottom="0dp"
android:layout_below="#+id/stepView"
android:id="#+id/thresholdView"
/>
<SeekBar
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/seek"
android:layout_marginTop="0dp"
android:layout_below="#+id/thresholdView"
/>
<ToggleButton
android:layout_width="200dp"
android:layout_height="75dp"
android:layout_centerHorizontal="true"
android:id="#+id/countToggle"
android:layout_margin="20dp"
android:textOff="Not Walking"
android:textOn="Walking"
android:layout_below="#+id/seek"
/>
</RelativeLayout>
Adjusting the threshold sets the sensitivity of the sensor :)
Reference: http://nebomusic.net/androidlessons/Pedometer_Project.pdf
I need your help. I am trying to read the data from the sensors of the smart phone. That is why i tried to write some codes. After a while , i found a code on the Internet. But it does not work i do not know why. In this code , there are two pages for one to select a sensor and the other for the getting the data .
I am copying the codes here . And at the end i will tell you what the problem is.
Here is the MAIN activity code.
package com.example.sensorlistactivity;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
public class SensorListActivity extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sensor_main);
SensorSelectorFragment sensorSelect = (SensorSelectorFragment) getSupportFragmentManager()
.findFragmentById(R.id.frag_sensor_select);
SensorDisplayFragment sensorDisplay = (SensorDisplayFragment) getSupportFragmentManager()
.findFragmentById(R.id.frag_sensor_view);
sensorSelect.setSensorDisplay(sensorDisplay);
}
}
Here is the SENSOR SELECTOR CODE.
package com.example.sensorlistactivity;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.ListFragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
public class SensorSelectorFragment extends ListFragment {
private static final String TAG = "SensorSelectorFragment";
private SensorDisplayFragment sensorDisplay;
public void setSensorDisplay(SensorDisplayFragment sensorDisplay) {
this.sensorDisplay = sensorDisplay;
SensorManager sensorManager = (SensorManager) getActivity()
.getSystemService(Activity.SENSOR_SERVICE);
List<Sensor> sensors = sensorManager.getSensorList(Sensor.TYPE_ALL);
this.setListAdapter(new SensorListAdapter(getActivity()
.getApplicationContext(), android.R.layout.simple_list_item_1,
sensors));
}
private void showSensorFragment(Sensor sensor) {
sensorDisplay.displaySensor(sensor);
FragmentTransaction ft = getActivity().getSupportFragmentManager()
.beginTransaction();
ft.hide(this);
ft.show(sensorDisplay);
ft.addToBackStack("Showing sensor: " + sensor.getName());
ft.commit();
}
private class SensorListAdapter extends ArrayAdapter<Sensor> {
public SensorListAdapter(Context context, int textViewResourceId,
List<Sensor> sensors) {
super(context, textViewResourceId, sensors);
}
#Override
public View getView(final int position, View convertView,
ViewGroup parent) {
final Sensor selectedSensor = getItem(position);
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(
android.R.layout.simple_list_item_1, null);
}
((TextView) convertView).setText(selectedSensor.getName());
convertView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (BuildConfig.DEBUG) {
Log.d(TAG,
"display sensor! " + selectedSensor.getName());
}
showSensorFragment(selectedSensor);
}
});
return convertView;
}
}
}
Here is the DISPLAYMENT CODE .
package com.example.sensorlistactivity;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.content.Context;
import android.hardware.Sensor;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.TextView;
public class SensorDisplayFragment extends Fragment implements
SensorEventListener {
private static final String TAG = "SensorDisplayFragment";
private static final String THETA = "\u0398";
private static final String ACCELERATION_UNITS = "m/s\u00B2";
private SensorManager sensorManager;
private Sensor sensor;
private TextView name;
private TextView type;
private TextView maxRange;
private TextView minDelay;
private TextView power;
private TextView resolution;
private TextView vendor;
private TextView version;
private TextView accuracy;
private TextView timestampLabel;
private TextView timestamp;
private TextView timestampUnits;
private TextView dataLabel;
private TextView dataUnits;
private TextView xAxis;
private TextView xAxisLabel;
private TextView yAxis;
private TextView yAxisLabel;
private TextView zAxis;
private TextView zAxisLabel;
private TextView singleValue;
private TextView cosLabel;
private TextView cos;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View layout = inflater.inflate(R.layout.sensor_view, null);
sensorManager = (SensorManager) getActivity().getSystemService(
Context.SENSOR_SERVICE);
name = (TextView) layout.findViewById(R.id.name);
type = (TextView) layout.findViewById(R.id.type);
maxRange = (TextView) layout.findViewById(R.id.maxRange);
minDelay = (TextView) layout.findViewById(R.id.minDelay);
power = (TextView) layout.findViewById(R.id.power);
resolution = (TextView) layout.findViewById(R.id.resolution);
vendor = (TextView) layout.findViewById(R.id.vendor);
version = (TextView) layout.findViewById(R.id.version);
accuracy = (TextView) layout.findViewById(R.id.accuracy);
timestampLabel = (TextView) layout.findViewById(R.id.timestampLabel);
timestamp = (TextView) layout.findViewById(R.id.timestamp);
timestampUnits = (TextView) layout.findViewById(R.id.timestampUnits);
dataLabel = (TextView) layout.findViewById(R.id.dataLabel);
dataUnits = (TextView) layout.findViewById(R.id.dataUnits);
xAxis = (TextView) layout.findViewById(R.id.xAxis);
xAxisLabel = (TextView) layout.findViewById(R.id.xAxisLabel);
yAxis = (TextView) layout.findViewById(R.id.yAxis);
yAxisLabel = (TextView) layout.findViewById(R.id.yAxisLabel);
zAxis = (TextView) layout.findViewById(R.id.zAxis);
zAxisLabel = (TextView) layout.findViewById(R.id.zAxisLabel);
singleValue = (TextView) layout.findViewById(R.id.singleValue);
cosLabel = (TextView) layout.findViewById(R.id.cosLabel);
cos = (TextView) layout.findViewById(R.id.cos);
layout.findViewById(R.id.delayFastest).setOnClickListener(
new OnClickListener() {
public void onClick(View v) {
sensorManager
.unregisterListener(SensorDisplayFragment.this);
sensorManager.registerListener(
SensorDisplayFragment.this, sensor,
SensorManager.SENSOR_DELAY_FASTEST);
}
});
layout.findViewById(R.id.delayGame).setOnClickListener(
new OnClickListener() {
public void onClick(View v) {
sensorManager
.unregisterListener(SensorDisplayFragment.this);
sensorManager.registerListener(
SensorDisplayFragment.this, sensor,
SensorManager.SENSOR_DELAY_GAME);
}
});
layout.findViewById(R.id.delayNormal).setOnClickListener(
new OnClickListener() {
public void onClick(View v) {
sensorManager
.unregisterListener(SensorDisplayFragment.this);
sensorManager.registerListener(
SensorDisplayFragment.this, sensor,
SensorManager.SENSOR_DELAY_NORMAL);
}
});
layout.findViewById(R.id.delayUi).setOnClickListener(
new OnClickListener() {
public void onClick(View v) {
sensorManager
.unregisterListener(SensorDisplayFragment.this);
sensorManager.registerListener(
SensorDisplayFragment.this, sensor,
SensorManager.SENSOR_DELAY_UI);
}
});
return layout;
}
public void displaySensor(Sensor sensor) {
if (BuildConfig.DEBUG) {
Log.d(TAG, "display the sensor");
}
this.sensor = sensor;
name.setText(sensor.getName());
type.setText(String.valueOf(sensor.getType()));
maxRange.setText(String.valueOf(sensor.getMaximumRange()));
// minDelay.setText(String.valueOf(sensor.getMinDelay()));
power.setText(String.valueOf(sensor.getPower()));
resolution.setText(String.valueOf(sensor.getResolution()));
vendor.setText(String.valueOf(sensor.getVendor()));
version.setText(String.valueOf(sensor.getVersion()));
sensorManager.registerListener(this, sensor,
SensorManager.SENSOR_DELAY_NORMAL);
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
switch (accuracy) {
case SensorManager.SENSOR_STATUS_ACCURACY_HIGH:
this.accuracy.setText("SENSOR_STATUS_ACCURACY_HIGH");
break;
case SensorManager.SENSOR_STATUS_ACCURACY_MEDIUM:
this.accuracy.setText("SENSOR_STATUS_ACCURACY_MEDIUM");
break;
case SensorManager.SENSOR_STATUS_ACCURACY_LOW:
this.accuracy.setText("SENSOR_STATUS_ACCURACY_LOW");
break;
case SensorManager.SENSOR_STATUS_UNRELIABLE:
this.accuracy.setText("SENSOR_STATUS_UNRELIABLE");
break;
}
}
#Override
public void onSensorChanged(SensorEvent event) {
onAccuracyChanged(event.sensor, event.accuracy);
timestampLabel.setVisibility(View.VISIBLE);
timestamp.setVisibility(View.VISIBLE);
timestamp.setText(String.valueOf(event.timestamp));
timestampUnits.setVisibility(View.VISIBLE);
switch (event.sensor.getType()) {
case Sensor.TYPE_ACCELEROMETER:
showEventData("Acceleration - gravity on axis", ACCELERATION_UNITS,
event.values[0], event.values[1], event.values[2]);
break;
case Sensor.TYPE_MAGNETIC_FIELD:
showEventData("Abient Magnetic Field", "uT", event.values[0],
event.values[1], event.values[2]);
break;
case Sensor.TYPE_GYROSCOPE:
showEventData("Angular speed around axis", "radians/sec",
event.values[0], event.values[1], event.values[2]);
break;
case Sensor.TYPE_LIGHT:
showEventData("Ambient light", "lux", event.values[0]);
break;
case Sensor.TYPE_PRESSURE:
showEventData("Atmospheric pressure", "hPa", event.values[0]);
break;
case Sensor.TYPE_PROXIMITY:
showEventData("Distance", "cm", event.values[0]);
break;
case Sensor.TYPE_GRAVITY:
showEventData("Gravity", ACCELERATION_UNITS, event.values[0],
event.values[1], event.values[2]);
break;
case Sensor.TYPE_LINEAR_ACCELERATION:
showEventData("Acceleration (not including gravity)",
ACCELERATION_UNITS, event.values[0], event.values[1],
event.values[2]);
break;
case Sensor.TYPE_ROTATION_VECTOR:
showEventData("Rotation Vector", null, event.values[0],
event.values[1], event.values[2]);
xAxisLabel.setText("x*sin(" + THETA + "/2)");
yAxisLabel.setText("y*sin(" + THETA + "/2)");
zAxisLabel.setText("z*sin(" + THETA + "/2)");
if (event.values.length == 4) {
cosLabel.setVisibility(View.VISIBLE);
cos.setVisibility(View.VISIBLE);
cos.setText(String.valueOf(event.values[3]));
}
break;
case Sensor.TYPE_ORIENTATION:
showEventData("Angle", "Degrees", event.values[0], event.values[1],
event.values[2]);
xAxisLabel.setText(R.string.azimuthLabel);
yAxisLabel.setText(R.string.pitchLabel);
zAxisLabel.setText(R.string.rollLabel);
break;
case Sensor.TYPE_RELATIVE_HUMIDITY:
showEventData("Relatice ambient air humidity", "%", event.values[0]);
break;
case Sensor.TYPE_AMBIENT_TEMPERATURE:
showEventData("Ambien temperature", "degree Celcius",
event.values[0]);
break;
}
}
private void showEventData(String label, String units, float x, float y,
float z) {
dataLabel.setVisibility(View.VISIBLE);
dataLabel.setText(label);
if (units == null) {
dataUnits.setVisibility(View.GONE);
} else {
dataUnits.setVisibility(View.VISIBLE);
dataUnits.setText("(" + units + "):");
}
singleValue.setVisibility(View.GONE);
xAxisLabel.setVisibility(View.VISIBLE);
xAxisLabel.setText(R.string.xAxisLabel);
xAxis.setVisibility(View.VISIBLE);
xAxis.setText(String.valueOf(x));
yAxisLabel.setVisibility(View.VISIBLE);
yAxisLabel.setText(R.string.yAxisLabel);
yAxis.setVisibility(View.VISIBLE);
yAxis.setText(String.valueOf(y));
zAxisLabel.setVisibility(View.VISIBLE);
zAxisLabel.setText(R.string.zAxisLabel);
zAxis.setVisibility(View.VISIBLE);
zAxis.setText(String.valueOf(z));
}
private void showEventData(String label, String units, float value) {
dataLabel.setVisibility(View.VISIBLE);
dataLabel.setText(label);
dataUnits.setVisibility(View.VISIBLE);
dataUnits.setText("(" + units + "):");
singleValue.setVisibility(View.VISIBLE);
singleValue.setText(String.valueOf(value));
xAxisLabel.setVisibility(View.GONE);
xAxis.setVisibility(View.GONE);
yAxisLabel.setVisibility(View.GONE);
yAxis.setVisibility(View.GONE);
zAxisLabel.setVisibility(View.GONE);
zAxis.setVisibility(View.GONE);
}
#Override
public void onHiddenChanged(boolean hidden) {
super.onHiddenChanged(hidden);
if (hidden) {
if (BuildConfig.DEBUG) {
Log.d(TAG, "Unregistering listener");
}
sensorManager.unregisterListener(this);
}
}
#Override
public void onPause() {
super.onPause();
if (BuildConfig.DEBUG) {
Log.d(TAG, "onPause");
Log.d(TAG, "Unregistering listener");
}
sensorManager.unregisterListener(this);
}
}
Here is the problem : when I run this code , there is nullPointerExpection .
In the main activity , "sensorSelect" and "sensorDisplay" are null. In other words , this part does not work.
SensorSelectorFragment sensorSelect = (SensorSelectorFragment) getSupportFragmentManager()
.findFragmentById(R.id.frag_sensor_select);
SensorDisplayFragment sensorDisplay = (SensorDisplayFragment) getSupportFragmentManager()
.findFragmentById(R.id.frag_sensor_view);
Why is that so ?
Also i am using two layout .xml file . one of them sensor_main which is called by main code and the other one is sensor_view .
I am putting these codes also here , there could be a problem also with these since i do not understand how could it be possible two layout xml files.
SENSOR_MAIN.XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
>
<fragment
android:id="#+id/frag_sensor_select"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
class="root.gast.playground.sensor.SensorSelectorFragment" />
<fragment
android:id="#+id/frag_sensor_view"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
class="root.gast.playground.sensor.SensorDisplayFragment" />
</LinearLayout>
SENSOR_VIEW.XML
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true">
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical" >
<RadioGroup android:id="#+id/sensorRateSelector"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true" >
<RadioButton android:id="#+id/delayFastest"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="SENSOR_DELAY_FASTEST"
android:checked="false"/>
<RadioButton android:id="#+id/delayGame"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="SENSOR_DELAY_GAME"
android:checked="false"/>
<RadioButton android:id="#+id/delayNormal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="SENSOR_DELAY_NORMAL"
android:checked="true"/>
<RadioButton android:id="#+id/delayUi"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="SENSOR_DELAY_UI"
android:checked="false"/>
</RadioGroup>
<View android:id="#+id/seperator"
style="#style/line_separator"
android:layout_below="#id/sensorRateSelector" />
<TextView android:id="#+id/nameLabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/seperator"
android:layout_alignParentLeft="true"
android:text="Name:"
android:layout_marginRight="5dip" />
<TextView android:id="#+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/nameLabel"
android:layout_alignTop="#id/nameLabel"
android:layout_alignBottom="#id/nameLabel" />
<TextView android:id="#+id/typeLabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#id/nameLabel"
android:layout_below="#id/nameLabel"
android:text="Type:"
android:layout_marginRight="5dip" />
<TextView android:id="#+id/type"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/typeLabel"
android:layout_alignTop="#id/typeLabel"
android:layout_alignBottom="#id/typeLabel"/>
<TextView android:id="#+id/maxRangeLabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#id/nameLabel"
android:layout_below="#id/typeLabel"
android:text="Max Range:"
android:layout_marginRight="5dip" />
<TextView android:id="#+id/maxRange"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/maxRangeLabel"
android:layout_alignTop="#id/maxRangeLabel"
android:layout_alignBottom="#id/maxRangeLabel"/>
<TextView android:id="#+id/minDelayLabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#id/maxRangeLabel"
android:layout_below="#id/maxRangeLabel"
android:text="Min Delay:"
android:layout_marginRight="5dip" />
<TextView android:id="#+id/minDelay"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/minDelayLabel"
android:layout_alignTop="#id/minDelayLabel"
android:layout_alignBottom="#id/minDelayLabel"/>
<TextView android:id="#+id/powerLabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#id/minDelayLabel"
android:layout_below="#id/minDelayLabel"
android:text="Power:"
android:layout_marginRight="5dip" />
<TextView android:id="#+id/power"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/powerLabel"
android:layout_alignTop="#id/powerLabel"
android:layout_alignBottom="#id/powerLabel"
android:layout_marginRight="5dip"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/power"
android:layout_alignTop="#id/power"
android:layout_alignBottom="#id/power"
android:text="mA"/>
<TextView android:id="#+id/resolutionLabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#id/powerLabel"
android:layout_below="#id/powerLabel"
android:text="Resolution:"
android:layout_marginRight="5dip" />
<TextView android:id="#+id/resolution"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/resolutionLabel"
android:layout_alignTop="#id/resolutionLabel"
android:layout_alignBottom="#id/resolutionLabel"/>
<TextView android:id="#+id/vendorLabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#id/resolutionLabel"
android:layout_below="#id/resolutionLabel"
android:text="Vendor:"
android:layout_marginRight="5dip" />
<TextView android:id="#+id/vendor"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/vendorLabel"
android:layout_alignTop="#id/vendorLabel"
android:layout_alignBottom="#id/vendorLabel"/>
<TextView android:id="#+id/versionLabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/versionLabel"
android:layout_alignLeft="#id/vendorLabel"
android:layout_below="#id/vendorLabel"
android:text="Version:"
android:layout_marginRight="5dip" />
<TextView android:id="#+id/version"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/versionLabel"
android:layout_alignTop="#id/versionLabel"
android:layout_alignBottom="#id/versionLabel"/>
<TextView android:id="#+id/accuracyLabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#id/versionLabel"
android:layout_below="#id/versionLabel"
android:text="Accuracy:"
android:layout_marginRight="5dip" />
<TextView android:id="#+id/accuracy"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/accuracyLabel"
android:layout_alignTop="#id/accuracyLabel"
android:layout_alignBottom="#id/accuracyLabel"/>
<!-- timestamp -->
<TextView android:id="#+id/timestampLabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#id/accuracyLabel"
android:layout_below="#id/accuracyLabel"
android:layout_marginRight="5dip"
android:text="Timestamp:" />
<TextView android:id="#+id/timestamp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/timestampLabel"
android:layout_alignTop="#id/timestampLabel"
android:layout_alignBottom="#id/timestampLabel"
android:layout_marginRight="5dip"
android:visibility="gone" />
<TextView android:id="#+id/timestampUnits"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/timestamp"
android:layout_alignTop="#id/timestamp"
android:layout_alignBottom="#id/timestamp"
android:visibility="gone"
android:text="(ns)" />
<TextView android:id="#+id/dataLabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#id/accuracyLabel"
android:layout_below="#id/timestampLabel"
android:layout_marginRight="5dip"
android:visibility="gone"/>
<TextView android:id="#+id/dataUnits"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/dataLabel"
android:layout_alignTop="#id/dataLabel"
android:layout_alignBottom="#id/dataLabel"
android:visibility="gone" />
<TextView android:id="#+id/singleValue"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/dataUnits"
android:layout_alignTop="#id/dataUnits"
android:layout_alignBottom="#id/dataUnits"
android:visibility="gone" />
<!-- X axis -->
<TextView android:id="#+id/xAxisLabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#id/dataLabel"
android:layout_below="#id/dataLabel"
android:layout_marginRight="5dip"
android:visibility="gone"
android:text="#string/xAxisLabel" />
<TextView android:id="#+id/xAxis"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/xAxisLabel"
android:layout_alignTop="#id/xAxisLabel"
android:layout_alignBottom="#id/xAxisLabel"
android:layout_marginRight="5dip"
android:visibility="gone" />
<!-- Y axis -->
<TextView android:id="#+id/yAxisLabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#id/xAxisLabel"
android:layout_below="#id/xAxisLabel"
android:layout_marginRight="5dip"
android:visibility="gone"
android:text="#string/yAxisLabel" />
<TextView android:id="#+id/yAxis"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/yAxisLabel"
android:layout_alignTop="#id/yAxisLabel"
android:layout_alignBottom="#id/yAxisLabel"
android:layout_marginRight="5dip"
android:visibility="gone" />
<!-- Z axis -->
<TextView android:id="#+id/zAxisLabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#id/yAxisLabel"
android:layout_below="#id/yAxisLabel"
android:layout_marginRight="5dip"
android:visibility="gone"
android:text="#string/zAxisLabel" />
<TextView android:id="#+id/zAxis"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/zAxisLabel"
android:layout_alignTop="#id/zAxisLabel"
android:layout_alignBottom="#id/zAxisLabel"
android:layout_marginRight="5dip"
android:visibility="gone" />
<!-- cos value (for rotation vector only) -->
<TextView android:id="#+id/cosLabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#id/zAxisLabel"
android:layout_below="#id/zAxisLabel"
android:layout_marginRight="5dip"
android:visibility="gone"
android:text="cos(\u0398/2):" />
<TextView android:id="#+id/cos"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/cosLabel"
android:layout_alignTop="#id/cosLabel"
android:layout_alignBottom="#id/cosLabel"
android:layout_marginRight="5dip"
android:visibility="gone" />
</RelativeLayout>
</ScrollView>
Without seeing your manifest, I cannot answer this 100%, but I think what is going on is the app cannot build the display because it cannot reference your Sensor Fragments. Here is your package declaration for SensorDisplayFragment:
package com.example.sensorlistactivity;
so to use then in an xml file, you should have this as your class:
class="com.example.sensorlistactivity.SensorDisplayFragment" />
I have just started learning android. I have develop a program named Android Light Sensor that measure the Intensity of Light. Here is my code:
package com.AndroidLightSensor;
import com.example.andriodlightsensor.R;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
public class AndriodLightSensorActivity extends Activity {
ProgressBar lightMeter;
TextView textMax, textReading;
float counter;
Button read;
TextView display;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
counter = 0;
read = (Button) findViewById(R.id.bStart);
display = (TextView) findViewById(R.id.tvDisplay);
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
lightMeter = (ProgressBar)findViewById(R.id.lightmeter);
textMax = (TextView)findViewById(R.id.max);
textReading = (TextView)findViewById(R.id.reading);
SensorManager sensorManager
= (SensorManager)getSystemService(Context.SENSOR_SERVICE);
Sensor lightSensor
= sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
if (lightSensor == null){
Toast.makeText(AndriodLightSensorActivity.this,
"No Light Sensor! quit-",
Toast.LENGTH_LONG).show();
}else{
float max = lightSensor.getMaximumRange();
lightMeter.setMax((int)max);
textMax.setText("Max Reading(Lux): " + String.valueOf(max));
sensorManager.registerListener(lightSensorEventListener,
lightSensor,
SensorManager.SENSOR_DELAY_NORMAL);
}
}
SensorEventListener lightSensorEventListener
= new SensorEventListener(){
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// TODO Auto-generated method stub
}
#Override
public void onSensorChanged(SensorEvent event) {
// TODO Auto-generated method stub
if(event.sensor.getType()==Sensor.TYPE_LIGHT){
final float currentReading = event.values[0];
lightMeter.setProgress((int)currentReading);
textReading.setText("Current Reading(Lux): " + String.valueOf(currentReading));
read.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
display.setText("" + String.valueOf(currentReading));
}
});
}
}
};
}
Also The xml is:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/tvDisplay"
/>
<ProgressBar
android:id="#+id/lightmeter"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="80dp"
style="?android:attr/progressBarStyleHorizontal"
android:max="100"
android:progress="0"
/>
<TextView
android:id="#+id/max"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<TextView
android:id="#+id/reading"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<Button
android:layout_width="250dp"
android:layout_height="wrap_content"
android:text="Start"
android:layout_y="249dp"
android:textSize="30dp"
android:onClick="onButtonDown"
android:id="#+id/bStart"
></Button>
</LinearLayout>
I want to get the current value whenever I press the button; i:e the value should not keep changing (Like in Stop Watch, but the updated should replace the previous one). In Eclipse, It shows no error, but when I run on my device is says" Unfortunately, Android Light Sensor has stopped."
Please help!!
There are an error that is obvious.
If findViewById is used before setContentView(R.layout.main); the values returned are null.
When you try to use them you get an error.
Put this two lines after setContentView(R.layout.main);
read = (Button) findViewById(R.id.bStart);
display = (TextView) findViewById(R.id.tvDisplay);