繁体   English   中英

Android保存一个Sharedpreferences数组

[英]Android Saving A Sharedpreferences Array

我目前正在尝试在onPause和onResume上存储具有共享首选项的Google地图标记。 我有一个声明为测试的默认值的数组。 当我加载并放置标记时,除了默认值0.0我似乎什么都没有得到。 我是否可能在某个地方弄乱了for循环? 还是我完全忽略了某些东西?

这是我的两种方法。

@Override
public void onPause(){


    super.onPause();

    SharedPreferences sharedPreferences = getSharedPreferences("MyData", Context.MODE_PRIVATE);

    SharedPreferences.Editor editor = sharedPreferences.edit();

    //public double listOfPoints[];

    int length = listOfPoints.length;

    for(int i = 0; i < length; i++){


    //Save each GPS value
    editor.putString(Integer.toString(i), Double.toString(listOfPoints[i]));

    //Save how many data points we had
    editor.putString("length", Integer.toString(length));

    editor.commit();
    }

    //Double.parseDouble() and Double.toString()
}





@Override
public void onResume(){

    super.onResume();
    //Load array of data back into the array
    SharedPreferences sharedPreferences = getSharedPreferences("MyData", Context.MODE_PRIVATE);

    //Get the number of GPS points (1GPS location is 2 points)
    int length = Integer.parseInt(sharedPreferences.getString("length", "0"));


    //Get all the GPS points into an array
    for(int i = 0; i < length; i++){

    listOfPoints [i] = Double.parseDouble(sharedPreferences.getString("i", "0.0"));

    }




    loadMarkers();
}

private void loadMarkers() {


    //Add markers onto the map
    for(int i = 0; i < listOfPoints.length; i = i + 2){
    googlemap.addMarker(new MarkerOptions().position(new LatLng(listOfPoints[i], listOfPoints[i+1])).title("Default"));

    }
    googlemap.addMarker(new MarkerOptions().position(new LatLng(0.0, 0.5)).title("hats"));
    googlemap.addMarker(new MarkerOptions().position(new LatLng(1.0, 0.5)).title("hats2"));
}

使用getString(Integer.toString(i), "0.0")代替getString("i", "0.0")因为1,2,3,..是键而不是i

listOfPoints [i] = Double.parseDouble(
                   sharedPreferences.getString(Integer.toString(i), "0.0"));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM