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);
Related
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.
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>
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 have tried everything but still am not able to figure out what is wrong in this code, whenever I click on the Button 'Get Fare' , a dialog opens showing "Unfortunately app has stopped". Please help ...
Code for MetroFare.java
package com.myapp.anuj;
import com.myapp.anuj.MetroFare;
import com.myapp.anuj.R;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
public class MetroFare extends Activity implements OnClickListener, OnItemSelectedListener{
String start[] = {"Shastri Nagar", "Kashmere Gate", "Dwarka Mor"};
String dest[] = {"Pratap Nagar", "Rajiv Chowk", "Kirti Nagar"};
Spinner starting, destination;
Button getfare;
int fare = 0;
int s=0, d=0;
TextView result;
int farearray[][] = {{8,15,14}, {10,12,15}, {21,18,15}};
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.kuchbhi);
getfare = (Button) findViewById(R.id.bGetFare);
result = (TextView) findViewById(R.id.tvShowFare);
getfare.setOnClickListener(this);
ArrayAdapter<String> adapterStart = new ArrayAdapter<String>(MetroFare.this, android.R.layout.simple_spinner_item, start);
ArrayAdapter<String> adapterDest = new ArrayAdapter<String>(MetroFare.this, android.R.layout.simple_spinner_item, dest);
starting = (Spinner) findViewById(R.id.spinnerStart);
destination = (Spinner) findViewById(R.id.spinnerDest);
starting.setAdapter(adapterStart);
destination.setAdapter(adapterDest);
starting.setOnItemSelectedListener(this);
destination.setOnItemSelectedListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String sfare = getString(fare);
result.setText(sfare);
}
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
s = starting.getSelectedItemPosition();
d = destination.getSelectedItemPosition();
fare = farearray[s][d];
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
Code for kuchbhi.xml
<?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:orientation="vertical" >
<Spinner
android:id="#+id/spinnerStart"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Spinner
android:id="#+id/spinnerDest"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:id="#+id/bGetFare"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Get Fare" />
<TextView
android:id="#+id/tvShowFare"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView" />
</LinearLayout>
As I mentioned, your problem is this call: getString(fare), which is attempting to retrieve a String resource with an id the value of fare. Judging from your code, I'm assuming that you're simply trying to display the String value of fare in a TextView, in which case change that call as follows:
String sfare = String.valueOf(fare);
(ANDROID GPS)
actually i am new in android and since i am a c++ programmer so am facing some difficulty in this program which is to take the gps location of the android mobile and send it as sms to the given number. but since it is in java so please can someone tell me what the different XML for this program will be...i mean the string and main xmls
package com.adzz.gps;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.content.Context;
import android.telephony.SmsManager;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import android.view.View.OnClickListener;
public class MainActivity extends Activity {
String m;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
LocationManager manager= (LocationManager)
this.getSystemService(Context.LOCATION_SERVICE);
LocationListener listener =new LocationListener() {
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onLocationChanged(Location location) {
final String phoneNumber="9453603045";
double lat1=location.getLatitude();
Double d1= new Double(lat1);
double longi1=location.getLongitude();
Double d2=new Double(longi1);
m="latitude = "+ d1.toString() + "and latitude = "+ d2.toString();
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phoneNumber, null, m, null, null);
TextView lat= (TextView) findViewById(R.id.lat);
TextView longi=(TextView) findViewById(R.id.longi);
lat.setText("latitude = "+lat1);
longi.setText("longitude ="+longi1);
}
};
manager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 25,
listener);
Button b= (Button) findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast toast=Toast.makeText(Main.this, m, 5000);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
<?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:orientation="vertical" >
<TextView
android:id="#+id/lat"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp" />
<TextView
android:id="#+id/longi"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp" />
<Button
android:id="#id/button1"
android:layout_gravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
First you need to create main.xml in layout folder in res directory. This is the main layout which is loading in your Activity , take two TextView inside main.xml with id named as lat and longi. main.xml is given below.
<?xml version="1.0" encoding="utf-8"?>
<TextView
android:id="#+id/lat"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="195dp"
android:text="Lattitude" />
<TextView
android:id="#+id/longi"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView2"
android:layout_alignParentTop="true"
android:layout_marginTop="82dp"
android:text="Longitude" />