Android arraylist how to use

2019-07-20 14:04发布

So I have a list of markers that I need to figure out what to do with. I have searched for a few hours now, but nothing clearly states how to use the information or how to get the information from the list. Please explain or break down my code and inform me on how it exactly works. So I can set my markers on my map.

This is how I add my markers to my list. Now on onPostExecute I need to display them on my map. But I am unsure how to get them. There is about 50 markers that I send to my app from my server.

List<Marker> markers = new ArrayList<Marker>();
Marker marker = map.addMarker(new MarkerOptions()
            .position(location)
            .title(getName)
            .snippet(getDesc)
            .icon(BitmapDescriptorFactory
                      .fromResource(R.drawable.icon)));

            markers.add(marker);

EDIT: SOURCE CODE

private class PrefetchData extends AsyncTask<String, Void, String> 
   {

        @Override
        protected void onPreExecute() 
        {
            super.onPreExecute();    
        }

        protected void onPostExecute(Void result) 
        {
            for (int i = 0; i < markers.size(); i++) 
            {
                Marker currentMarker = markers.get(i);
                // do what you want with the current marker
            }
        }

        protected String doInBackground(String... params) 
        {
            JsonParser jsonParser = new JsonParser();
            String json = jsonParser.getJSONFromUrl("http://www.mywebsite.com/test.json");

            if (json != null) 
            {
                try 
                {
                    JSONObject parent = new JSONObject(json);
                    JSONArray eventDetails = parent.getJSONArray("maps");

                    for(int i=0; i < eventDetails.length(); i++)
                    {
                        object = eventDetails.getJSONObject(i);

                        String getName = object.getString("name");
                        String getAddy =object.getString("addy");
                        String getHours = object.getString("hours");
                        String getDesc = object.getString("desc");
                        String getLat = object.getString("lat");
                        String getLong = object.getString("long");

                        Log.e("JSON", "> " + getName + getAddy + getHours + getDesc + getLat + getLong );

                        double lat_ = Double.valueOf(getLat);
                        double lng_ = Double.valueOf(getLong);              

                        LatLng location = new LatLng(lat_, lng_);

                        Marker marker = map.addMarker(new MarkerOptions()
                                .position(location)
                                .title(getName)
                                .snippet(getDesc)
                                .icon(BitmapDescriptorFactory
                                       .fromResource(R.drawable.icon)));

                        markers.add(marker);

                        // creating connection detector class instance
                        cd = new Connection(getApplicationContext());
                    }
                }
                catch (JSONException e) 
                {
                    // TODO Auto-generated catch block
                    Log.e("Json Error", "Error: " + e.toString());
                        e.printStackTrace();
                }
             }

            return null;
         }
      }  

LOGCAT ERRORS:

01-26 01:27:43.082: E/AndroidRuntime(8209): FATAL EXCEPTION: main
01-26 01:27:43.082: E/AndroidRuntime(8209): Process: com.databasedemo, PID: 8209
01-26 01:27:43.082: E/AndroidRuntime(8209): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.databasedemo/com.databasedemo.Map}: java.lang.NullPointerException
01-26 01:27:43.082: E/AndroidRuntime(8209):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
01-26 01:27:43.082: E/AndroidRuntime(8209):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
01-26 01:27:43.082: E/AndroidRuntime(8209):     at android.app.ActivityThread.access$800(ActivityThread.java:135)
01-26 01:27:43.082: E/AndroidRuntime(8209):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
01-26 01:27:43.082: E/AndroidRuntime(8209):     at android.os.Handler.dispatchMessage(Handler.java:102)
01-26 01:27:43.082: E/AndroidRuntime(8209):     at android.os.Looper.loop(Looper.java:136)
01-26 01:27:43.082: E/AndroidRuntime(8209):     at android.app.ActivityThread.main(ActivityThread.java:5017)
01-26 01:27:43.082: E/AndroidRuntime(8209):     at java.lang.reflect.Method.invokeNative(Native Method)
01-26 01:27:43.082: E/AndroidRuntime(8209):     at java.lang.reflect.Method.invoke(Method.java:515)
01-26 01:27:43.082: E/AndroidRuntime(8209):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
01-26 01:27:43.082: E/AndroidRuntime(8209):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
01-26 01:27:43.082: E/AndroidRuntime(8209):     at dalvik.system.NativeStart.main(Native Method)
01-26 01:27:43.082: E/AndroidRuntime(8209): Caused by: java.lang.NullPointerException
01-26 01:27:43.082: E/AndroidRuntime(8209):     at com.databasedemo.Map.onCreate(Map.java:121)
01-26 01:27:43.082: E/AndroidRuntime(8209):     at android.app.Activity.performCreate(Activity.java:5231)
01-26 01:27:43.082: E/AndroidRuntime(8209):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
01-26 01:27:43.082: E/AndroidRuntime(8209):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
01-26 01:27:43.082: E/AndroidRuntime(8209):     ... 11 more

