Android列表视图数组索引超出界限异常

时间:2013-12-10 07:55:11

标签: java android

我编写了一个函数来计算距离并反映在列表视图的textview中。现在这给出了Array Index Out Of Bounds Exception。这可能是什么错。因为其余代码用于提前提供结果,但在添加此功能后,此应用程序正在进行删除。

Route.java

 public class Route  extends Activity 
 {
ImageView exit, home, liveview, pinmap;
ArrayList<String> tolist;
ArrayList<String> distancelist;
List<String> greenl,bluel,redl,yellowl;
ListView list;
String Source,Destination;
Myadapter adapter;
MyDataBase mdb;
Integer[] dis=new Integer[97];
Integer[] disbetween=new Integer[97];
Boolean b=true;
Location mySourceLocation,myTargetLocation;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.routemap);
    list=(ListView) findViewById(R.id.listView1);
    tolist=new ArrayList<String>();
    distancelist=new ArrayList<String>();
    mdb=new MyDataBase(this);
    mdb.open();
    mySourceLocation=new Location("");
    myTargetLocation=new Location("");
    String[] stops = {
            "Bangalore International Exhibition Center", "Jindal", "Manjunathnagar", "Nagasandra", "Dasarahalli", "Jalahalli", "Peenya Industry", "Peenya", "Yeswanthpur Industry", "Yeswanthpur", "Sandal Soap Factory", "Mahalaxmi", "Rajajinagar", "Kuvempu Road", "Srirampura", "Sampige Road", "Kempegowda Interchange", "Chikpet", "K R Market", "National College", "Lalbagh", "South End Circle", "Jayanagar", "R V Road Interchange", "Banashankari", "J P Nagar", "Puttenahalli", "Anjanapura Cross Road", "Krishna Leela Park", "Vajrahalli", "Thaighattapura", "Anjanapura/NICE Junction", "Kengeri", "R V College of Engineering", "Bangalore University Cross", "Rajarajeshwari Nagar", "Nayandahalli", "Mysore Road", "Deepanjali Nagar", "Attiguppe", "Vijayanagar", "Hosahalli", "Magadi Road", "City Railway Station", "Sir M Vishweshwariah", "Vidhana Soudha", "Cubbon Park", "M G Road Interchange", "Trinity", "Halasuru", "Indiranagar", "S V Road", "Baiyyappanahalli", "Jyotipura", "K R Puram", "Mahadevpura", "Garudacharpalya", "Doddanekkundi Induatrial State", "Vishweshwariah Industrial State", "Kundanahalli", "Vydhehi Hospital", "Satya Sai Medical Institute", "ITPB", "Kadugodi   Industrial Area", "Ujjwal Vidhyalaya", "Whitefield", "Nagawara", "Arabic College", "Venkateshpura", "Tannery Town", "Pottery Town", "Cantonment Railway Station", "Shivajinagar", "Vellara Junction", "Langford Town", "Mico Bosch", "Dairy Circle", "Swagath Road Cross", "Jayadeva Hospital Interchange", "J P Nagar 4th Phase", "IIMB", "Hulimavu", "Gottigere", "Ragigudda Temple", "BTM Layout", "Silk Board", "HSR Layout", "Oxford College", "Muneshwara Nagar", "Chikkabegur", "Basapura Road", "Hosa Road", "Electronics City 1", "Electronics City 2", "Huskur Road", "Hebbagodi", "Bommasandra"
            };
    String[] operationalstops = {"M G Road Interchange","Trinity", "Halasuru", "Indiranagar", "S V Road", "Baiyyappanahalli"};

    String[] greenline = {"Bangalore International Exhibition Center", "Jindal", "Manjunathnagar", "Nagasandra", "Dasarahalli", "Jalahalli", "Peenya Industry", "Peenya", "Yeswanthpur Industry", "Yeswanthpur", "Sandal Soap Factory", "Mahalaxmi", "Rajajinagar", "Kuvempu Road", "Srirampura", "Sampige Road", "Kempegowda Interchange", "Chikpet", "K R Market", "National College", "Lalbagh", "South End Circle", "Jayanagar", "R V Road Interchange", "Banashankari", "J P Nagar", "Puttenahalli", "Anjanapura Cross Road", "Krishna Leela Park", "Vajrahalli", "Thaighattapura", "Anjanapura/NICE Junction"};

    String[] blueline = {"Kengeri", "R V College of Engineering", "Bangalore University Cross", "Rajarajeshwari Nagar", "Nayandahalli", "Mysore Road", "Deepanjali Nagar", "Attiguppe", "Vijayanagar", "Hosahall1i", "Magadi Road", "City Railway Station", "Kempegowda Interchange", "Sir M Vishweshwariah", "Vidhana Soudha", "Cubbon Park", "M G Road Interchange", "Trinity", "Halasuru", "Indiranagar", "S V Road", "Baiyyappanahalli", "Jyotipura", "K R Puram", "Mahadevpura", "Garudacharpalya", "Doddanekkundi Induatrial State", "Vishweshwariah Industrial State", "Kundanahalli", "Vydhehi Hospital", "Satya Sai Medical Institute", "ITPB", "Kadugodi Industrial Area", "Ujjwal Vidhyalaya", "Whitefield"};

    String[] redline = {"Nagawara", "Arabic College", "Venkateshpura", "Tannery Town", "Pottery Town", "Cantonment Railway Station", "Shivajinagar", "M G Road Interchange", "Vellara Junction", "Langford Town", "Mico Bosch", "Dairy Circle", "Swagath Road Cross", "Jayadeva Hospital Interchange", "J P Nagar 4th Phase", "IIMB", "Hulimavu", "Gottigere"};

    String[] yellowline = {"R V Road Interchange", "Ragigudda Temple", "Jayadeva Hospital Interchange", "BTM Layout", "Silk Board", "HSR Layout", "Oxford College", "Muneshwara Nagar", "Chikkabegur", "Basapura Road", "Hosa Road", "Electronics City 1", "Electronics City 2", "Huskur Road", "Hebbagodi", "Bommasandra"};

    greenl=Arrays.asList(greenline);
    bluel=Arrays.asList(blueline);
    redl=Arrays.asList(redline);
    yellowl=Arrays.asList(yellowline);

    adapter=new Myadapter();

}


