Fix the ambient Temperature in Android - java

I successfully made an app to measure the ambient temperature in Android studio. But the next step doesn't want to work. here's the point:
when I start the app the temperature should be shown in 1 textView (works so far). Then it should stay with this temperature but it changes. I only want to check the temperature once.
when I click on submit it shall do the same with the second textView.
I did this successfully with the time but with the temperature, it won't work. And my second question is, I did a lot of research and it looks like the temperature will always be shown in °c. Can I change that so the people who want it in °F can have it this way?
Code for the temperature without change the value and with the button for getting the temperature on textView2:
MainActivity:
public class MainActivity extends AppCompatActivity implements SensorEventListener {
private TextView textView, textView2;
private Button button;
private SensorManager sensorManager;
private Sensor tempSensor;
private Boolean isTemperatureSensorAvailable;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.textView);
textView2 = findViewById(R.id.textView2);
button = findViewById(R.id.button);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
if(sensorManager.getDefaultSensor(Sensor.TYPE_AMBIENT_TEMPERATURE) !=null) {
tempSensor = sensorManager.getDefaultSensor(Sensor.TYPE_AMBIENT_TEMPERATURE);
isTemperatureSensorAvailable = true;
}else{
textView.setText("Temperature Sensor is not available");
isTemperatureSensorAvailable = false;
}
}
#Override
public void onSensorChanged(SensorEvent event) {
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
#Override
protected void onResume(){
super.onResume();
if(isTemperatureSensorAvailable){
sensorManager.registerListener(this,tempSensor, SensorManager.SENSOR_DELAY_NORMAL);
}
}
#Override
protected void onPause(){
super.onPause();
if(isTemperatureSensorAvailable){
sensorManager.unregisterListener(this);
}
}
private void update_text_unit()//Run from button
{
boolean toogle = false;
float temperature = 0;
float C_temp = 0;
float F_temp =0;
//Get sensor data
Sensor temp = sensorManager.getDefaultSensor(Sensor.TYPE_AMBIENT_TEMPERATURE);
F_temp = (C_temp * (9/5) +32);//Convert to °F
if(toogle = true) {
textView2.setText("Temp is:" + C_temp + "°C");
toogle = false;
}
else {
textView2.setText("Temp is:" + F_temp + "°F");
toogle = true;
}
}
}
I hope someone can help me going into a better direction.
Thanks for your help.

In the first code you have a section which is on sensor changed so this will run each time causing your issue. In you oncreate all the API to get the temperature once and chuck it to the text view as a string. For °C to °F you will need to convert. I would just do this manually:
(X°C × 9/5) + 32 = result_°F
Where X is the input temperature and result is the output in °F.

Here is an example of the button temp change feature not exactly sure how you read the temp so the line of Sensor.gettemp will probably need to change. Run this from a button push, it will update your text view
private void update_text_unit()//Run from button
{
boolean toogle = false;
float temperature = 0;
float C_temp = 0;
float F_temp =0;
//Get sensor data
C_temp = Sensor.gettemp();
F_temp = (C_temp * (9/5) +32);//Convert to °F
if(toogle = true) {
yourtextview.setText("Temp is:" + C_temp + "°C");
toogle = false;
}
else {
yourtextview.setText("Temp is:" + F_temp + "°F");
toogle = true;
}
}

Related

How to make the vibrate different according to the significant light value?

