1

I am working on a project where I want to collect sensor data with coordinates and save them to a csv file.

The app was working perfectly before I started coding for getting the location.

I am using location manager but every time I install this app on my device the application just doesn't seem to work. I disappears after few seconds of installation.

Also note that I am saving the sensor data in every 20 milliseconds so should I collect the coordinate data in the same rate?

Sorry to put the whole code but I need help! Please let me know where should I make changes?



public class MainActivity extends AppCompatActivity implements SensorEventListener, LocationListener {
    private SensorManager sensorManager;
    private Sensor magnetic;

    //Location
    LocationManager locationManager;
    Handler handler;
    Location location;

    double latitude;
    double longitude;

    // --o


    private int counter = 1;

    private boolean recording = false;
    private boolean counterOn = false;

    private float magValues[] = new float[3];

    private Context context;

    private static final int REQUESTCODE_STORAGE_PERMISSION = 1;

    Collection<String[]> magneticData = new ArrayList<>();

    private CsvWriter csvWriter = null;

    public static DecimalFormat DECIMAL_FORMATTER;

    TextView stateText;
    EditText fileIDEdit;

    //Location
    TextView lat;
    TextView lon;
    //--o

    TextView magText;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //Location
        handler = new Handler();

        lat = (TextView) findViewById(R.id.latitudeTextView);
        lon = (TextView) findViewById(R.id.longitudeTextView);

        //--o


        findViewById(R.id.button).setOnClickListener(listenerStartButton);
        findViewById(R.id.button2).setOnClickListener(listenerStopButton);

        fileIDEdit = (EditText)findViewById(R.id.editText);
        magText = (TextView) findViewById(R.id.textView3);

        stateText = (TextView) findViewById(R.id.textView);
        stateText.setText("Stand by");

        context = this;

        // Sensor
        sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        magnetic = sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);

        DecimalFormatSymbols symbols = new DecimalFormatSymbols(Locale.US);
        symbols.setDecimalSeparator('.');
        DECIMAL_FORMATTER = new DecimalFormat("#.000", symbols);

        //Location
        handler.postDelayed(runLocation, 1000);

    }
    public Runnable runLocation = new Runnable() {
        @Override
        public void run() {
            lat.setText(String.valueOf(latitude));
            lon.setText(String.valueOf(longitude));
            Toast.makeText(MainActivity.this, "location check", Toast.LENGTH_SHORT).show();

            MainActivity.this.handler.postDelayed(MainActivity.this.runLocation, 5000);
        }
    };

    private View.OnClickListener listenerStartButton = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            recording = true;
            stateText.setText("Recording started");
            stateText.setTextColor(Color.parseColor("#FF0000"));
        }
    };

   



    @Override
    public void onSensorChanged(SensorEvent event) {
        long timeInMillisec = (new Date()).getTime() + (event.timestamp - System.nanoTime()) / 1000000L;

        // Some sensor operations
            }
            //magneticData.add(new String[]{String.valueOf(timeInMillisec), String.valueOf(magValues[0]), String.valueOf(magValues[1]), String.valueOf(magValues[2])});
            @SuppressLint("SimpleDateFormat") SimpleDateFormat logLineStamp = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss:SSS", Locale.getDefault());
            //logLineStamp.setTimeZone(TimeZone.getTimeZone("UTC"));


            magneticData.add(new String[]{logLineStamp.format(new Date(timeInMillisec)), String.valueOf(x), String.valueOf(y), String.valueOf(z), String.valueOf(magnitude), String.valueOf(latitude),  String.valueOf(longitude)});
            counter++;
        }
    }
    // Checks if the the storage permissions are given or not by the user
    // It will request the use if not
    private static boolean storagePermitted(Activity activity){
        // Check read write permission
        


}
//Check Location

private void getLocation() {
    if (ActivityCompat.checkSelfPermission(this,
            Manifest.permission.ACCESS_FINE_LOCATION)
            != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(this, new String[]
                        {Manifest.permission.ACCESS_FINE_LOCATION},
                REQUEST_LOCATION_PERMISSION);
    } else {
        locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
        locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 0, this);
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, this);
        location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
        if (location != null){
            latitude = location.getLatitude();
            longitude = location.getLongitude();
        }
    }
}

    // Added Later

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {

    }

    @Override
    public void onLocationChanged(Location location) {
        latitude = location.getLatitude();
        longitude = location.getLongitude();

        lat.setText(String.valueOf(latitude));
        lon.setText(String.valueOf(longitude));
        Toast.makeText(MainActivity.this, "location changed: "+latitude+" "+longitude, Toast.LENGTH_LONG).show();


    }

    @Override
    public void onStatusChanged(String s, int i, Bundle bundle) {

    }

    @Override
    public void onProviderEnabled(String s) {

    }

    @Override
    public void onProviderDisabled(String s) {

    }
}

harry r
  • 786
  • 2
  • 6
  • 19
  • _"[...] the application just doesn't seem to work. I disappears after few seconds of installation."_ Have a look at the [crash log](https://stackoverflow.com/questions/23353173/unfortunately-myapp-has-stopped-how-can-i-solve-this). – Markus Kauppinen Jul 20 '20 at 12:19
  • @MarkusKauppinen [error logs](https://codeshare.io/GA9Oqr). Yes I checked, I think it has something to do with not getting permission. – harry r Jul 20 '20 at 12:25
  • Well, you are running your location related code with the condition `!= PackageManager.PERMISSION_GRANTED` which means that the required permission is not granted. – Markus Kauppinen Jul 20 '20 at 13:16
  • okay @MarkusKauppinen I have modified my code to make it more readable. Now my app is working fine but in csv file all the enteries of coordinates are 0 instead of latitude and longitude. – harry r Jul 20 '20 at 14:19
  • _"[...] in csv file all the enteries of coordinates are 0 instead of latitude and longitude."_ Have you checked are the values zero already when you get the location or only after writing to the CSV file? The problem could be in either place, I guess. Do you ever see the `Toast` you have in `onLocationChanged()`? – Markus Kauppinen Jul 21 '20 at 09:42

0 Answers0