5条回答
爷、活的狠高调
2楼-- · 2019-07-20 14:53

Simply call .get(index).

To get the count, use .size()

Marker marker = markers.get(index);
查看更多
唯我独甜
3楼-- · 2019-07-20 14:54

Display showInfoWindow without clicking on marker android google map api v2

Declare markersList in outside of the class

List<Marker> markersList= new ArrayList<Marker>();

Adding marker to markersList

Marker marker=map.addMarker(new MarkerOptions().position(ll)
        .title(description).snippet("Jersey No :"+deviceID.split("-")[2])
        .icon(bitmapMarker));
markersList.add(marker);  // markersList --ArrayList declared outside class

Without selecting marker to showing marker infowindow
Here I used spinner to select the position

@Override
public boolean onNavigationItemSelected(int itemPosition, long itemId) {

    Marker currentMarker = markersList.get(itemPosition);
    LatLng latlng = currentMarker.getPosition();
    CameraUpdate update = CameraUpdateFactory.newLatLngZoom(latlng, 19F); 
    map.animateCamera(update);
    currentMarker.showInfoWindow();

}
查看更多
老娘就宠你
4楼-- · 2019-07-20 14:55

This code will iterate through the whole list.

for (int i = 0; i < markers.size(); i++) {
    Marker currentMarker = markers.get(i);
    // do what you want with the current marker
}

EDIT: This is some code from the developers website. It's an example of how to add a marker to a map.

Marker marker = map.addMarker(new MarkerOptions()
     .position(new LatLng(37.7750, 122.4183))
     .title("San Francisco")
     .snippet("Population: 776733"));

You are already doing this in your doInBackground method. So what is the problem exactly?

EDIT 2: Try using this code in place of yours, and see if it works.

private class PrefetchData extends AsyncTask<String, Void, String>  {

        private LatLng location;
        private String getName;
        private String getDesc;
        private List<Object[]> markerOptions;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();    
        }

        protected void onPostExecute(Void result) {
            for (int i = 0; i < markerOptions.size; i++) {
                Marker marker = map.addMarker(new MarkerOptions()
                                .position(markerOptions.get(i)[0])
                                .title(markerOptions.get(i)[1])
                                .snippet(markerOptions.get(i)[2])
                                .icon(BitmapDescriptorFactory
                                       .fromResource(R.drawable.icon)));

                        markers.add(marker);
            }
        }

        protected String doInBackground(String... params) {
        markerOptions = new ArrayList<Object[]>();
            JsonParser jsonParser = new JsonParser();
            String json = jsonParser.getJSONFromUrl("http://www.mywebsite.com/test.json");

            if (json != null) {
                try {
                    JSONObject parent = new JSONObject(json);
                    JSONArray eventDetails = parent.getJSONArray("maps");

                    for(int i=0; i < eventDetails.length(); i++) {
                        object = eventDetails.getJSONObject(i);

                        getName = object.getString("name");
                        String getAddy =object.getString("addy");
                        String getHours = object.getString("hours");
                        getDesc = object.getString("desc");
                        String getLat = object.getString("lat");
                        String getLong = object.getString("long");

                        Log.e("JSON", "> " + getName + getAddy + getHours + getDesc + getLat + getLong );

                        double lat_ = Double.valueOf(getLat);
                        double lng_ = Double.valueOf(getLong);              

                        location = new LatLng(lat_, lng_);

                        markerOptions.add(new Object[]{location, getName, getDesc});

                        // creating connection detector class instance
                        cd = new Connection(getApplicationContext());
                    }
                }
                catch (JSONException e) {
                    // TODO Auto-generated catch block
                    Log.e("Json Error", "Error: " + e.toString());
                        e.printStackTrace();
                }
             }

            return null;
         }
      }
查看更多
我只想做你的唯一
5楼-- · 2019-07-20 14:55
for (Marker marker : markers){
     LatLng latlng = marker.getPostion();
     String snippet = marker.getSnippet();
     String title = marker.getTitle()
}
查看更多
闹够了就滚
6楼-- · 2019-07-20 15:02
int size=markers.size();

for(int m=0 ; m < size; ++m)
 Marker obj= markers.get(index);

or you can use iterator

Iterator<Marker> iterator = markers.iterator();
        while (iterator.hasNext()) {
            Marker m=iterator.next();
        }
查看更多
登录 后发表回答