我的代码有问题。我将数据从一个活动传递到另一个活动,没有问题,但是当我尝试显示时间表是从微调器中选择时,它给了我索引超出范围的异常

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.sql.Time;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;
import android.app.AlertDialog;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.graphics.Color;
import android.support.v4.view.PagerTabStrip;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;

public class TimetableMainActivity extends AppCompatActivity {

final String[] page_titles = new String[]{"Mon", "Tue", "Wed", "Thu", "Fri"};

final String[] hours = new String[]{"9", "10", "11", "noon", "1", "2", "3", "4", "5", "6"};

private String[][] days;
private int pos;
private String source = null;

public static ArrayList<String> schedule = new ArrayList<String>();

List<Map<String, String>>[] list = new List[5]; // Mon - Fri
Map<String, String> map;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (!isNetworkAvailable())
        new AlertDialog.Builder(TimetableMainActivity.this).
                setTitle("Error").setMessage("No Network Connection").
                setNeutralButton("Close", null).show();
    else {
        new GetXML().execute("");
    }
}

public boolean isNetworkAvailable() {
    ConnectivityManager cm = (ConnectivityManager)
            getSystemService(Context.CONNECTIVITY_SERVICE);

    NetworkInfo networkInfo = cm.getActiveNetworkInfo();

    if (networkInfo != null && networkInfo.isConnected())
        return true;
    else
        return false;
}

private class GetXML extends AsyncTask<String, Void, String> {
    String src = null;

    @Override
    protected String doInBackground(String... params) {
        Bundle extras = getIntent().getExtras();
        source = extras.getString("Name");
        try {
            URL url = new URL(source);
            HttpURLConnection con = (HttpURLConnection) url.openConnection();
            src = readStream(con.getInputStream());

        } catch (Exception e) {
            e.printStackTrace();
        }

        return src;
    }

    @Override
    protected void onPostExecute(String result) {
        if (src == null)
            new AlertDialog.Builder(TimetableMainActivity.this).
                    setTitle("Error").setMessage("No Schedule Found").
                    setNeutralButton("Close", null).show();
        else parseXML(src);

        setContentView(R.layout.activity_main_timetable);


            days = new String[5][10];
            for (int i = 0; i < 5; i++) {
                for (int j = 0; j < 10; j++) {
                    int k = i * 10 + j;
                    days[i][j] = schedule.get(k);
                }
            }


        for (int i = 0; i < 5; i++)
            list[i] = new ArrayList<Map<String, String>>();

        int count = hours.length;

        for (int j = 0; j < 5; j++) {
            for (int i = 0; i < count; i++) {
                map = new HashMap<String, String>();
                map.put("time", hours[i]);
                map.put("description", days[j][i]);
                list[j].add(map);
            }
        }

        Calendar cal = Calendar.getInstance();
        int today = cal.get(Calendar.DAY_OF_WEEK) - 2;

        pos = 0;
        if (today >= 0 && today <= 4)
            pos = today;

        ViewPager viewPager = findViewById(R.id.ViewPager);
        CustomPagerAdapter adapter = new CustomPagerAdapter(TimetableMainActivity.this, list);
        PagerTabStrip pagerTabStrip = findViewById(R.id.pager_tab);

        int color = Color.parseColor("#33b7ee");
        pagerTabStrip.setTabIndicatorColor(color);

        viewPager.setAdapter(adapter);
        viewPager.setCurrentItem(pos);
    }

    @Override
    protected void onPreExecute() {
    }

    @Override
    protected void onProgressUpdate(Void... values) {
    }
}

