java.lang.ArrayIndexOutOfBoundsException:length = 1; index = 1 ERROR

时间:2015-11-25 09:16:50

标签: java android arrays

从数组中检索数据时,我的应用程序出现问题。

SchedulePage:

    public class SchedulePage extends Activity {

    List<MyTask> tasks;
    List<Test_Sched> SchedList;
//  Intent intent = getIntent();
//  String Username = intent.getStringExtra("Username2");
    int Count = 0;
    String SendCount = "";

    TextView endtv, durationtv;


    //storage of Test_Name 
    private static ArrayList<String> Test_Name = new ArrayList<String>();

    //storage of x values in array private 
    private static ArrayList<Integer> Duration = new ArrayList<Integer>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_schedule_page);

        endtv = (TextView) findViewById(R.id.Endtv);
        durationtv = (TextView) findViewById(R.id.Durationtv);

        //Use this to Create Layouts Dynamically
        //RelativeLayout relativeLayout = new RelativeLayout(this);

        tasks = new ArrayList<>();

        GetSchedule();

        //GridView gv = (GridView) findViewById(R.id.grid);
        //gv.setAdapter(new ImageAdapter(getApplicationContext()));


        //Storing test name Arraylist in a array
        final String [] web = Test_Name.toArray(new String[Test_Name.size()]);

        //Storing images  in a array
        ArrayList<Integer> imagesAL = new ArrayList<Integer>();
        for(int i = 0; i < Test_Name.size(); i++){
        //  String testname = web[i];
            String lf = "One Leg(Left)", rf = "One Leg(Right)", sf = "Separate Foot", sbsf= "Side By Side Foot", tthr ="Toe To Heel(Right)", tthl ="Toe To Heel(Left)";

            if(lf.equals(Test_Name.get(i))){
                imagesAL.add(R.drawable.leftfoot);
            }
            if(rf.equals(Test_Name.get(i))){
                imagesAL.add(R.drawable.rightfoot);
            }
            if(sf.equals(Test_Name.get(i))){
                imagesAL.add(R.drawable.feetapart);

            }
            if(sbsf.equals(Test_Name.get(i))){
                imagesAL.add(R.drawable.sidebysidefoot);

            }
            if(tthr.equals(Test_Name.get(i))){
                imagesAL.add(R.drawable.righttoetoleftheel);
            }
            if(tthl.equals(Test_Name.get(i))){
                imagesAL.add(R.drawable.lefttoetorightheel);
            }
            }

        Integer [] imageId = imagesAL.toArray(new Integer[imagesAL.size()]);

        ImageAdapter adapter = new ImageAdapter(SchedulePage.this, web, imageId);
        GridView grid;
        grid=(GridView)findViewById(R.id.grid);
                grid.setAdapter(adapter);
                grid.setOnItemClickListener(new AdapterView.OnItemClickListener() {

                    @Override
                    public void onItemClick(AdapterView<?> parent, View view,
                                            int position, long id) {
                        Toast.makeText(SchedulePage.this, "You Clicked at " +web[+ position], Toast.LENGTH_SHORT).show();

                    }
                });

    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.schedule_page, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    //Login Stuff

    public static ArrayList<Integer> getDuration() {
          return Duration;
       }

    public static ArrayList<String> getTestName() {
          return Test_Name;
       }

    private void GetSchedule(){
    String jsonOutput = "http://172.20.34.112/IBBTS_WebService_MobileAndDevice/Service1.asmx/GetSchedule";

    if (isOnline()) {
        //while(End == "not yet"){
        requestData(jsonOutput);
        //}
    }else {
        Toast.makeText(SchedulePage.this, "Network isn't available", Toast.LENGTH_LONG).show();

    }
}
    private static String doJSONHTTPCall(String urlStr) {
        String output2 = "";
        try {

            URL url;
            try {
                url = new URL(urlStr);
            } 
            catch (MalformedURLException e) {
                throw e;
            }
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setRequestProperty("Accept", "application/json");

            BufferedReader br = new BufferedReader(new InputStreamReader(
                    (conn.getInputStream())));

            String output;
            while ((output = br.readLine()) != null) {
                output2 += output;
            }

            conn.disconnect();
        } 
        catch (MalformedURLException e) {
            e.printStackTrace();
        } 
        catch (IOException e) {
            e.printStackTrace();
        }

        return output2;
    }

    private void requestData(String uri) {
        //Send the integer to String
        Bundle gt=getIntent().getExtras();
        String usernamePass =gt.getString("userName2");
        SendCount = Integer.toString(Count);
        RequestPackage p = new RequestPackage();
        p.setMethod("GET");
        p.setUri(uri);
        p.setParam("Username", usernamePass);

        MyTask task = new MyTask();
        task.execute(p);
        }

    protected void updateDisplay(){

        if (SchedList != null) {
            for (Test_Sched test_Sched : SchedList) {
                Duration.add(test_Sched.getDuration());
                Test_Name.add(test_Sched.getTest_Name());
                Count++;
            }
            }

    }

    protected boolean isOnline() {

        ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
                NetworkInfo netInfo  = cm.getActiveNetworkInfo();
        if (netInfo != null && netInfo.isConnectedOrConnecting()) {
            return true;
        } else {
            return false;
        }

    }
    private class MyTask extends AsyncTask<RequestPackage, String, String>{

        @Override
        protected void onPreExecute() {
            //updateDisplay("Starting Task");

            if (tasks.size() == 0) {
                //progress.setVisibility(View.VISIBLE);
            }
            tasks.add(this);
        }

            @Override
            protected String doInBackground(RequestPackage... params) {

                String content = HttpManager.getData(params[0]);
                return content;

            }

            @Override
                protected void onPostExecute(String result) {
                SchedList = ScheduleJSONParser.parseFeed(result);
                updateDisplay();
                tasks.remove(this);
                if (tasks.size() == 0) {
                    //progress.setVisibility(View.INVISIBLE);
                }
                }
            @Override
                protected void onProgressUpdate(String... values) {
                    //updateDisplay(values[0]);
                }
        }
}

