【问题标题】:LatLng value is not being stored persistently in text file on deviceLatLng 值未永久存储在设备上的文本文件中
【发布时间】:2018-01-19 18:29:54
【问题描述】:

在我的应用程序中,用户有两个选项来放置标记:1) 通过onMapLongClick 方法,2) 通过使用语音命令。它们都可以正常工作,但我注意到一个错误,该错误仅在通过主页按钮关闭应用程序几个小时后才出现。

如果我等了几个小时再回到应用程序,标记仍然存在;但是,我两次分别等了大约 5-6 个小时,标记不见了。

我在这里做错了什么?这对我的用户来说非常糟糕,因为该应用程序旨在记住一个位置,即使在关闭应用程序数小时(或可能数天)之后也是如此。一次只有一个标记,而不是多个标记。

这里是存储或检索 LatLng 对象的位置:

onMapReady:

//Get Lat and Lng of marker and place on map if marker is there && if app has already been launched
            if (prefs.getBoolean("firstrun", false)) {
                try {
                    FileInputStream input = openFileInput("latlngpoints.txt");
                    DataInputStream din = new DataInputStream(input);
                    int sz = din.readInt();
                    for (int i = 0; i < sz; i++) {
                        String str = din.readUTF();
                        String[] stringArray = str.split(",");
                        double lat = Double.parseDouble(stringArray[0]);
                        double lon = Double.parseDouble(stringArray[1]);
                        LatLng newLatLng = new LatLng(lat, lon);
                        m = mMap.addMarker(new MarkerOptions()
                                .position(newLatLng)
                                .title("My Ride")
                                .icon(BitmapDescriptorFactory.fromResource(R.drawable.custom_marker30x48)));
                        markerDeleted = false;
                    }
                } catch (IOException e) {}

onActivityResult 用于语音识别按钮:

ArrayList<LatLng> markerLoc = new ArrayList<>();
                                markerLoc.add(new LatLng(latLng.latitude, latLng.longitude));

                                try {
                                    FileOutputStream output = openFileOutput("latlngpoints.txt", Context.MODE_PRIVATE);
                                    DataOutputStream dout = new DataOutputStream(output);
                                    dout.writeInt(markerLoc.size());
                                    for (LatLng point : markerLoc) {
                                        dout.writeUTF(point.latitude + "," + point.longitude);
                                    }
                                    dout.flush();
                                    dout.close();

                                } catch (IOException e) {
                                    //Log.d(TAG, "onActivityResult: " + e.getMessage());

                                }

onMapLongClick:

ArrayList<LatLng> markerLoc = new ArrayList<>();
                    markerLoc.add(new LatLng(latLng.latitude, latLng.longitude));
                    try {
                        FileOutputStream output = openFileOutput("latlngpoints.txt", Context.MODE_PRIVATE);
                        DataOutputStream dout = new DataOutputStream(output);
                        dout.writeInt(markerLoc.size());
                        for (LatLng point : markerLoc) {
                            dout.writeUTF(point.latitude + "," + point.longitude);
                            //Log.d(TAG, "onMapLongClick: " + String.valueOf(point.latitude) + "," +  String.valueOf(point.longitude));
                        }
                        dout.flush();
                        dout.close();

                    } catch (IOException e) {
                        //Log.d(TAG, "onMapLongClick: " + e.getMessage());
                    }

我是否也应该在我的 onPause 和 onResume 方法中做一些事情?除了停止指南针的传感器侦听器并检查是否启用了位置服务之外,它们几乎是空的。

    /*
    Stop sensor listeners
    Also check for no Network/GPS
     */
    @Override
    protected void onPause() {
        super.onPause();
        stopSensorListeners();
    }

    @Override
    protected void onResume() {
        super.onResume();
        startSensorListeners();

        if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) || !locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
            //AlertDialog to inform user GPS is off and take them to their Settings activity
            buildAlertMessageNoGps();
        }
    }

如果这是保持持久性存储的更好方法,我很乐意创建一个数据库。

【问题讨论】:

    标签: android google-maps google-maps-markers


    【解决方案1】:

    好的,我花了几天时间才让这个工作,但我会发布我想出的东西,以防其他人需要帮助。

    首先,在我的onMapReady() 中,我做了以下操作:

     SharedPreferences prefs = getPreferences(MODE_PRIVATE);
            if (prefs.contains("lat") || prefs.contains("lng")) {
                double lat = prefs.getFloat("lat", 0.0f);
                double lng = prefs.getFloat("lng", 0.0f);
                LatLng resumeLatLng = new LatLng(lat, lng);
                m = mMap.addMarker(new MarkerOptions()
                        .position(resumeLatLng)
                        .title("My Ride")
                        .icon(BitmapDescriptorFactory.fromResource(R.drawable.custom_marker30x48)));
                markerDeleted = false;
            }
    

    在我的onMapLongClick() 方法中,我做到了:

    SharedPreferences.Editor locationEditor = getPreferences(MODE_PRIVATE).edit();
    locationEditor.clear();
    locationEditor.putFloat("lat", (float) m.getPosition().latitude).apply();
    locationEditor.putFloat("lng", (float) m.getPosition().longitude).apply();
    

    我有一个清除标记的按钮,所以我们还要照顾那只小狗。所以:

    SharedPreferences.Editor editor = getPreferences(MODE_PRIVATE).edit();
    editor.remove("lat");
    editor.remove("lng");
    editor.apply();
    

    好的,一切都很好。那么,如果用户调用onPause() 方法呢?明白了:

    if (!markerDeleted) {
        SharedPreferences.Editor locationEditor = getPreferences(MODE_PRIVATE).edit();
        locationEditor.clear();
        locationEditor.putFloat("lat", (float) m.getPosition().latitude).apply();
        locationEditor.putFloat("lng", (float) m.getPosition().longitude).apply();
    }
    

    最后,在我的onResume() 方法中:

    if(!markerDeleted) {
        SharedPreferences prefs = getPreferences(MODE_PRIVATE);
        double lat = prefs.getFloat("lat", (float) m.getPosition().latitude);
        double lng = prefs.getFloat("lng", (float) m.getPosition().longitude);
        LatLng resumeLatLng = new LatLng(lat, lng);
        m = mMap.addMarker(new MarkerOptions()
                .position(resumeLatLng)
                .title("My Ride")
                .icon(BitmapDescriptorFactory.fromResource(R.drawable.custom_marker30x48)));
        markerDeleted = false;
    }
    

    现在,我可以添加一个标记,完全关闭应用程序,然后返回,我的标记仍然存在。

    如果我清除标记,退出应用程序,然后返回,它就不存在了。

    我使用共享首选项成功创建了标记持久性,并且没有使用数据库。 :-)

    【讨论】:

      猜你喜欢
      • 2015-03-22
      • 2021-08-22
      • 2015-07-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-15
      • 1970-01-01
      相关资源
      最近更新 更多