两次获取相同的纬度,经度值,比较并保存到db

Posted

技术标签:

【中文标题】两次获取相同的纬度,经度值,比较并保存到db【英文标题】:get same latitude, longitude values twice, compare and save to db 【发布时间】:2018-10-08 00:24:55 【问题描述】:

我从 GPS 获取纬度和经度值,如果我两次获得相同的位置值(纬度和经度),那么我需要比较数组列表值,将这些值添加到 db 并从数组列表中删除多个值. 在我的代码中,在该逻辑不起作用后,第一次将值添加到 db 中。有人可以帮帮我吗。提前致谢

我的代码

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_
android:layout_
android:layout_marginLeft="10dp"
android:orientation="vertical"
tools:context="com.demo.gps">

<LinearLayout
    android:layout_
    android:layout_
    android:layout_marginTop="10dp"
    android:orientation="horizontal">

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

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

<LinearLayout
    android:layout_
    android:layout_
    android:layout_marginTop="10dp"
    android:orientation="horizontal">

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

    <TextView
        android:id="@+id/longValue"
        android:layout_
        android:layout_
        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】:

在 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


试试这个代码。

【讨论】:

使用 List 代替 List。

以上是关于两次获取相同的纬度,经度值,比较并保存到db的主要内容,如果未能解决你的问题,请参考以下文章

棒棒糖和棉花糖 gps 问题无法获取经度和纬度值,但在 21 以下的 api 上工作的代码相同

更快地获取经度和纬度值

复制相同值两次时,可写计算变量不读取值

使用标记从谷歌地图获取纬度/经度坐标

android纬度/经度格式

如何从java中的列表中获取最近的纬度经度[重复]