-3

Hi in my android application I need to display a some details in list view based upon the date. When u open the application it get get data for the last Ten days and display that. This application was working fine in few days back but now its showing some fatal exception and I double checked my code and I am unable to find any mistake.

And the errors are

02-09 12:37:11.399: E/AndroidRuntime(25430): FATAL EXCEPTION: main
02-09 12:37:11.399: E/AndroidRuntime(25430): Process: com.imaginet.everwinmatriculation, PID: 25430
02-09 12:37:11.399: E/AndroidRuntime(25430): java.lang.StringIndexOutOfBoundsException: length=802; regionStart=306; regionLength=-277
02-09 12:37:11.399: E/AndroidRuntime(25430):    at java.lang.String.startEndAndLength(String.java:504)
02-09 12:37:11.399: E/AndroidRuntime(25430):    at java.lang.String.substring(String.java:1333)
02-09 12:37:11.399: E/AndroidRuntime(25430):    at com.imaginet.everwinmatriculation.EventsFragment$5.onResponse(EventsFragment.java:284)
02-09 12:37:11.399: E/AndroidRuntime(25430):    at com.imaginet.everwinmatriculation.EventsFragment$5.onResponse(EventsFragment.java:1)
02-09 12:37:11.399: E/AndroidRuntime(25430):    at com.android.volley.toolbox.JsonRequest.deliverResponse(JsonRequest.java:65)
02-09 12:37:11.399: E/AndroidRuntime(25430):    at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99)
02-09 12:37:11.399: E/AndroidRuntime(25430):    at android.os.Handler.handleCallback(Handler.java:739)
02-09 12:37:11.399: E/AndroidRuntime(25430):    at android.os.Handler.dispatchMessage(Handler.java:95)
02-09 12:37:11.399: E/AndroidRuntime(25430):    at android.os.Looper.loop(Looper.java:135)
02-09 12:37:11.399: E/AndroidRuntime(25430):    at android.app.ActivityThread.main(ActivityThread.java:5312)
02-09 12:37:11.399: E/AndroidRuntime(25430):    at java.lang.reflect.Method.invoke(Native Method)
02-09 12:37:11.399: E/AndroidRuntime(25430):    at java.lang.reflect.Method.invoke(Method.java:372)
02-09 12:37:11.399: E/AndroidRuntime(25430):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:901)
02-09 12:37:11.399: E/AndroidRuntime(25430):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:696)

And the code is:

public class EventsFragment extends Fragment {

public EventsFragment(){}

Button btn1;
// Log tag
private static final String TAG = EventsFragment.class.getSimpleName();

private ProgressDialog pDialog;

private List<ExternalEvents> movieList = new ArrayList<ExternalEvents>();
private List<ExternalEvents> newlistfordescrip = new    ArrayList<ExternalEvents>();
private ListView listView;
private CustomListAdapter adapter;
TextView txt;
ImageButton fmdate,tddate;
static String fdate,tdate;
public static final String INDEX = "event_details";
EditText fromdate,todate;

final Calendar c = Calendar.getInstance();
int mYear = c.get(Calendar.YEAR);
int mMonth = c.get(Calendar.MONTH);
int mDay = c.get(Calendar.DAY_OF_MONTH);

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {

    View rootView = inflater.inflate(R.layout.fragment_events, container, false);

    return rootView;
}

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onActivityCreated(savedInstanceState);

    fromdate=(EditText)getActivity().findViewById(R.id.editText1);
    todate=(EditText)getActivity().findViewById(R.id.editText2);

    fmdate=(ImageButton) getActivity().findViewById(R.id.imageButton1);
    tddate=(ImageButton) getActivity().findViewById(R.id.imageButton2);

    showprograssdialog();
    jsonReqOnStartUp();

    fmdate.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {

                public void onDateSet(DatePicker view, int year,
                        int monthOfYear, int dayOfMonth) {

                    mDay = dayOfMonth;
                    mMonth = monthOfYear;
                    mYear = year;

                    updateDisplay();
                }

                private void updateDisplay() {
                    // TODO Auto-generated method stub
                    GregorianCalendar c = new GregorianCalendar(mYear, mMonth, mDay);
                    SimpleDateFormat sdf = new SimpleDateFormat("dd MMMM yyyy");

                    fromdate.setText(sdf.format(c.getTime()));

                    sdf = new SimpleDateFormat("dd-MM-yyyy");

                    fdate=sdf.format(c.getTime());
                }
            };