I want the app to vibrate accordingly to the light value detected. For example, when the value is higher then the vibration is stronger. But this code seems not working, anyone can help to see where is my mistake? It can detect the light value correctly and the vibration is working but the vibration is not vibrating according to the light value.
public class LightDetection extends AppCompatActivity {
TextView textLight, textOn, textOff;
Button btnStart, btnStop;
float x;
long ambientValue = 16;
long floor_delay = 500;
long ceiling_delay = 80;
long vibrate = 100;
long vibrate_delay;
Vibrator sensorVibrator;
SensorManager sensorManager;
Sensor sensor;
private Handler handler = new Handler();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_light_detection);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensor = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
sensorVibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
textLight = (TextView) findViewById(R.id.textView);
textOn = (TextView) findViewById(R.id.textView2);
textOff = (TextView) findViewById(R.id.textView3);
btnStart = (Button) findViewById(R.id.button3);
btnStop = (Button) findViewById(R.id.button4);
final SensorEventListener lightListener = new SensorEventListener() {
public void onAccuracyChanged(Sensor sensor, int acc) {
}
#SuppressLint("SetTextI18n")
public void onSensorChanged(SensorEvent event) {
float x = event.values[0];
Log.i("IE LightDetect.", "Light value: " + x);
textLight.setText((int) x + " lux");
}
};
btnStart.setOnClickListener(new View.OnClickListener() {
#SuppressLint("SetTextI18n")
public void onClick(View view) {
sensorManager.registerListener(lightListener, sensor,
SensorManager.SENSOR_DELAY_FASTEST);
handler.postDelayed(runnable, vibrate_delay);
textOn.setText("LIGHT DETECTION MODE: ON");
}
});
btnStop.setOnClickListener(new View.OnClickListener() {
#SuppressLint("SetTextI18n")
public void onClick(View view) {
textOn.setText("LIGHT DETECTION MODE: OFF");
sensorManager.unregisterListener(lightListener);
sensorVibrator.cancel();
handler.removeCallbacks(runnable);
}
});
}
private Runnable runnable = new Runnable() {
#Override
public void run() {
/* do what you need to do */
long luxValue = (long) x;
//Correction Ratio - Ceiling Delay/Most Likely Max Lux
long ratio = 950 / 300;
if (luxValue < ambientValue) {
vibrate = 100;
vibrate_delay = floor_delay + (ratio * luxValue);
} else {
vibrate = 100;
vibrate_delay = floor_delay - (ratio * luxValue);
}
if (vibrate_delay < ceiling_delay) {
long[] pattern = {0, vibrate, ceiling_delay};
sensorVibrator.vibrate(pattern, 1);
} else {
long[] pattern = {0, vibrate, vibrate_delay};
sensorVibrator.vibrate(pattern, 1);
}
Log.i("IE LightDetect.", "Lux: " + luxValue);
handler.postDelayed(this, vibrate_delay);
}
};
}`
After getting the light value in onSensorChanged() you are not saving the value globally, there u r using float x = event.values[0] which is just creating a local variable inside the function, and not the global one..try ditching the float from there, use x = event.values[0] instead of float x = event.values[0]..the it will save the value in the global variable and that you will use where you calculating vibration..

Display Temperature value with air pressure and altitude

Iam displaying my temperature sensor values in text view and also displaying air pressure from air pressure sensor with altitude in another two text view
the problem is that the first text view display air pressure instead of displaying temperature and the other text views display correct values of air pressure and altitude and i named the text view id correct but when i run the app it dosnt display temperature in first text view in the same activity and if i separate them in two activities it work good but i want to dislapy them in same activity and this is my code
public class TemperatureActivity extends Activity
implements SensorEventListener {
private SensorManager mSensorManager;
private Sensor mSensor;
private boolean isSensorPresent;
private TextView mTemperatureValue;
private TextView mPressureValue;
private TextView mAltitudeValue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSensorManager =
(SensorManager)this.getSystemService
(Context.SENSOR_SERVICE);
mTemperatureValue =
(TextView)findViewById(R.id.temperaturetext);
if(mSensorManager.getDefaultSensor
(Sensor.TYPE_AMBIENT_TEMPERATURE) != null) {
mSensor = mSensorManager.getDefaultSensor
(Sensor.TYPE_AMBIENT_TEMPERATURE);
isSensorPresent = true;
} else {
mTemperatureValue.setText("Ambient Temperature Sensor is not available!");
isSensorPresent = false;
}
mPressureValue =
(TextView)findViewById(R.id.pressuretext);
mAltitudeValue =
(TextView)findViewById(R.id.altitudetext);
mSensorManager = (SensorManager)
this.getSystemService(Context.SENSOR_SERVICE);
if(mSensorManager.getDefaultSensor
(Sensor.TYPE_PRESSURE) != null) {
mSensor = mSensorManager.getDefaultSensor
(Sensor.TYPE_PRESSURE);
isSensorPresent = true;
} else {
isSensorPresent = false;
mPressureValue.setText("Pressure Sensor is not available!");
mAltitudeValue.setText("Cannot calculate altitude, as pressure
Sensor is not available!");
}
}
#Override
protected void onResume() {
super.onResume();
if(isSensorPresent) {
mSensorManager.registerListener(this, mSensor,
SensorManager.SENSOR_DELAY_NORMAL);
}
}
#Override
protected void onPause() {
super.onPause();
if(isSensorPresent) {
mSensorManager.unregisterListener(this);
}
}
#Override
public void onSensorChanged(SensorEvent event) {
mTemperatureValue.setText("Temperature in degree Celsius is " +
event.values[0]);
float pressure = event.values[0];
mPressureValue.setText("Pressure in mbar is " +
pressure);
float altitude = SensorManager.getAltitude
(SensorManager.PRESSURE_STANDARD_ATMOSPHERE,
pressure);
mAltitudeValue.setText("Current altitude is " +
altitude);
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
}
#Override
public void onSensorChanged(SensorEvent event) {
mTemperatureValue.setText("Temperature in degree Celsius is " +
event.values[0]);
float pressure = event.values[0];
mPressureValue.setText("Pressure in mbar is " +
pressure);
float altitude = SensorManager.getAltitude
(SensorManager.PRESSURE_STANDARD_ATMOSPHERE,
pressure);
mAltitudeValue.setText("Current altitude is " +
altitude);
}
Completely broken. Every sensor event, you're writing the same value to multiple fields. You get one event per sensor. You should update the temperature only when you get a temperature event, the pressure only when you get a pressure event, etc.

in java code using savedInstanceState to save a reusable value

I am developing an android app and want to save a rand2(Double type) value using savedInstanceState so that i can use rand2 value whenever app is reopened but while retrieving rand2 value it always comes NULL, Either the value is not saving or value is not retrieving . Why it is happening and what should i do to save rand2 value so that i can reuse it when the app is reopened?
public class MainActivity extends AppCompatActivity {
double rand2;
private boolean started = false;
private Handler handler = new Handler();
public Runnable runnable = new Runnable() {
#Override
public void run() {
double rand1 = Math.random() * 5;
rand2 = rand2 + rand1 * 0.04;
DecimalFormat df = new DecimalFormat("0.00");
String message1 = "" + df.format(rand1);
DecimalFormat dff = new DecimalFormat("000000.00");
String message2 = "" + dff.format(rand2);
displayRate(message1);
displaySatoshi(message2);
if (started) {
start(started);
}
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// recovering the instance state
// Restore UI state from the savedInstanceState.
// This bundle has also been passed to onCreate.
if (savedInstanceState != null) {
rand2 = savedInstanceState.getDouble("abc");
} else {
rand2 = 0.00;
}
setContentView(R.layout.activity_main);
// Find the View that shows the numbers category
TextView numbers = (TextView) findViewById(withdraw);
// Set a click listener on that View
numbers.setOnClickListener(new View.OnClickListener() {
// The code in this method will be executed when the numbers View is clicked on.
#Override
public void onClick(View view) {
Intent numbersIntent = new Intent(MainActivity.this, Withdraw.class);
startActivity(numbersIntent);
}
});
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
savedInstanceState.putDouble("abc", rand2);
// call superclass to save any view hierarchy
super.onSaveInstanceState(savedInstanceState);
}
public void Start(View v) {
ToggleButton starStopTogglrButton = (ToggleButton) findViewById(R.id.start_stop);
boolean hasStartStop = starStopTogglrButton.isChecked();
if (hasStartStop) {
start(hasStartStop);
} else {
stop(hasStartStop);
}
}
public void stop(Boolean hasStartStop) {
//Checking start or stop
started = hasStartStop;
handler.removeCallbacks(runnable);
}
public void start(Boolean hasStartStop) {
started = hasStartStop;
handler.postDelayed(runnable, 1000);
}
private void displayRate(String message1) {
TextView orderSummaryTextView = (TextView) findViewById(R.id.rate);
orderSummaryTextView.setText(message1);
}
private void displaySatoshi(String message2) {
TextView orderSummaryView = (TextView) findViewById(R.id.satoshis);
orderSummaryView.setText(message2);
}
}
onSaveInstanceState is called when the app is closed, but onCreate is only called when the app is booted after it's been finished. Remember the acitvity lifecycle:
So since onSaveInstanceState is called at closing and onCreate only is called when the activity is (re)created, it is null because it isn't added at that time.
You're looking for onRestoreInstanceState. Override that method and grab the variable and assign it from there.
Remember that using the savedInstanceState does not save the data if the activity is completely destroyed. For persistent data storage, use sharedprefs, files or SQL

How to reset the step count from android

public class speedDetection extends Activity implements SensorEventListener {
private TextView textView;
private SensorManager mSensorManager;
private Sensor mStepCounterSensor;
private Sensor mStepDetectorSensor;
// boolean flag = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_speed_detection);
//pass in the level from time to time.
//int level = this.getIntent().getIntExtra("Level",0);
textView = (TextView) findViewById(R.id.textView);
//Toast.makeText(getApplicationContext(), level, Toast.LENGTH_LONG).show();
mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
mStepCounterSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_STEP_COUNTER);
mStepDetectorSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_STEP_DETECTOR);
}
#Override
public void onSensorChanged(SensorEvent event) {
Sensor sensor = event.sensor;
float[] values = event.values;
int stepsInSensor = -1;
/*if (!flag) {
//Reset the count when reset the apps
int initValue = (int) values[values.length - 1];
stepsInSensor = stepsInSensor - initValue;
}*/
if (values.length > 0) { //some values was inside
stepsInSensor = (int) values[0]; //the latest value added will be at value[0]
}
if (sensor.getType() == Sensor.TYPE_STEP_COUNTER) {
textView.setText("Step Counter Detected : " + stepsInSensor);
} else if (sensor.getType() == Sensor.TYPE_STEP_DETECTOR) {
textView.setText("Step Detector Detected : " + stepsInSensor);
}
}
#Override
public void onAccuracyChanged(Sensor sensor, int i) { }
protected void onResume() {
super.onResume();
mSensorManager.registerListener(this, mStepCounterSensor, SensorManager.SENSOR_DELAY_FASTEST);
mSensorManager.registerListener(this, mStepDetectorSensor,SensorManager.SENSOR_DELAY_FASTEST);
}
protected void onStop() {
super.onStop();
mSensorManager.unregisterListener(this, mStepCounterSensor);
mSensorManager.unregisterListener(this, mStepDetectorSensor);
}
}
Anyone have idea how to reset the stepInSensor started with 0 everytime the apps started?
the Sensor.TYPE_STEP_COUNTER can only reset when the device reboot.
I found a post answering this question was like "store the first value returned as initial value, then subtract subsequent value by it."
but how exactly it can be done?
Use the following code
private static final String Initial_Count_Key = "FootStepInitialCount";
final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
// Initialize if it is the first time use
if(!prefs.contains(Initial_Count_Key)){
Editor editor = prefs.edit();
editor.putInt(Initial_Count_Key, stepsInSensor);
editor.commit();
}
How to get the step count
// return -1 if it is not initialize
int startingStepCount = prefs.getInt(Initial_Count_Key, -1);
int stepCount = stepsInSensor - startingStepCount;
How to reset (Reset the starting value)
Editor editor = prefs.edit();
editor.putInt(Initial_Count_Key, stepsInSensor);
editor.commit();
It's just math, right?
Store the initial step count when the app starts. When you try to get the new step value, simply subtract the initial value from the current step sensor value. That tells you exactly how many steps have been taken since the app started.

How to calibrate orientation sensors in android

I'm trying to get data from my phone's gyros.
So far,the angles keep changing depends on the angle that i move my phone.
However, the azimuth angle for example, i want it to start counting from the position i started and not from the north direction --> i want it to start from 0.
my question is: how can i save the first data i get from the gyro so i could do "minus" from the rest of the data when i move the phone?
The code looks like this:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sm=(SensorManager)getSystemService(Context.SENSOR_SERVICE);
rotationvector=sm.getDefaultSensor(Sensor.TYPE_ORIENTATION);
sm.registerListener(this,rotationvector,SensorManager.SENSOR_DELAY_NORMAL);
rotationx=(TextView)findViewById(R.id.rotationx);
rotationy=(TextView)findViewById(R.id.rotationy);
rotationz=(TextView)findViewById(R.id.rotationz);
}
#Override
public void onSensorChanged(SensorEvent event) {
rotationx.setText(" " +event.values[0]);
rotationy.setText(" " +event.values[1]);
rotationz.setText(" " +event.values[2]);
}
The thing i want to do is like:
rotationx.setText(" " +event.values[0]-FirstAzimuthValue);
Thanks!
new code:
private boolean isFirstMeasure = true;
private float FirstAzimuthValue = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sm=(SensorManager)getSystemService(Context.SENSOR_SERVICE);
rotationvector=sm.getDefaultSensor(Sensor.TYPE_ORIENTATION);
sm.registerListener(this,rotationvector,SensorManager.SENSOR_DELAY_NORMAL);
rotationx=(TextView)findViewById(R.id.rotationx);
rotationy=(TextView)findViewById(R.id.rotationy);
rotationz=(TextView)findViewById(R.id.rotationz);
}
#Override
public void onSensorChanged(SensorEvent event) {
if (isFirstMeasure){
FirstAzimuthValue - event.values[0]; //error this line
isFirstMeasure = false;
}
rotationx.setText(" " +(event.values[0] - FirstAzimuthValue));
rotationy.setText(" " +event.values[1]);
rotationz.setText(" " +event.values[2]);
}
Why not just
private boolean isFirstMeasure = true;
private float firstAzimuthValue = 0;
// ...
#Override
public void onSensorChanged(SensorEvent event) {
if (isFirstMeasure) {
firstAzimuthValue = event.values[0];
isFirstMeasure = false;
}
rotationx.setText(" " + (event.values[0] - firstAzimuthValue));
rotationy.setText(" " +event.values[1]);
rotationz.setText(" " +event.values[2]);
}

Categories