代码之家  ›  专栏  ›  技术社区  ›  Encipherer

Android应用程序中的索引超出范围异常

  •  -3
  • Encipherer  · 技术社区  · 9 年前

    嗨,在我的android应用程序中,我需要根据日期在列表视图中显示一些详细信息。当你打开应用程序时,它会获取最近十天的数据并显示出来。前几天这个应用程序运行良好,但现在它显示了一些致命的异常,我仔细检查了代码,无法发现任何错误。

    错误是

    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)
    

    代码是:

    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;
        }
    }
    
    }
    
    1 回复  |  直到 9 年前
        1
  •  2
  •   18446744073709551615    9 年前

    在线路中

    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),"");
    

    你检查一下 strDescrip.contains("&") 但不要检查 strDescrip.contains(";") ,与相同 < > .