TypedArray is empty after obtainTypedArray call

2019-08-11 09:18发布

问题:

I have a simple google maps implementation, I'm filling two typed arrays with doubles from my strings.xml so I can use them to fill in as longitudes and latitudes.

Here is the method:

@Override
public void onMapReady(GoogleMap map) {

   map.setMyLocationEnabled(true);
   TypedArray lats = getResources().obtainTypedArray(R.array.Lats);
   TypedArray longs = getResources().obtainTypedArray(R.array.Longs);
   int length = longs.getIndexCount();
    Log.e("MY APP LOG", "here");
    Log.e("MY APP LOG", "length = " + length);
    for(int i = 0; i < length; i++)
    {
        LatLng coord = new LatLng(lats.getFloat(i,0),longs.getFloat(i,0));
        Log.e("MY APP LOG", "here2");
        Log.e("MY APP LOG", "latitude = " + lats.getFloat(i,0));

        map.addMarker(new MarkerOptions()
                .title("Sydney")
                .snippet("The most populous city in Australia.")
                .position(coord));
    }
    LatLng coord = new LatLng(lats.getFloat(0,0),longs.getFloat(0,0));

    map.moveCamera(CameraUpdateFactory.newLatLngZoom(coord, 13));


}

My strings.xml:

<array name="Lats">
    <item>-33.867</item>
    <item>-33.869</item>
    <item>-33.871</item>
    <item>-33.873</item>
    <item>-33.876</item>
    <item>-33.881</item>
    <item>-33.883</item>
    <item>-33.885</item>
    <item>-33.891</item>
</array>

<array name="Longs">
    <item>151.206</item>
    <item>151.209</item>
    <item>151.211</item>
    <item>151.205</item>
    <item>151.204</item>
    <item>151.207</item>
    <item>151.203</item>
    <item>151.201</item>
    <item>151.200</item>
</array>

The logcat shows:

04-30 05:00:00.727  24986-24986/com.example.andrew.ubair4 E/MY APP LOG﹕ here
04-30 05:00:00.727  24986-24986/com.example.andrew.ubair4 E/MY APP LOG﹕ length = 0

回答1:

Try to define lats and longs as String-Array in String resource :

<string-array name="lats">
    <item>-33.867</item>
    <item>-33.869</item>
    <item>-33.871</item>
    <item>-33.873</item>
    <item>-33.876</item>
    <item>-33.881</item>
    <item>-33.883</item>
    <item>-33.885</item>
    <item>-33.891</item>
</string-array>

<string-array name="longs">
    <item>151.206</item>
    <item>151.209</item>
    <item>151.211</item>
    <item>151.205</item>
    <item>151.204</item>
    <item>151.207</item>
    <item>151.203</item>
    <item>151.201</item>
    <item>151.200</item>
</string-array>

String[] lats = getResources().getStringArray(R.array.lats);
String[] longs = getResources().getStringArray(R.array.longs);

for(int i=0;i<longs.length;i++){
     LatLng coord = new LatLng(Double.parseDouble(lats[i]),Double.parseDouble(longs[i]));
     map.addMarker(new MarkerOptions()
        .title("Sydney")
        .snippet("The most populous city in Australia.")
        .position(coord));
}