получить одинаковую широту, долготу дважды, сравнить и сохранить в дБ - PullRequest
0 голосов
/ 27 апреля 2018

Я получаю значения широты и долготы от GPS, если я получаю одинаковые значения местоположения (широта и долгота) дважды, тогда мне нужно сравнить значения списков массивов, добавить эти значения в БД и удалить несколько значений из списков массивов. , В моем коде впервые значения добавляются в БД после того, как эта логика не работает. Может кто-нибудь, пожалуйста, помогите мне. Заранее спасибо

Мой код

MainActivity.java

public class MainActivity extends AppCompatActivity implements SensorEventListener {

private TextView latitudeVal, longitudeVal;
private Sensor accelerometer;
private SensorManager sm;
private LocationManager locationManager;
private LocationListener locationListener;
private DBHandler dbHandler;
private Location current;
private List longitudeList;
private List latitudeList;
private int countLongitude = 0;
private int countLatitude = 0;
private double longValue;
private double latValue;

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

    dbHandler = new DBHandler(this, null, null, 1);
    current = new Location("Dummy");

    longitudeList = new ArrayList<>();
    latitudeList = new ArrayList<>();

    latitudeVal = (TextView) findViewById(R.id.latValue);
    longitudeVal = (TextView) findViewById(R.id.longValue);

    sm = (SensorManager) getSystemService(SENSOR_SERVICE);
    accelerometer = sm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
    sm.registerListener(this, accelerometer, SensorManager.SENSOR_DELAY_UI); //registered sensor manager

    locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
    locationListener = new LocationListener() {
        @Override
        public void onLocationChanged(Location location) {

            latitudeVal.setText("= " + location.getLatitude());             // getting latitude value
            longitudeVal.setText("= " + location.getLongitude());           // getting longitude value
            current = location;

        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {

        }

        @Override
        public void onProviderEnabled(String provider) {

        }

        @Override
        public void onProviderDisabled(String provider) {

        }
    };
    //runtime permissions for gps
    if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            requestPermissions(new String[]{
                    android.Manifest.permission.INTERNET, android.Manifest.permission.ACCESS_COARSE_LOCATION, android.Manifest.permission.ACCESS_FINE_LOCATION
            }, 10);
        }
        return;
    } else {
        locationManager.requestLocationUpdates("gps", 5000, 0, locationListener);
    }


}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    try {
    switch (requestCode) {

            case 10:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
                    locationManager.requestLocationUpdates("gps", 5000, 0, locationListener);
    }
    }catch (SecurityException e){
        e.printStackTrace();
    }
}


@Override
public void onSensorChanged(SensorEvent event) {

    long actualTime = event.timestamp;

    try{
        if(actualTime - lastUpdate > 100000000) {
            lastUpdate = actualTime;
                //logic for adding if we get same 
                double longi = Math.round(current.getLongitude() * 1000.0) / 1000.0;   // rounding off the values
                double lati = Math.round(current.getLatitude() * 1000.0) / 1000.0;
                longitudeList.add(longi);
                latitudeList.add(lati);
                if(longitudeList.size() > 1 && latitudeList.size() > 1){
                    for (int i = 0; i < longitudeList.size(); i++) {
                        for (int j = i+1; j < longitudeList.size(); j++) {
                            // compare list.get(i) and list.get(j)
                            countLongitude++;
                        }
                    }

                    for (int i = 0; i < longitudeList.size(); i++) {
                        for (int j = i+1; j < longitudeList.size(); j++) {
                            // compare list.get(i) and list.get(j)
                            countLatitude++;
                        }
                    }

                    if(countLatitude == 2 && countLongitude == 2) {
                        //adding data to db
                        longValue = current.getLongitude();
                        latValue = current.getLatitude();
                        dbHandler.addLocation(current);
                        countLongitude = 0;
                        countLatitude = 0;
                        for(int i=0; i<longitudeList.size(); i++){
                            if(String.valueOf(longValue).equals(longitudeList.get(i)))
                                     longitudeList.remove(i);
                            }
                        }
                    }
                }
        }
        catch (Exception e){
            e.printStackTrace();
        }
}

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

  }
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:layout_marginLeft="10dp"
android:orientation="vertical"
tools:context="com.demo.gps">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="10dp"
    android:orientation="horizontal">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Latitude"
        android:textColor="@android:color/holo_green_light"
        android:textSize="20sp" />

    <TextView
        android:id="@+id/latValue"
        android:layout_width="wrap_content"
        android:text=""
        android:layout_height="wrap_content"
        android:textColor="@android:color/holo_green_light"
        android:layout_marginLeft="30dp"
        android:textSize="20sp" />
</LinearLayout>

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="10dp"
    android:orientation="horizontal">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="@android:color/holo_green_light"
        android:text="Longitude"
        android:textSize="20sp" />

    <TextView
        android:id="@+id/longValue"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="15dp"
        android:textColor="@android:color/holo_green_light"
        android:text=""
        android:textSize="20sp" />
 </LinearLayout>
</LinearLayout>

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
 package="com.demo.gps">

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

<application
    android:allowBackup="true"
    android:icon="@mipmap/app"
    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>
    </activity>
  </application>

 </manifest>

1 Ответ

0 голосов
/ 27 апреля 2018

В методе onSensorChanged () добавляйте значения широты и долготы в список, только если он не содержится в списке. Чтобы проверить наличие значений или нет, используйте метод list.contains ().

try{
     if(actualTime - lastUpdate > 100000000) {
         lastUpdate = actualTime;
             //logic for adding if we get same 
                double longi = Math.round(current.getLongitude() * 1000.0) / 1000.0;   // rounding off the values
                double lati = Math.round(current.getLatitude() * 1000.0) / 1000.0;
if((!longitudeList.contains(longi))&&(!latitudeList.contains(lati))){
                    longitudeList.add(longi);
                    latitudeList.add(lati);
//your db logic here

}

попробуйте этот код.

...