0

I have written a function to calculate distance and reflect in a textview in list view. Now this is giving Array Index Out Of Bounds Exception. What might be the fault here.? Because the rest of the code used to give results earlier, but after adding this function, this app is crasing.

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 Output

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
7
  • Please post the stacktrace and post SSCCE. Commented Dec 10, 2013 at 7:57
  • Can you check number of items in tolist Commented Dec 10, 2013 at 7:59
  • Please se updated ques, the logcat is there.. Commented Dec 10, 2013 at 7:59
  • before the creation of tolist, the app is getting crashed. Commented Dec 10, 2013 at 8:01
  • Can you paste the stacktrace instead of picture and complete code RouteList.xml? Commented Dec 10, 2013 at 8:22

2 Answers 2

1

You start the variable i from 0, and use this line:

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

So you index the dis array with -1

Sign up to request clarification or add additional context in comments.

Comments

0

In your distanceBetweenStations() method you have this line in the else section:

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

which will produce ArrayIndexOutOfBoundsException. Why?

In your method, You create cursor:

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

and start while() loop:

 while(c1.moveToNext()) {

If there are more than 1 row in the cursor, on the first iteration, first condition is satisfied (since b is true), so your problematic line won't run yet. But you're setting b to false, so on the second row, your else section is called, and remembering that i is still 0, you have:

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

I'm not sure what you're trying to do, so these are just some ideas how to prevent an exception:

  • add a condition:

    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
        }
    }
    
  • set b to false somewhere else, instead of second else condition

  • restructure your condition altogether

As said, you're the one who knows what you want to do, so you should be able to work a solution now.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.