**************************The function causing crash******************************

public void distanceBetweenStations() {
    for(int i=0;i<tolist.size();i++)
    {
    Cursor c1=mdb.getStops(tolist.get(i));
    while(c1.moveToNext())
    {   
        if(b)
        {   
            Double lati=c1.getDouble(2);
            Double longi=c1.getDouble(3);
            mySourceLocation.setLatitude(lati);
            mySourceLocation.setLongitude(longi);
            disbetween[i]=0;
            distancelist.add(disbetween[i].toString());
            dis[i]=0;
            b=false;
        }
        else
        {
        Double lati=c1.getDouble(2);
        Double longi=c1.getDouble(3);
        myTargetLocation.setLatitude(lati);
        myTargetLocation.setLongitude(longi);
        dis[i]=(int) mySourceLocation.distanceTo(myTargetLocation);
        disbetween[i]=dis[i]-dis[i-1];
        distancelist.add(disbetween[i].toString());
        Toast.makeText(getApplicationContext(),longi+"  "+lati+" "+disbetween[i], 1).show();    
        }
    }
    }
    adapter.notifyDataSetChanged();
}

 *************************The function causing crash*******************************

 class Myadapter extends BaseAdapter
  {

    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return tolist.size();
    }

    @Override
    public Object getItem(int pos) {
        // TODO Auto-generated method stub
        return tolist.get(pos);
    }

    @Override
    public long getItemId(int position) {
        // TODO Auto-generated method stub
        return position;
    }

RouteList.xml

<TextView
    android:id="@+id/textView3"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentRight="true"
    android:layout_alignParentTop="true"
    android:text="Medium Text"
    android:textAppearance="?android:attr/textAppearanceMedium" />

<TextView
    android:id="@+id/textView4"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentRight="true"
    android:layout_alignParentTop="true"
    android:layout_marginTop="22dp"
    android:text="Medium Text"
    android:textAppearance="?android:attr/textAppearanceMedium" />

<TextView
    android:id="@+id/textView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignBottom="@+id/textView4"
    android:layout_alignParentLeft="true"
    android:layout_alignParentTop="true"
    android:layout_toLeftOf="@+id/textView3"
    android:text="Large Text"
    android:gravity="center"
    android:textAppearance="?android:attr/textAppearanceLarge" />

 </RelativeLayout>

Routemap.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/backfront"
android:orientation="vertical" >

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginBottom="7dp"
    android:layout_marginLeft="7dp"
    android:layout_marginRight="7dp"
    android:layout_marginTop="7dp"
    android:background="@drawable/back"
    android:orientation="horizontal" >

    <TextView
        android:id="@+id/RouteText"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:textColor="#FFFFFF" />
</LinearLayout>

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_marginBottom="7dp"
    android:layout_marginLeft="7dp"
    android:layout_marginRight="7dp"
    android:layout_marginTop="7dp" >

    <ImageView
        android:id="@+id/exit"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentRight="true"
        android:layout_marginBottom="10dp"
        android:layout_marginTop="10dp"
        android:layout_marginRight="20dp"
        android:src="@drawable/exitapp" />

     <ImageView
        android:id="@+id/mapview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toLeftOf="@id/exit"
        android:layout_alignParentBottom="true"
        android:layout_marginBottom="10dp"
        android:layout_marginTop="10dp"
        android:layout_marginRight="20dp"
        android:src="@drawable/pinmap" />

      <ImageView
        android:id="@+id/showlive"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toLeftOf="@id/mapview"
        android:layout_alignParentBottom="true"
        android:layout_marginBottom="10dp"
        android:layout_marginTop="10dp"
        android:layout_marginRight="20dp"
        android:src="@drawable/pinmap" />

       <ImageView
        android:id="@+id/home"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toLeftOf="@id/showlive"
        android:layout_alignParentBottom="true"
        android:layout_marginBottom="10dp"
        android:layout_marginTop="10dp"
        android:layout_marginRight="20dp"
        android:src="@drawable/home" />

    <ListView
        android:id="@+id/listView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_above="@+id/exit"
        android:paddingBottom="30dp" >
    </ListView>
