Accelerometer application - java

I must do an application that returns a random number by shaking the phone. I've made it with a button and it works fine. The problems is with the accelerometer. It doesn't works, even though I have no errors.
import java.util.Random;
import android.app.Activity;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class RandomButtonActivity extends Activity implements SensorEventListener
{
Button tasto1;
TextView testo;
TextView message;
EditText limiteMin;
EditText limiteMax;
Random generator = new Random();
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
testo = (TextView) findViewById(R.id.textView1);
limiteMin = (EditText) findViewById(R.id.editText2);
limiteMax = (EditText) findViewById(R.id.EditText01);
}
public void onSensorChanged(SensorEvent event)
{
Sensor sensor = event.sensor;
if (sensor.getType()==Sensor.TYPE_ACCELEROMETER)
{
int j = Integer.parseInt(limiteMin.getText().toString());
int i = Integer.parseInt(limiteMax.getText().toString())-j;
int x = 0;
if(i==0 && j==0)
{
x = generator.nextInt();
while(x<0)
{
x = generator.nextInt();
}
}
else
{
if(j>=i)
{
i = 0;
j = 0;
}
else
{
x = generator.nextInt(i+1)+j;
testo.setText(""+x);
}
}
testo.setText(""+x);
}
else
{
}
}
public void onAccuracyChanged(Sensor sensor, int accuracy)
{
}
}
Looking around the internet this code should work just fine. I've done nothing to the XML file.
EDIT:
I added:
<uses-feature android:name="android.hardware.sensor.accelerometer" android:required="true"
to Android:manifest but nothing has changed.

It seems that you never add your class as an event listener.
This code works for me:
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//This is what you are missing:
sm = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sm.registerListener(this, sm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_UI);
}
public void onSensorChanged(SensorEvent event)
{
Sensor sensor = event.sensor;
if (sensor.getType() == Sensor.TYPE_ACCELEROMETER)
{
/// Do something
}
}
public void onAccuracyChanged(Sensor sensor, int accuracy)
{
}
It is also a good idea to override onResume/onStop/onPause like this
#Override protected void onResume()
{
super.onResume();
sm.registerListener(this, sm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL);
}
#Override protected void onStop()
{
sm.unregisterListener(this);
super.onStop();
}
And as ernell mentioned always remember to have the permissions you need in the manifest.

Related

Moving a sprite via a gyroscope

So i have 2 questions
first i am curious if its possible to move a sprite via a gyroscope
second if so, do i need to specify the movement of the sprite's X & Y or will that be automatic
and/or do i get the gyro's X & Y movement or is that automatic
#beginner
package com.thejames.thesphere;
import androidx.appcompat.app.AppCompatActivity;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.widget.ImageView;
public class MainActivity extends AppCompatActivity {
private ImageView thesphere;
private SensorManager sensorManager;
private Sensor gyroscopeSensor;
private SensorEventListener gyroscopeEventListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
gyroscopeSensor = sensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE);
gyroscopeEventListener = new SensorEventListener() {
#Override
public void onSensorChanged(SensorEvent sensorEvent) {
if (sensorEvent.values(2) > 0.5f) {
//Sphere+Movement
} else if (sensorEvent.values(2) < -0.5f) {
//Sphere-Movement
}
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
thesphere = findViewById(R.id.thesphere);
}
#Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(gyroscopeEventListener, gyroscopeSensor, sensorManager.SENSOR_DELAY_FASTEST);
}
#Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(gyroscopeEventListener);
}
}

Dynamically change the status of a ProgressBar based on two TextFields

