Google Maps android IndexOutOfBoundsException [英] Google Maps android IndexOutOfBoundsException

查看:87
本文介绍了Google Maps android IndexOutOfBoundsException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图让标记放置在地图上并飞往目的地。在forloop中,我有一个if语句,我希望它能这样做:

  for(i loop){
if(array(i)== null {spawn plane code}
else {move plane code}

这里是代码:

  package com.fly.plane; 

import java。 sql.Time;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List; $ b $ import java.util.Timer;
import java.util.TimerTask;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.fly.plane.R;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.Projection;
import com.google.android.gms.maps.SupportMapFragment;

import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatL NG;
导入com.google.android.gms.maps.model.Marker;
导入com.google.android.gms.maps.model.MarkerOptions;


导入android.R.array;
导入android.app.ListActivity;
导入android.app.ProgressDialog;
导入android.graphics.Point;
导入android.os.AsyncTask;
导入android.os.Bundle;
导入android.os.Handler;
导入android.os.Looper;
导入android.os.SystemClock;
导入android.support.v4.app.FragmentActivity;
导入android.text.format.DateFormat;
导入android.util.Log;
导入android.view.View;
导入android.view.animation.Interpolator;
导入android.view.animation.LinearInterpolator;
导入android.widget.TextView;

public class MyMapActivity extends ListActivity {

private ProgressDialog pDialog;

//获取数据的URL JSON
private static String url =http://edmundgentle.com/snippets/flights/api.php;

// JSON节点速度
private static final String TAG_data =data;
private static final String TAG_BEARING =bearing;
private static final String TAG_SPEED =speed;
private static final String TAG_ARR =arr;
private static final String TAG_ARR_TIME =time;
private static final String TAG_ARR_LAT =lat;
private static final String TAG_ARR_LON =lon;
private static final String TAG_DEP =dep;
private static final String TAG_DEP_TIME =time;
private static final String TAG_DEP_LAT =lat;
private static final String TAG_DEP_LON =lon;

//数据JSONArray
JSONArray data = null;

//用于ListView的Hashmap
ArrayList< HashMap< String,Double>>联系人列表;

// ListView的Hashmap
ArrayList< Double> CT;

列表<标记> markers = new ArrayList< Marker>();

//最终处理程序处理程序;
私有GoogleMap mMap;
public static final LatLng dest(Double alt,Double aln,int i){
// double double latitude = Double.parseDouble(alt);
// final double longitude = Double.parseDouble(aln);
返回新的LatLng(alt,aln);
}
public double latt = -15.48169437461;
public double lng = -15.48169437461;
public ArrayList< Integer> DLAT;

public String [] markerList;

public String dlat;
public String dlon;
public String alat;
public String alon;

private int count;

public boolean wait = true;

//私人按钮startB;
公共TextView文本;

定时器计时;
double time = 600;
double timm = 1;

long timer = 18000000;
long newTime;
TextView电视,测试;
线程t;
@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_map);

contactList = new ArrayList< HashMap< String,Double>>();

ct = new ArrayList< Double>();

// ListView lv = getListView();

//创建标记
new Getdata()。execute();
//计时器在快速时间显示时间
t = new Thread(){

@Override
public void run(){
try {
while(!isInterrupted()){
Thread.sleep(600);
runOnUiThread(new Runnable(){
@Override
public void run(){
timer = timer +60000;
if(timer> = 64000000)timer = 18000000;
newTime = timer;
//在此处更新TextView!
// String time =HH:mm:ss;
//tv.setText(DateFormat。格式(time,timer));
tv.setText(Double.toString(time));
test.setText(Double.toString(timm));
//tv.setText( ();
// Timer();
}
});
}
} catch(InterruptedException e){
}
}
};

tv = new TextView(this);
test = new TextView(this);
tv =(TextView)findViewById(R.id.timer);
test =(TextView)findViewById(R.id.test);
//从现在开始,在10秒内运行mUpdateUITimerTask的run()方法
}


//赋予每个飞机动画
public void animateMarker(final Marker marker,final LatLng toPosition,
final boolean hideMarker,final double spd){

float speed =(float)spd; // Float.parseFloat(spd);
final Handler handler = new Handler();
final long start = SystemClock.uptimeMillis();
Projection proj = mMap.getProjection();
Point startPoint = proj.toScreenLocation(marker.getPosition());
final LatLng startLatLng = proj.fromScreenLocation(startPoint);
最终浮动时间= 10 *速度;
final Interpolator interpolator = new LinearInterpolator();
handler.post(new Runnable(){
@Override
public void run(){
long elapsed = SystemClock.uptimeMillis() - start;
float t = interpolator.getInterpolation((float)((float)elapsed
/ duration));
double lng = t * toPosition.longitude +(1 - t)
* startLatLng.longitude;
double lat = t * toPosition.latitude +(1 - t)
* startLatLng.latitude;
marker.setPosition(new LatLng(lat,lng));
if(t < 1.0){
// 16ms后再次发布
handler.postDelayed(this,16);
} else {
handler.postDelayed(this,16);
if(hideMarker){
marker.setVisible(false);
} else {
marker.setVisible(真);
}
}
}
});


public void Timer(){
// TimerTask tasknew = new TimerTask();
timing = new Timer();
timing.schedule(new CreateMarker(),1000,1000);


$ b public String calcCurPos(double curlat,double curlon,double deslat,double deslon,double avgSpd,double bearing){

double distance = avgSpd * 0.0167;

//检查度数或弧度
// deslat = distance * Math.cosh(bearing);

// double retLat = curlat + deslat;
// double dPhi = Math.log(Math.tan(retLat / 2 + Math.PI / 4)/Math.tan(curlat / 2 + Math.PI / 4));
// double q = deslat / dPhi deslat / dPhi:Math.cos(curlat);
轴承=轴承* Math.PI / 180;

int radius = 6371;

double nextLat = Math.asin(Math.sin(curlat)* Math.cos(距离/半径)
+ Math.cos(curlat)* Math.sin(距离/半径) * Math.cos(轴承));

double nextLon = curlon + Math.atan2(Math.sin(bearing)* Math.sin(distance / radius)
* Math.cos(curlat),Math.cos(distance /半径)-Math.sin(curlat)* Math.sin(nextLat));

nextLat =(nextLat * 180)/ Math.PI;
nextLon =(nextLon * 180)/ Math.PI;


/ **
*警告可能希望在返回之前将它们转换为字符串。
* /
return nextLat +; + nextLon;
}

public class CreateMarker extends TimerTask {

@Override
public void run(){
// TODO自动生成的方法存根

//打印测试
//tv.setText(Double.toString(time));
//tv.setText(Double.toString(time));
if(time> = 2400){
time = 0;
}

时间+ = 1;
// mMap =((MapFragment)getFragmentManager()。findFragmentById(R.id.map))。getMap();

for(int i = 0; i <100; i ++){
//从数组列表中获取数据
final double depLat = contactList.get(i).get ( DLAT);
final double depLon = contactList.get(i).get(dlon);
final double arLat = contactList.get(i).get(alat);
final double arLon = contactList.get(i).get(alon);
final double spd = contactList.get(i).get(speed);
final double dTime = contactList.get(i).get(time);
double curLat = contactList.get(i).get(clat);
double curLon = contactList.get(i).get(clon);
final double bearing = contactList.get(i).get(bearing);

final int j = i;
// int dTime = Integer.parseInt(dtime);

double oldLat = curLat;
$ b $ if(time> = dTime)
{
if(curLat< arLat || curLat> 0){

字符串latlng = calcCurPos(curLat,curLon,arLat,arLon,spd,方向);

String [] values = latlng.split(;);

curLat = Double.parseDouble(values [0]);
curLon = Double.parseDouble(values [1]);
final double crLat = curLat;
final double crLon = curLon;

final LatLng position = new LatLng(crLat,crLon);

$ b $ * Marker mo = mMap.addMarker(new MarkerOptions()
.position(new LatLng(depLat,depLon))
.icon(BitmapDescriptorFactory.fromResource (R.drawable.planemarker))); * /
// DrawMarker();

//animateMarker (markers.get(i),position,true,spd);
try {
if(markers.get(i)== null){
// timm + = 1;
timm + = 1;
runOnUiThread(new Runnable(){
@Override
public void run(){

final Marker marker = mMap.addMarker(new MarkerOptions()
.position(new LatLng(depLat,depLon))
.title(Hello world)
.icon(BitmapDescriptorFactory.fromResource(R.drawable.planemarker)));
标记。 add(marker);
//marker.setVisible(false);
//animateMarker(markers.get(j),new LatLng(arLat,arLon),true,spd);
// Marker marker = markers.get(i);

//marker.setPosition(position);
}
});

}
else // (markers.get(i)!= null){
{
Marker marker = markers.get(i);
marker.setPosition(position);
marker.setVisible(false);
//animateMarker (markers.get(i),position,true,spd);


catch(NullPointerException npe)
{
//做别的事
}

}
}
}


//返回null;




$ **
*通过进行HTTP调用获取json的异步任务类
* * /
private class Getdata extends AsyncTask< Void,Void,Void> {

@Override
保护无效onPreExecute(){
super.onPreExecute();
//显示进度对话框
pDialog = new ProgressDialog(MyMapActivity.this);
pDialog.setMessage(Please wait ...);
pDialog.setCancelable(false);
pDialog.show();


$ b $覆盖
保护无效doInBackground(Void ... arg0){
//创建服务处理器类实例
HTTPHandler sh = new HTTPHandler();

//向url发出请求并获取响应
String jsonStr = sh.makeServiceCall(url,HTTPHandler.GET);

Log.d(Response:,>+ jsonStr);
布尔值limit = false;
if(jsonStr!= null || limit == false){
try {
JSONObject jsonObj = new JSONObject(jsonStr);

//获取JSON数组节点
data = jsonObj.getJSONArray(TAG_data);

//遍历所有数据
for(int i = 0; i< data.length(); i ++){
JSONObject c = data.getJSONObject(i) ;

字符串轴承= c.getString(TAG_BEARING);
String spd = c.getString(TAG_SPEED);
//出发节点是JSON对象
JSONObject dep = c.getJSONObject(TAG_DEP);
String dtime = dep.getString(TAG_DEP_TIME);
// String dlat = dep.getString(TAG_DEP_LAT);
// String dlon = dep.getString(TAG_DEP_LON);
dlat = dep.getString(TAG_DEP_LAT);
dlon = dep.getString(TAG_DEP_LON);


//替换:从出发时间起最后2个0
dtime = dtime.replaceAll(:,);
//dtime.replaceAll(;,);
dtime = dtime.substring(0,dtime.length() - 2);

//到达节​​点是JSON对象
JSONObject arr = c.getJSONObject(TAG_ARR);

String alt = arr.getString(TAG_ARR_LAT);
String aln = arr.getString(TAG_ARR_LON);


//将数据位置转换为Google地图+双倍数据

double brng = Double.parseDouble(bearing);
brng = brng * Math.PI / 180;

double speed = Double.parseDouble(spd);
// double brng = Double.parseDouble(bearing);
double dLatitude = Double.parseDouble(dlat);
double dLongitude = Double.parseDouble(dlon);
double aLatitude = Double.parseDouble(alt);
double aLongitude = Double.parseDouble(aln);
double cLatitude = Double.parseDouble(dlat);
double cLongitude = Double.parseDouble(dlon);
double dtme = Double.parseDouble(dtime);

//单个联系人的tmp hashmap
HashMap< String,Double> contact = new HashMap< String,Double>();

contact.put(bearing,brng);
contact.put(速度,速度);
contact.put(time,dtme);
contact.put(alat,aLatitude);
contact.put(alon,aLongitude);
contact.put(dlat,dLatitude);
contact.put(dlon,dLongitude);
contact.put(clat,cLatitude);
contact.put(clon,cLongitude);

//将联系人添加到联系人列表
contactList.add(contact);

if(i == data.length()){
wait = false;

$ b $ catch(JSONException e){
e.printStackTrace();

} else {
Log.e(ServiceHandler,无法从网址获取任何数据);
}

返回null;
}
//在json加载时产生飞机
@Override
protected void onPostExecute(void result){
Timer();
t.start();
super.onPostExecute(result);
//关闭进度对话框
if(pDialog.isShowing())
pDialog.dismiss();
//使用plane api作为latlon
mMap =((MapFragment)getFragmentManager()。findFragmentById(R.id.map))。getMap();

// for(int i = 0; i< contactList.size(); i ++)
}}


}

这里是错误信息:

  02-26 21:53:42.031:E / AndroidRuntime(14970):致命例外:Timer-0 
02-26 21:53:42.031:E / AndroidRuntime(14970):java .lang.IndexOutOfBoundsException:无效索引0,大小为0
02-26 21:53:42.031:E / AndroidRuntime(14970):在java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255)
02-26 21:53:42.031:E / AndroidRuntime(14970):在java.util.ArrayList.get(ArrayList.java:308)
02-26 21:53:42.031:E / AndroidRuntime(14970) ):at com.fly.plane.MyMapActivity $ CreateMarker.run(MyMapActivity.java:395)
02-26 21:53:42.031:E / AndroidRuntime(14970):位于java.util.Timer $ TimerImpl。运行(Timer.java:284)

据我了解,markers.get(i)问题,但我不知道如何检查标记数组是否为空它抛出这个错误。

任何帮助将不胜感激。

解决方案

您可以使用 Map< Integer ,Marker> Integer 是键, Marker 是值)。然后,您可以利用 Map.get(),如果键为整数而不是 null (你的代码中你的 i 不会是 null )。 / p>

将标记声明为Map:

  Map< Integer,Marker> markers = new HashMap< Integer,Marker>(); 

里面 CreateMarker.run() code> final LatLng position = new LatLng(crLat,crLon); 更改如下:

  //隐式装箱在Map $ b中使用int整数ii = Integer.valueOf(i); 

//尝试通过map中的索引获得标记(索引是关键字)
Marker markerByIndex = markers.get(ii);

//如果指定键的对象不在映射中,则返回null
if(markerByIndex == null){
//标记不存在 - 创建它,添加到谷歌地图和按键
timm + = 1;
runOnUiThread(new Runnable(){
@Override
public void run(){
final Marker marker = mMap.addMarker(new MarkerOptions()
.position( new LatLng(depLat,depLon))
.title(Hello world)
.icon(BitmapDescriptorFactory.fromResource(R.drawable.planemarker)));

//使用i作为键
markers.put(ii,marker);
}
});
} else {
// marker存在,改变它
markerByIndex.setPosition(position);
markerByIndex.setVisible(false);

//...将地图中的标记替换
markers.put(ii,markerByIndex);

//赋予标记
的动画效果animateMarker(markerByIndex,position,true,spd);
}


I am trying to get markers placed on the map and fly to their destination. within a forloop i have an if statement, i wish it to do this:

for(i loop){
If (array(i) == null{ spawn plane code}
else {move plane code}

here is the code:

 package com.fly.plane;

import java.sql.Time;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.fly.plane.R;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.Projection;
import com.google.android.gms.maps.SupportMapFragment;

import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;


import android.R.array;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.graphics.Point;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.SystemClock;
import android.support.v4.app.FragmentActivity;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.View;
import android.view.animation.Interpolator;
import android.view.animation.LinearInterpolator;
import android.widget.TextView;

public class MyMapActivity extends ListActivity {

    private ProgressDialog pDialog;

    // URL to get data JSON
    private static String url = "http://edmundgentle.com/snippets/flights/api.php";

    // JSON Node speeds
    private static final String TAG_data = "data";
    private static final String TAG_BEARING = "bearing";
    private static final String TAG_SPEED = "speed";
    private static final String TAG_ARR = "arr";
    private static final String TAG_ARR_TIME = "time";
    private static final String TAG_ARR_LAT = "lat";
    private static final String TAG_ARR_LON = "lon";
    private static final String TAG_DEP = "dep";
    private static final String TAG_DEP_TIME = "time";
    private static final String TAG_DEP_LAT = "lat";
    private static final String TAG_DEP_LON = "lon";

    // data JSONArray
    JSONArray data = null;

    // Hashmap for ListView
    ArrayList<HashMap<String, Double>> contactList;

    // Hashmap for ListView
    ArrayList<Double> ct;

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

    //final Handler handler;
    private GoogleMap mMap; 
    public static final LatLng dest(Double alt,Double aln, int i){
        //final double latitude = Double.parseDouble(alt);
        //final double longitude = Double.parseDouble(aln);
        return new LatLng(alt, aln);
    }
    public double latt = -15.48169437461;
    public double lng = -15.48169437461;
    public ArrayList<Integer> dLat;

    public String[] markerList;

    public String dlat;
    public String dlon;
    public String alat;
    public String alon;

    private int count;

    public boolean wait = true;

    //private Button startB;
    public TextView text;

    Timer timing;
    double time = 600;
    double timm = 1;

    long timer = 18000000;
    long newTime;
    TextView tv, test;
    Thread t;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_map);

        contactList = new ArrayList<HashMap<String, Double>>();

        ct = new ArrayList<Double>();

        //ListView lv = getListView();

      //create markers  
        new Getdata().execute();
        // timer showing time of day in fast time
        t = new Thread() {

              @Override
              public void run() {
                try {
                  while (!isInterrupted()) {
                    Thread.sleep(600);
                    runOnUiThread(new Runnable() {
                      @Override
                      public void run() {
                          timer = timer +60000;
                          if (timer >= 64000000) timer = 18000000;
                          newTime = timer;
                        // update TextView here!
                         //String time = "HH:mm:ss";
                         //tv.setText(DateFormat.format(time , timer));
                         tv.setText(Double.toString(time));
                         test.setText(Double.toString(timm));
                         //tv.setText(Double.toString(contactList.get(20).get("time")));
                         //Timer();
                      }
                    });
                  }
                } catch (InterruptedException e) {
                }
              }
            };

            tv = new TextView(this); 
            test = new TextView(this); 
            tv=(TextView)findViewById(R.id.timer); 
            test=(TextView)findViewById(R.id.test); 
         // run the mUpdateUITimerTask's run() method in 10 seconds from now
    }    


    // animate each plane
    public void animateMarker(final Marker marker , final LatLng toPosition,
            final boolean hideMarker, final double spd) {

        float speed = (float) spd;// Float.parseFloat(spd);
        final Handler handler = new Handler();
        final long start = SystemClock.uptimeMillis();
        Projection proj = mMap.getProjection();
        Point startPoint = proj.toScreenLocation(marker.getPosition());
        final LatLng startLatLng = proj.fromScreenLocation(startPoint);
        final float duration = 10 * speed;
        final Interpolator interpolator = new LinearInterpolator();
        handler.post(new Runnable() {
            @Override
            public void run() {
                long elapsed = SystemClock.uptimeMillis() - start;
                float t = interpolator.getInterpolation((float) ((float) elapsed
                        / duration));
                double lng = t * toPosition.longitude + (1 - t)
                        * startLatLng.longitude;
                double lat = t * toPosition.latitude + (1 - t)
                        * startLatLng.latitude;
                marker.setPosition(new LatLng(lat, lng));
                if (t < 1.0) {
                    // Post again 16ms later.
                    handler.postDelayed(this, 16);
                } else {
                    handler.postDelayed(this, 16);
                    if (hideMarker) {
                        marker.setVisible(false);
                    } else {
                        marker.setVisible(true);
                    }
                }
            }
        });
    }

    public void Timer(){
        //TimerTask tasknew = new TimerTask();
        timing = new Timer();
        timing.schedule(new CreateMarker(), 1000, 1000);
    }


    public String calcCurPos(double curlat, double curlon, double deslat, double deslon, double avgSpd, double bearing){

        double distance = avgSpd * 0.0167;

        // check if degrees or radians
        //deslat = distance * Math.cosh(bearing);

        //double retLat = curlat + deslat;
        //double dPhi = Math.log(Math.tan(retLat/2+Math.PI/4)/Math.tan(curlat/2+Math.PI/4));
        //double q = deslat/dPhi  deslat/dPhi : Math.cos(curlat);
        bearing = bearing * Math.PI / 180;

        int radius = 6371;

        double nextLat = Math.asin(Math.sin(curlat)* Math.cos(distance/radius)
                + Math.cos(curlat)*Math.sin(distance/radius)*Math.cos(bearing));

        double nextLon = curlon + Math.atan2(Math.sin(bearing)* Math.sin(distance/ radius)
                * Math.cos(curlat), Math.cos(distance/radius)-Math.sin(curlat) * Math.sin(nextLat));

        nextLat = (nextLat * 180) / Math.PI;
        nextLon = (nextLon * 180) / Math.PI;


        /**
         * Warning might want to convert them to string prior to return.
         */
        return nextLat + ";" + nextLon;
    }

public class CreateMarker extends TimerTask{

    @Override
    public void run() {
        // TODO Auto-generated method stub

        // print test
        //tv.setText(Double.toString(time));
        //tv.setText(Double.toString(time));
        if (time >= 2400){
            time=0;
        }

        time += 1;
        //mMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();

        for (int i =0; i < 100;i++){
            // get data from array list
            final double depLat = contactList.get(i).get("dlat");
            final double depLon =  contactList.get(i).get("dlon");
            final double arLat = contactList.get(i).get("alat");
            final double arLon =  contactList.get(i).get("alon");
            final double spd = contactList.get(i).get("speed");
            final double dTime = contactList.get(i).get("time");
            double curLat = contactList.get(i).get("clat");
            double curLon = contactList.get(i).get("clon");
            final double bearing = contactList.get(i).get("bearing");

            final int j = i;
            //int dTime = Integer.parseInt(dtime);

            double oldLat = curLat;

            if (time >= dTime)
            {
                if (curLat < arLat || curLat > 0){

                    String latlng = calcCurPos(curLat, curLon, arLat, arLon ,spd, bearing );

                    String[] values = latlng.split(";");

                    curLat = Double.parseDouble(values[0]);
                    curLon = Double.parseDouble(values[1]);
                    final double crLat = curLat;
                    final double crLon = curLon;

                    final LatLng position = new LatLng(crLat,crLon);


                    /*Marker mo =  mMap.addMarker(new MarkerOptions()
                    .position(new LatLng(depLat, depLon))
                    .icon(BitmapDescriptorFactory.fromResource(R.drawable.planemarker)));*/
                        //DrawMarker();

                    //animateMarker(markers.get(i), position , true, spd);
                    try{
                    if (markers.get(i) == null){
                        //timm += 1;
                        timm += 1;
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {

                        final Marker marker =  mMap.addMarker(new MarkerOptions()
                        .position(new LatLng(depLat, depLon))
                        .title("Hello world")
                        .icon(BitmapDescriptorFactory.fromResource(R.drawable.planemarker)));
                        markers.add(marker);
                        //marker.setVisible(false);
                        //animateMarker(markers.get(j), new LatLng(arLat,arLon) , true, spd);
                        //Marker marker = markers.get(i);

                        //marker.setPosition(position);
                          }
                        });

                    }
                    else //(markers.get(i) != null){
                    {
                        Marker marker = markers.get(i);
                        marker.setPosition(position);
                        marker.setVisible(false);
                        //animateMarker(markers.get(i), position , true, spd);
                    }
                    }
                    catch(NullPointerException npe)
                    {
                        //do something else
                    }

                }
            }
        }


        //return null;

    }
    }


    /**
     * Async task class to get json by making HTTP call
     * */
    private class Getdata extends AsyncTask<Void, Void, Void> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            // Showing progress dialog
            pDialog = new ProgressDialog(MyMapActivity.this);
            pDialog.setMessage("Please wait...");
            pDialog.setCancelable(false);
            pDialog.show();

        }

        @Override
        protected Void doInBackground(Void... arg0) {
            // Creating service handler class instance
            HTTPHandler sh = new HTTPHandler();

            // Making a request to url and getting response
            String jsonStr = sh.makeServiceCall(url, HTTPHandler.GET);

            Log.d("Response: ", "> " + jsonStr);
            boolean limit = false;
            if (jsonStr != null  ||  limit == false) {
                try {
                    JSONObject jsonObj = new JSONObject(jsonStr);

                    // Getting JSON Array node
                    data = jsonObj.getJSONArray(TAG_data);

                    // looping through All data
                    for (int i = 0; i < data.length(); i++) {
                        JSONObject c = data.getJSONObject(i);

                        String bearing = c.getString(TAG_BEARING);
                        String spd = c.getString(TAG_SPEED);
                        // departure node is JSON Object
                        JSONObject dep = c.getJSONObject(TAG_DEP);
                        String dtime = dep.getString(TAG_DEP_TIME);
                        //String dlat = dep.getString(TAG_DEP_LAT);
                        //String dlon = dep.getString(TAG_DEP_LON);
                        dlat = dep.getString(TAG_DEP_LAT);
                        dlon = dep.getString(TAG_DEP_LON);


                        // replace : and last 2 0's from departure time
                        dtime = dtime.replaceAll(":","");
                        //dtime.replaceAll(";","");
                        dtime = dtime.substring(0,dtime.length()-2);

                        // arrival node is JSON Object
                        JSONObject arr = c.getJSONObject(TAG_ARR);

                        String alt = arr.getString(TAG_ARR_LAT);
                        String aln = arr.getString(TAG_ARR_LON);


                        // convert data positions to doubles for Google Maps + stuff

                        double brng = Double.parseDouble(bearing);
                        brng = brng * Math.PI / 180;

                        double speed = Double.parseDouble(spd);
                        //double brng = Double.parseDouble(bearing);
                        double dLatitude = Double.parseDouble(dlat);
                        double dLongitude = Double.parseDouble(dlon);
                        double aLatitude = Double.parseDouble(alt);
                        double aLongitude = Double.parseDouble(aln);
                        double cLatitude = Double.parseDouble(dlat);
                        double cLongitude = Double.parseDouble(dlon);
                        double dtme = Double.parseDouble(dtime);

                        // tmp hashmap for single contact
                        HashMap<String, Double> contact = new HashMap<String, Double>();

                        contact.put("bearing", brng);
                        contact.put("speed", speed);
                        contact.put("time", dtme);
                        contact.put("alat", aLatitude);
                        contact.put("alon", aLongitude);
                        contact.put("dlat", dLatitude);
                        contact.put("dlon", dLongitude);    
                        contact.put("clat", cLatitude);
                        contact.put("clon", cLongitude);

                        // adding contact to contact list
                        contactList.add(contact);

                        if (i== data.length()){
                            wait = false;
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } else {
                Log.e("ServiceHandler", "Couldn't get any data from the url");
            }

            return null;
        }
        // spawns planes when json loaded
        @Override
        protected void onPostExecute(Void result) {
            Timer();
            t.start();
            super.onPostExecute(result);
            // Dismiss the progress dialog
            if (pDialog.isShowing())
                pDialog.dismiss();            
            // use plane api for latlon
            mMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();

            //for (int i = 0; i < contactList.size() ; i++)
        }}


}

and here is the error message:

02-26 21:53:42.031: E/AndroidRuntime(14970): FATAL EXCEPTION: Timer-0
02-26 21:53:42.031: E/AndroidRuntime(14970): java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
02-26 21:53:42.031: E/AndroidRuntime(14970):    at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255)
02-26 21:53:42.031: E/AndroidRuntime(14970):    at java.util.ArrayList.get(ArrayList.java:308)
02-26 21:53:42.031: E/AndroidRuntime(14970):    at com.fly.plane.MyMapActivity$CreateMarker.run(MyMapActivity.java:395)
02-26 21:53:42.031: E/AndroidRuntime(14970):    at java.util.Timer$TimerImpl.run(Timer.java:284)

i understand that the markers.get(i) is causing the problem, but i dont know how to check if the markers array is null without it throwing this error.

Any help would be appreciated.

解决方案

You can use Map<Integer, Marker> (Integer are keys and Marker are values). Then you can leverage Map.get() which don't throws Exception if key is Integer and not null (your i will not be null in your code).

Declare markers as Map:

Map<Integer, Marker> markers = new HashMap<Integer, Marker>();

Inside CreateMarker.run() after final LatLng position = new LatLng(crLat,crLon); change as follows:

//implicit boxing to use int in Map
Integer ii = Integer.valueOf(i);

//try to get marker by index from map (index is the key)
Marker markerByIndex = markers.get(ii);

//Map.get() returns null if object by specified key is not in map
if (markerByIndex == null){
    //marker doesn't exists - create it, add to Google Map and to Map by key
    timm += 1;
    runOnUiThread(new Runnable() {
        @Override
        public void run() {
            final Marker marker =  mMap.addMarker(new MarkerOptions()
                                   .position(new LatLng(depLat, depLon))
                                   .title("Hello world")
                                   .icon(BitmapDescriptorFactory.fromResource(R.drawable.planemarker)));

            //put marker to map using i as a key
            markers.put(ii, marker);
        }
    });
} else {
    //marker exists, mutate it
    markerByIndex.setPosition(position);
    markerByIndex.setVisible(false);

    //...replace the marker in map
    markers.put(ii, markerByIndex);

    //animate the marker
    animateMarker(markerByIndex, position , true, spd);
}

这篇关于Google Maps android IndexOutOfBoundsException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