</RelativeLayout>

 </LinearLayout>

LogCat输出

enter image description here

12-10 12:49:31.577: E/AndroidRuntime(20793): FATAL EXCEPTION: main
12-10 12:49:31.577: E/AndroidRuntime(20793): java.lang.RuntimeException: Unable to   start activity   ComponentInfo{veniteck.solutions.mapmymetro/veniteck.solutions.mapmymetro.Route}:   java.lang.ArrayIndexOutOfBoundsException: length=97; index=-1
12-10 12:49:31.577: E/AndroidRuntime(20793):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2077)
12-10 12:49:31.577: E/AndroidRuntime(20793):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2104)
 12-10 12:49:31.577: E/AndroidRuntime(20793):   at android.app.ActivityThread.access$600(ActivityThread.java:134)
 12-10 12:49:31.577: E/AndroidRuntime(20793):   at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1247)
  12-10 12:49:31.577: E/AndroidRuntime(20793):  at android.os.Handler.dispatchMessage(Handler.java:99)
12-10 12:49:31.577: E/AndroidRuntime(20793):    at android.os.Looper.loop(Looper.java:154)
 12-10 12:49:31.577: E/AndroidRuntime(20793):   at android.app.ActivityThread.main(ActivityThread.java:4624)
 12-10 12:49:31.577: E/AndroidRuntime(20793):   at java.lang.reflect.Method.invokeNative(Native Method)
 12-10 12:49:31.577: E/AndroidRuntime(20793):   at java.lang.reflect.Method.invoke(Method.java:511)
 12-10 12:49:31.577: E/AndroidRuntime(20793):   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:809)
 12-10 12:49:31.577: E/AndroidRuntime(20793):   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:576)
 12-10 12:49:31.577: E/AndroidRuntime(20793):   at dalvik.system.NativeStart.main(Native Method)
 12-10 12:49:31.577: E/AndroidRuntime(20793): Caused by:  java.lang.ArrayIndexOutOfBoundsException: length=97; index=-1
 12-10 12:49:31.577: E/AndroidRuntime(20793):   at veniteck.solutions.mapmymetro.Route.distanceBetweenStations(Route.java:161)
 12-10 12:49:31.577: E/AndroidRuntime(20793):   at veniteck.solutions.mapmymetro.Route.sameline(Route.java:359)
 12-10 12:49:31.577: E/AndroidRuntime(20793):   at veniteck.solutions.mapmymetro.Route.onCreate(Route.java:90)
 12-10 12:49:31.577: E/AndroidRuntime(20793):   at android.app.Activity.performCreate(Activity.java:4479)
 12-10 12:49:31.577: E/AndroidRuntime(20793):   at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1050)
12-10 12:49:31.577: E/AndroidRuntime(20793):    at   android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2041)
 1 2-10 12:49:31.577: E/AndroidRuntime(20793):  ... 11 more
12-10 12:49:33.191: D/dalvikvm(20793): threadid=11: interp stack at 0x4d442000

2 个答案:

答案 0 :(得分:1)

从0开始变量i,并使用以下行:

disbetween[i]=dis[i]-dis[i-1];

所以你用-1

索引dis数组

答案 1 :(得分:0)

在您的distanceBetweenStations()方法中,您在else部分中有这一行:

disbetween[i]=dis[i]-dis[i-1];

将产生ArrayIndexOutOfBoundsException。为什么?

在您的方法中,您创建了光标:

Cursor c1=mdb.getStops(tolist.get(i));

并启动while()循环:

 while(c1.moveToNext()) {

如果光标中有多于一行,则在第一次迭代时,第一个条件得到满足(因为b为真),因此您的有问题的行将不会运行。但是你将b设置为false,所以在第二行,你的else部分被调用,并且记住我仍然是0,你有:

disbetween[0] = dis[0] - dis[-1]; <--------- can't access 

我不确定你要做什么,所以这些只是一些想法如何防止异常:

  • 添加条件:

    else {            
        //check for this condition, otherwise for i=0 you will have an exception 
        if (i>0) {
            Double lati=c1.getDouble(2);
            Double longi=c1.getDouble(3);
            myTargetLocation.setLatitude(lati);
            myTargetLocation.setLongitude(longi);
            dis[i]=(int) mySourceLocation.distanceTo(myTargetLocation);
            disbetween[i]=dis[i]-dis[i-1];
            distancelist.add(disbetween[i].toString());
            Toast.makeText(getApplicationContext(),longi+"  "+lati+" "+disbetween[i], 1).show();
        }
        else {
            //handle the situation if i < 0
        }
    }
    
  • 在其他地方将b设置为false,而不是第二个其他条件

  • 完全重组您的情况

如上所述,你是那个知道你想做什么的人,所以你现在应该可以解决问题。