            DatePickerDialog d = new DatePickerDialog(getActivity(),
                    mDateSetListener, mYear, mMonth, mDay);
            d.getDatePicker().setMaxDate(System.currentTimeMillis()-1000);
            d.show();

        }
    });

    tddate.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {

                public void onDateSet(DatePicker view, int year,
                        int monthOfYear, int dayOfMonth) {

                    mDay = dayOfMonth;
                    mMonth = monthOfYear;
                    mYear = year;

                    updateDisplay();
                }

                private void updateDisplay() {
                    // TODO Auto-generated method stub
                    GregorianCalendar c = new GregorianCalendar(mYear, mMonth, mDay);
                    SimpleDateFormat sdf = new SimpleDateFormat("dd MMMM yyyy");

                    todate.setText(sdf.format(c.getTime()));

                    sdf = new SimpleDateFormat("dd-MM-yyyy");

                    tdate=sdf.format(c.getTime());

                }
            };

            DatePickerDialog d = new DatePickerDialog(getActivity(),
                    mDateSetListener, mYear, mMonth, mDay);
            d.getDatePicker().setMaxDate(System.currentTimeMillis()-1000);

            d.show();

        }
    });
    listView = (ListView) getActivity().findViewById(R.id.list);
    adapter = new CustomListAdapter(getActivity(), movieList);
    listView.setAdapter(adapter);

    btn1 = (Button) getActivity().findViewById(R.id.button1);
    btn1.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub

            if(tdate==null)
            {
                Toast.makeText(getActivity(), "To Date Cannot be empty Please set it", Toast.LENGTH_LONG).show();
            }
            if(fdate==null)
            {
                Toast.makeText(getActivity(), "From Date Cannot be empty Please set it", Toast.LENGTH_LONG).show();
            }
            if(fdate == tdate)
            {
                Toast.makeText(getActivity(), "From and To date cannot be same", Toast.LENGTH_LONG).show();
            }
            if((fdate!=null)&&(tdate!=null)&&(fdate!=tdate))
            {
                movieList.clear();
                newlistfordescrip.clear();
                showprograssdialog();
                makeJsonObjectRequest();
            }
        }
    });

    listView.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position,
                long id) {
            // TODO Auto-generated method stub
            String desc, tagDesc;
            ExternalEvents m = movieList.get(position);
            ExternalEvents n = newlistfordescrip.get(position);
            desc=m.getdescription();
            tagDesc=n.getdescription();

            // Starting single contact activity
            Intent in = new Intent(getActivity(),Eventsdisplay.class);

            in.putExtra("eventdetails", m.getevent_details());
            in.putExtra("date", m.getdate());
            in.putExtra("description", n.getdescription());
            if(m.getThumbnailUrl().get(0) != null)
            {
                in.putExtra("imageval", "notnull");
                Bundle bundleObject = new Bundle(); 
                bundleObject.putSerializable("image",m.getThumbnailUrl());
                in.putExtras(bundleObject);
            }
            else
            {
                in.putExtra("imageval", "null");
            }
            startActivity(in);
        }
    });

    // changing action bar color
    getActivity().getActionBar().setBackgroundDrawable(
            new ColorDrawable(Color.parseColor("#1b1b1b")));
}