I'm trying to change the status of a ProgressBar while the user is typing a text on either text fields.
For example , the user starts typing on the first TextView, the ProgressBar should change it's value, if he deletes the text, it should reset to the previous value which is 30
package com.example.phill.jokes;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;
public class Entry extends AppCompatActivity {
private ProgressBar pr;
private Handler rHandler = new Handler();
private TextView tv ;
private TextView tv2 ;
private boolean titleboolean;
private boolean jokeboolean;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_entry);
pr = (ProgressBar) findViewById(R.id.progressBar);
tv=(TextView) findViewById(R.id.textView9) ;
tv2=(TextView) findViewById(R.id.textView6) ;
new Thread(new Runnable() {
#Override
public void run() {
while (true)
{
android.os.SystemClock.sleep(300);
rHandler.post(new Runnable() {
#Override
public void run() {
pr.setProgress(30);
if(tv.getText().toString().matches(""))
{
titleboolean=true;
}
else
titleboolean=false;
if(tv2.getText().toString().matches(""))
{
jokeboolean=true;
}
else
jokeboolean=false;
if(titleboolean)
{
pr.setProgress(60);
}
if(jokeboolean)
{
pr.setProgress(100);
}
}
});
if(titleboolean && jokeboolean)
break;
}
rHandler.post(new Runnable() {
#Override
public void run() {
if(titleboolean && jokeboolean){
tv2.setVisibility(View.INVISIBLE);
tv.setVisibility(View.VISIBLE);
}
;
}
});
}
}).start();
}
}
The value of the ProgressBar never changes.
Any Ideas?
Let me explain you in detail
if(titleboolean && jokeboolean)
break;
when your both text fields clears it calls break statement after that your thread stops running you can achieve this in another way
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.ProgressBar;
import android.widget.TextView;
public class TestActivity extends AppCompatActivity
{
private ProgressBar pr;
private EditText tv;
private EditText tv2;
private boolean titleboolean;
private boolean jokeboolean;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
pr=(ProgressBar)findViewById(R.id.progressBar);
tv = (EditText) findViewById(R.id.tv);
tv2 = (EditText) findViewById(R.id.tv2);
TextView tV = new TextView(this);
tV.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence
s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s,
int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
setProgress();
}
});
tv2.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence
s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s,
int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
setProgress();
}
});
}
public void setProgress() {
pr.setProgress(30);
if (tv.getText().toString().matches("")) {
titleboolean = true;
} else
titleboolean = false;
if (tv2.getText().toString().matches("")) {
jokeboolean = true;
} else
jokeboolean = false;
if (titleboolean) {
pr.setProgress(60);
}
if (jokeboolean) {
pr.setProgress(100);
}
}
}
Use EditText instead TextView with TextChangedListener.
TextView does not allow to type text.
Also infinite cycle with pauses is bad approach, use EditText.addTextChangedListener to handle text after it have changed

I am working on a simple pedometer app, and it has these errors, for the following code

package com.example.ritwik.letswalk;
import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity implements SensorEventListener{
TextView tv_steps;
SensorManager sensorManager;
boolean running=false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv_steps=(TextView) findViewById(r.id.tv_steps);
sensorManager=(SensorManager) getSystemService(Context.SENSOR_SERVICE);
}
#Override
protected void onResume()
{
super.onResume();
running=true;
Sensor countSensor=sensorManager.getDefaultSensor(Sensor.TYPE_STEP_COUNTER);
if(countSensor==null){
sensorManager.registerListener(this, countSensor, SensorManager.SENSOR_DELAY_UI);
}
else
Toast.makeText(this, "Sensor Not Found",Toast.LENGTH_SHORT).show();
}
#Override
protected void onPause()
{
super.onPause();
running=false;
}
#Override
protected void onSensorChangeed(SensorEvent event)
{
if(running)
{
tv_steps.setText(String.valueOf(event.values[0]));
}
}
}
the code has the following errors
Error:(21, 15) error: cannot find symbol class TextView
Error:Execution failed for task ':app:compileDebugJavaWithJavac'.
Compilation failed; see the compiler error output for details. Error:(12, 5) error: cannot find symbol class TextView Error:(43, 37)
error: cannot find symbol class SensorEvent Error:(11, 8) error:
MainActivity is not abstract and does not override abstract method
onAccuracyChanged(Sensor,int) in SensorEventListener Error:(21, 39)
error: package r does not exist Error:(42, 5) error: method does not
override or implement a method from a supertype
SensorEventListener has two abstract methods :
1) onAccuracyChanged(Sensor sensor, int accuracy)
2) onSensorChanged(SensorEvent event)
You need to override onAccuracyChanged method too.
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
This method is called when the accuracy of sensor changes. If you don't wish to do anything here then do not write any code here. But since its abstract you need to implement it.
Hope it helps.
In my pedometer app I did
public void onSensorChanged(SensorEvent event) {
Sensor sensor = event.sensor;
float[] values = event.values;
if (values.length > 0) {
value = (int) values[0];
}
if (sensor.getType() == Sensor.TYPE_STEP_COUNTER) {
textView.setText("" + value);
}
}
public void onAccuracyChanged(Sensor sensor,int a){}
If you want the whole code: Here it is:
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.widget.TextView;
public class CounterActivity extends Activity implements SensorEventListener {
private TextView textView;
private SensorManager mSensorManager;
private Sensor mStepCounterSensor;
private Sensor mStepDetectorSensor;
int value = -1; //Step Counter
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.counter_activity);
textView = (TextView) findViewById(R.id.steps);
mSensorManager = (SensorManager)
getSystemService(Context.SENSOR_SERVICE);
mStepCounterSensor = mSensorManager
.getDefaultSensor(Sensor.TYPE_STEP_COUNTER);
mStepDetectorSensor = mSensorManager
.getDefaultSensor(Sensor.TYPE_STEP_DETECTOR);
}
public void onAccuracyChanged(Sensor sensor,int a){}
public void onSensorChanged(SensorEvent event) {
Sensor sensor = event.sensor;
float[] values = event.values;
if (values.length > 0) {
value = (int) values[0];
}
if (sensor.getType() == Sensor.TYPE_STEP_COUNTER) {
textView.setText("" + value);
}
}
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);
}
}