public void parseXML(String src) {
    try {
        StringReader sr = new StringReader(src);
        XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
        factory.setNamespaceAware(true);
        XmlPullParser xpp = factory.newPullParser();
        xpp.setInput(sr);

        int token = xpp.getEventType();
        while (token != XmlPullParser.END_DOCUMENT) {
            if (token == XmlPullParser.START_TAG) {
                if (xpp.getName().equals("cid")) {
                    token = xpp.nextToken();

                    if (xpp.getText() == null)
                        schedule.add("");

                    if (token == XmlPullParser.TEXT) {
                        schedule.add(xpp.getText());
                    }
                }
            }

            token = xpp.nextToken();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

private String readStream(InputStream in) {
    BufferedReader reader = null;
    String line = null;
    StringBuffer sb = new StringBuffer();
    try {
        reader = new BufferedReader(new InputStreamReader(in));
        while ((line = reader.readLine()) != null) {
            sb.append(line);
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return sb.toString();
}


这是第二个活动,传递了第一个活动的数据,在这里:

public class ScheduleMainActivity extends AppCompatActivity {

final static String[] programs = { "Select Program", "Architectural",
        "Civil", "Geomatics", "Computing Systems", "Biomedical",
        "Instrumentation", "Electrical (Power)",
        "Telecommunications", "Chemical Processing", "Industrial", "Mechanical",
        "Manufacturing", "Petroleum" };

final static String[] years = { "Select Year", "First", "Second", "Third" };

String p = new String();
String y = new String();
String cid = new String();
String loc = new String();



@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main_schedule);

    Spinner spinner_p = (Spinner) findViewById(R.id.spinner_p);
    ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(ScheduleMainActivity.this,
            R.layout.spinnerrow, R.id.spinner_id, programs);
    spinner_p.setAdapter(arrayAdapter);

    spinner_p.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

        public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
            switch(pos) {
                case 1 : cid = "ae"; break;
                case 2 : cid = "ce"; break;
                case 3 : cid = "ge"; break;
                case 4 : cid = "cs"; break;
                case 5 : cid = "eb"; break;
                case 6 : cid = "ei"; break;
                case 7 : cid = "ep"; break;
                case 8 : cid = "te"; break;
                case 9 : cid = "cp"; break;
                case 10: cid = "in"; break;
                case 11: cid = "me"; break;
                case 12: cid = "mm"; break;
                case 13: cid = "pe"; break;
                default: break;
            }
            p = programs[pos];
        }

        public void onNothingSelected(AdapterView<?> parent) {
        }
    });

    Spinner spinner_y = (Spinner) findViewById(R.id.spinner_y);
    ArrayAdapter<String> y_arrayAdapter = new ArrayAdapter<String>(ScheduleMainActivity.this,
            R.layout.spinnerrow, R.id.spinner_id, years);
    spinner_y.setAdapter(y_arrayAdapter);

    spinner_y.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

        public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
            y = years[pos];
        }

        public void onNothingSelected(AdapterView<?> parent) {
        }
    });

    final Button b = (Button) findViewById(R.id.schedule);

    b.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            if(v == b) {
                if(event.getAction() == MotionEvent.ACTION_DOWN) {
                    v.setAlpha(.3f);
                }
                else {
                    v.setAlpha(1f);
                }
            }
            return false;
        }
    });

    b.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View arg0) {
            if(p.equals("Select Program") || y.equals("Select Year"))
                new AlertDialog.Builder(ScheduleMainActivity.this).
                        setTitle("Error").setMessage("No Program/Year selected").
                        setNeutralButton("Close", null).show();
            else {
                Calendar cal = Calendar.getInstance();
                SimpleDateFormat monthFormat = new SimpleDateFormat("M");
                String month_name = monthFormat.format(cal.getTime());

                int month = Integer.parseInt(month_name);
                int selectedYear = 0;

                if(y.equals("First"))
                    selectedYear = 1;
                else if(y.equals("Second"))
                    selectedYear = 2;
                else if(y.equals("Third"))
                    selectedYear = 3;

                int semester = 0;
                if(month >= 9 && month <= 12) {
                    semester = 3 * selectedYear - 2;
                }
                else if(month >= 1 && month <= 4) {
                    semester = 3 * selectedYear - 1;
                }
                else {
                    semester = 3 * selectedYear;
                }

                StringBuffer sb = new StringBuffer();
                sb.append("http://branko-cirovic.appspot.com/etcapp/timetables/timetable_"); sb.append(cid); sb.append(semester); sb.append(".xml");
                loc = sb.toString();

                Toast.makeText(ScheduleMainActivity.this,"You Selected : "
                        + loc, Toast.LENGTH_SHORT).show();

                Intent intent = new Intent(ScheduleMainActivity.this, TimetableMainActivity.class);
                intent.putExtra("Name", loc);
                startActivity(intent);

            }
        }
    });

}


}

如果有人可以解决我的问题或告诉我如何解决它,请多多关照

最佳答案

所以问题实际上出在我试图传递给第二个活动的URL上,这是错误的。

现在,通过将“捆绑包”添加到第二个活动的try语句中,它已经可以正常工作

07-25 22:43