ScheduleJSONParsor

public class ScheduleJSONParser {

public static List<Test_Sched> parseFeed(String content) {

    try {
        JSONArray ar = new  JSONArray(content);
        List<Test_Sched> SchedList = new ArrayList<>();

        for (int i = 0; i < ar.length(); i++) {

            JSONObject obj = ar.getJSONObject(i);
            Test_Sched test_Sched = new Test_Sched();

            test_Sched.setDuration(Integer.parseInt(obj.getString("Duration")));
            test_Sched.setTest_Name(obj.getString("Test_Name"));

            SchedList.add(test_Sched); 

        }

        return SchedList;
    } catch (JSONException e) {
        e.printStackTrace();
        return null;
    }

}}

logcat没有指出哪一行有错误,我发现很难排除故障。 我们的想法是从数据库中检索计划并将其传递给数组。然后,应用程序将显示每个练习名称的图像按钮。

当我从主菜单中单击schedulePage按钮时,它显示为空白,我必须第二次重新单击schedulePage。第二次显示arrayoutofbounds错误..

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

原因是这两行

GetSchedule();

final String [] web = Test_Name.toArray(new String[Test_Name.size()]);

GetSChedule()中您正在后台运行线程,并且从webservice的响应中您正在填充Test_Name数组。但在调用webservice之前,您正在将Test_Name数据复制到Web阵列,因此您的web []将为空,因为Test_Name中没有数据。

web[]全球

String [] web;

将其填入updateDisplay()

protected void updateDisplay(){
    if (SchedList != null) {
        for (Test_Sched test_Sched : SchedList) {
            Duration.add(test_Sched.getDuration());
            Test_Name.add(test_Sched.getTest_Name());
            Count++;
        }
        web = Test_Name.toArray(new String[Test_Name.size()]);
        }

}