How can I track how many miles the user has walked?

I have made some java code in android studio to where it counts how many steps someone takes but I'm not sure how I can make it to where it counts how many miles the user walks. Here is the code.
If anyone can tell me how to do it that would be appreciated, Thanks.
package com.example.andyheggis.healthapp;
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.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity implements SensorEventListener {
TextView tv_steps;
SensorManager sensorManager;
boolean running = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv_steps = (TextView) findViewById(R.id.tv_steps);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
}
#Override
protected void onResume() {
super.onResume();
running = true;
Sensor countSensor = sensorManager.getDefaultSensor(Sensor.TYPE_STEP_COUNTER);
if(countSensor != null) {
sensorManager.registerListener(this, countSensor, SensorManager.SENSOR_DELAY_UI);
} else {
Toast.makeText(this, "Sensor not found!", Toast.LENGTH_LONG).show();
}
}
#Override
protected void onPause() {
super.onPause();
running = false;
//if you unregister the hardware will stop detecting steps
//sensorManager.unregisterListener(this);
}
#Override
public void onSensorChanged(SensorEvent event) {
if(running) {
tv_steps.setText(String.valueOf(event.values[0]));
}
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
}

I need to generate and display a random number in SystemClock.sleep() with no range

I'm a student at a community college. The following is the Main Activity in which I was tasked to generate a random number instead of the 5 milliseconds to run the sleep()method. I then have to display that random number. I figured out how to accomplish it for the first button, but I keep running into snags for the next two(converting to int, converting to a string for resultsTextView.setText();. I have tried several times to code a method, but then I'm running into other errors because onCreate is void.
package com.example.dan.hour5application;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.os.AsyncTask;
import android.os.SystemClock;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.util.Random;
public class MainActivity extends AppCompatActivity {
Button uiThreadButton;
Button postButton;
Button asyncTaskButton;
TextView resultsTextView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Resources res = getResources();
float fontSize = res.getDimension(R.dimen.font_size);
resultsTextView = (TextView) findViewById(R.id.textView);
uiThreadButton = (Button) findViewById(R.id.uiThreadButton);
uiThreadButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
/////Achieved a random number here////
Random random = new Random();
int x = random.nextInt(10);
SystemClock.sleep(x);
String aString = Integer.toString(x);
resultsTextView.setText(aString);
}
});
postButton = (Button) findViewById(R.id.post);
postButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new Thread(new Runnable() {
public void run() {
resultsTextView.post(new Runnable() {
#Override
public void run() {
resultsTextView.setText("Updated");
}
});
}
}).start();
}
});
asyncTaskButton = (Button) findViewById(R.id.asynctask);
class DelayTask extends AsyncTask<Integer, Integer, Integer> {
#Override
protected void onPreExecute() {
resultsTextView.setText("Starting AsyncTask");
}
#Override
protected void onPostExecute(Integer result) {
if (result == 0) {
resultsTextView.setText("Updated via AsyncTask");
}
}
#Override
protected Integer doInBackground(Integer... params) {
SystemClock.sleep(5000);
return 0;
}
}
}
}
I have looked at several other examples on Stack, but they aren't quite what I'm doing. I'm only starting my 4th month in Android Development, and I'm still trying to learn Java. The assignment is long gone, and my instructor didn't provide me with help when I asked. Thanks for your help!

Categories