Android java help

  • Replies:3
Elia Tancredi
  • Forum posts: 2

Apr 21, 2016, 5:54:17 PM via Website

Hi everyone, i'm new here (sorry for my bad english). I'm facing a problem when trying to use accelerometer sensor in an app (based on the MapsActivity) developed by me. For the moment this app only let the user move to certain places and add a marker by tapping on displayed buttons. I would like to make this app moving the marker by simply moving the device (using accelerometer). I used this code in addition to the positioning management code:
private SensorManager mSensorManager;
private Sensor sensor;

public void onSensorChanged(SensorEvent event) {
    if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
        Context context = getApplicationContext();
        CharSequence text = "Hello toast!";
        int duration = Toast.LENGTH_SHORT;

        Toast toast = Toast.makeText(context, text, duration);
        toast.show();
    }
}

For the moment it sould only show up a toast message to test it, but it doesn't work. How could i solve this problem?
Thanks in advance.

Reply
Vladimir S.
  • Forum posts: 266

Apr 21, 2016, 6:23:04 PM via Website

Hi. Try this:

public void onSensorChanged(SensorEvent event) {
    if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
        CharSequence text = "Hello toast!";
        int duration = Toast.LENGTH_SHORT;

        Toast toast = Toast.makeText(this, text, duration);
        toast.show();
    }
}

Did you register Activity as SensorEventListener?

— modified on Apr 21, 2016, 6:26:58 PM

Reply
Elia Tancredi
  • Forum posts: 2

Apr 21, 2016, 6:29:53 PM via Website

no it was prebuilt, it says:
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback
now it gives me an error about gradle version, but it seems to be fixing on its own
update: above problems solved but still not showing the toast message

— modified on Apr 21, 2016, 6:37:06 PM

Reply
Vladimir S.
  • Forum posts: 266

Apr 21, 2016, 8:18:28 PM via Website

You need to implement SensorEventListener in MapsActivity:

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, SensorEventListener {

and to do some other things. Read this for details.

Reply