void jsonReqOnStartUp(){
    Calendar fDateload=new GregorianCalendar(mYear,mMonth,mDay-30);
    Calendar tDateload=new GregorianCalendar(mYear,mMonth,mDay);    
    SimpleDateFormat sdf= new SimpleDateFormat("dd-MM-yyyy");

    String  tdateld=sdf.format(tDateload.getTime());
    String  fdateld=sdf.format(fDateload.getTime());
    String url ="http://matric.everwinschool.in/webservice/rest/?module=internalevents&from="+fdateld+"&to="+tdateld;
    url = url.replaceAll(" ", "%20");

    // Creating volley request obj
    JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.GET,

            url, null, new Response.Listener<JSONObject>() {

        @Override
        public void onResponse(JSONObject response) {
            // TODO Auto-generated method stub
            //showpDialog();
            JSONArray value;
            try {
                value = response.getJSONArray("Internal Events");

                for (int i = 0; i < value.length(); i++)
                {
                    JSONObject obj = value.getJSONObject(i);
                    JSONObject objOther = value.getJSONObject(i);

                    ExternalEvents events = new ExternalEvents();
                    ExternalEvents tagEvents = new ExternalEvents();
                    tagEvents.setdescription(obj.getString("description"));

                    events.setevent_detils(obj.getString("event_details"));
                    events.setdate(obj.getString("date"));
                    tagEvents.setdescription(obj.getString("description"));
                    String strDescrip =  obj.getString("description");

                    while(strDescrip.contains("&"))
                        strDescrip = strDescrip.replace(strDescrip.substring(strDescrip.indexOf("&"),strDescrip.indexOf(";")+1),"");
                    while(strDescrip.contains("<"))
                        strDescrip = strDescrip.replace(strDescrip.substring(strDescrip.indexOf("<"),strDescrip.indexOf(">")+1),"");
                    events.setdescription(strDescrip);

                    String str=obj.getString("image");
                    if(str.equalsIgnoreCase("null"))
                    {
                        events.setThumbnailUrl(0,null);
                    }
                    else
                    {
                        String[] mArray = str.split(",");

                        for(int j=0;j<mArray.length;j++)
                        {
                            events.setThumbnailUrl(j, mArray[j]);
                        }
                        mArray=null;
                    }

                    //Adding movie to movies array
                    movieList.add(events);
                    newlistfordescrip.add(tagEvents);
                }   
                hidePDialog();
            } catch (JSONException e) {
                e.printStackTrace();
            }

            // notifying list adapter about data changes
            // so that it renders the list view with updated data
            adapter.notifyDataSetChanged();
        }

    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            VolleyLog.d(TAG, "Error: " + error.getMessage());
            Toast.makeText(getActivity(), "Unable to fetch data", Toast.LENGTH_LONG).show();
            hidePDialog();

        }
    });

    // Adding request to request queue
    AppController.getInstance().addToRequestQueue(jsonObjReq);  
}
protected void makeJsonObjectRequest() {
    // TODO Auto-generated method stub
    String url ="http://matric.everwinschool.in/webservice/rest/?module=internalevents&from="+fdate+ "&to=" +tdate;
    url = url.replaceAll(" ", "%20");

    // Creating volley request obj
    JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.GET,

            url, null, new Response.Listener<JSONObject>() {

        @Override
        public void onResponse(JSONObject response) {
            // TODO Auto-generated method stub
            //showpDialog();
            JSONArray value;
            try {
                value = response.getJSONArray("Internal Events");


                for (int i = 0; i < value.length(); i++)
                {
                    JSONObject obj = value.getJSONObject(i);
                    JSONObject objOther = value.getJSONObject(i);

                    ExternalEvents events = new ExternalEvents();
                    ExternalEvents tagEvents = new ExternalEvents();
                    tagEvents.setdescription(obj.getString("description"));

                    events.setevent_detils(obj.getString("event_details"));
                    events.setdate(obj.getString("date"));
                    tagEvents.setdescription(obj.getString("description"));
                    String strDescrip =  obj.getString("description");

                    while(strDescrip.contains("&"))
                        strDescrip = strDescrip.replace(strDescrip.substring(strDescrip.indexOf("&"),strDescrip.indexOf(";")+1),"");
                    while(strDescrip.contains("<"))
                        strDescrip = strDescrip.replace(strDescrip.substring(strDescrip.indexOf("<"),strDescrip.indexOf(">")+1),"");

                    events.setdescription(strDescrip);

                    String str=obj.getString("image");

                    String[] mArray = str.split(",");

                    for(int j=0;j<mArray.length;j++)
                    {
                        events.setThumbnailUrl(j, mArray[j]);
                    }
                    mArray=null;
                    // adding movie to movies array
                    movieList.add(events);
                    //String stradd = obj.getString("description");
                    newlistfordescrip.add(tagEvents);
                }   
                hidePDialog();
            } catch (JSONException e) {
                e.printStackTrace();
            }

            // notifying list adapter about data changes
            // so that it renders the list view with updated data
            adapter.notifyDataSetChanged();
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            VolleyLog.d(TAG, "Error: " + error.getMessage());
            Toast.makeText(getActivity(), "Unable to fetch data", Toast.LENGTH_LONG).show();
            hidePDialog();
        }
    });

    // Adding request to request queue
    AppController.getInstance().addToRequestQueue(jsonObjReq);  
}

private void showprograssdialog() {
    // TODO Auto-generated method stub
    pDialog = new ProgressDialog(getActivity());
    pDialog.setMessage("Please wait...");
    //  pDialog.setCancelable(false);
    pDialog.show();
}

protected void hidePDialog() {
    // TODO Auto-generated method stub

    if (pDialog != null) {
        pDialog.dismiss();
        pDialog = null;
    }
}

}
Encipherer
  • 411
  • 7
  • 23
  • 1
    as it says, your code is trying to access an array element index which is not there to begin with – Pankaj Nimgade Feb 09 '15 at 07:44
  • can u say how to fix that??? – Encipherer Feb 09 '15 at 07:45
  • @JaswinderWadali, well said, it will only go through elements which are available. just make a check before calling foreach that your array is not empty – Pankaj Nimgade Feb 09 '15 at 07:47
  • The issue is with one of the calls to `substring()` as the stacktrace shows. A good guess would be that one of the calls to `indexOf()` returns with `-1` (not found) and that causes the `substring()` call to return `StringIndexOutOfBoundsException` – Nir Alfasi Feb 09 '15 at 07:51
  • @JaswinderWadali what does foreach loop has anything to do with his issue? – Nir Alfasi Feb 09 '15 at 07:52
  • 2
    Guys it's not an `ArrayIndexOutOfBoundsException`. It is a `StringIndexOutOfBoundsException`. This means that either the code is trying to access a character at an index out of the length of the string or it is trying to substring out of the length of the string – EdmDroid Feb 09 '15 at 07:54

1 Answers1

2

In the lines

while(strDescrip.contains("&"))
                    strDescrip = strDescrip.replace(strDescrip.substring(strDescrip.indexOf("&"),strDescrip.indexOf(";")+1),"");
while(strDescrip.contains("<"))
                    strDescrip = strDescrip.replace(strDescrip.substring(strDescrip.indexOf("<"),strDescrip.indexOf(">")+1),"");

You check that strDescrip.contains("&") but do not check that strDescrip.contains(";"), the same with < and >.

18446744073709551615
  • 16,368
  • 4
  • 94
  • 127