解决java.lang.IndexOutOfBoundsException:索引0无效,大小为0?

时间:2018-06-11 12:02:02

标签: android indexoutofboundsexception

我有一个使用MpAndroidchart库的折线图,我想使用来自myphp / mysql服务器的一些数据添加元素

现在问题是我正在尝试获取id,所以我向服务器发送请求并尝试获取id,并且其响应是

[{"id":"1","username":"jena@gmail.com","password":"123"},{"id":"2","username":"test@gmail.com","password":"1234"},{"id":"3","username":"test2@gmail.com","password":"12345"},{"id":"4","username":"test3@gmail.com","password":"123456"},{"id":"5","username":"test4@gmail.com","password":"1234567"},{"id":"6","username":"test3@gmail.com","password":"12345678"},{"id":"7","username":"test3@gmail.com","password":"123456789"}]

但不幸的是抛出了IndexOutOfBoundsException的异常,尽管arraylist不是空的,因为我用listview检查了它

我的主要活动

public class testActivity extends Activity {

private static final String TAG = "ChartActivity";

private LineChart mChart;
private BarChart barChart;
private ScatterChart scatterChart;
private BubbleChart bubbleChart;
private PieChart pieChart;
Context c;

ArrayList<Integer> tr=new ArrayList<>();


@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.chart);
    c = this.getApplicationContext();


    mChart = (LineChart) findViewById(R.id.linechart);

    //mChart.setOnChartGestureListener(ChartActivity.this);
    //mChart.setOnChartValueSelectedListener(ChartActivity.this);
    mChart.setDragEnabled(true);
    mChart.setScaleEnabled(false);

    LimitLine upper_limit = new LimitLine(65f, "Danger");
    upper_limit.setLineWidth(4f);
    upper_limit.enableDashedLine(10f, 10f, 0);
    upper_limit.setLabelPosition(LimitLine.LimitLabelPosition.RIGHT_TOP);
    upper_limit.setTextSize(15f);


    LimitLine lower_limit = new LimitLine(35f, "too low");
    upper_limit.setLineWidth(4f);
    upper_limit.enableDashedLine(10f, 10f, 0);
    upper_limit.setLabelPosition(LimitLine.LimitLabelPosition.RIGHT_BOTTOM);
    upper_limit.setTextSize(15f);

    YAxis leftAxis = mChart.getAxisLeft();
    leftAxis.removeAllLimitLines();
    leftAxis.addLimitLine(upper_limit);
    leftAxis.addLimitLine(lower_limit);
    leftAxis.setAxisMaximum(100f);
    leftAxis.setAxisMinimum(25f);
    leftAxis.enableGridDashedLine(10f, 10f, 0);
    leftAxis.setDrawLimitLinesBehindData(true);

    mChart.getAxisRight().setEnabled(false);


    downloadChart d=new downloadChart(c,url);


    d.execute();



    ArrayList<Entry> yValues = new ArrayList<>();

    if(tr!=null && tr.size()!=0){
        tr.addAll(parseChart.players);
        for (int i = 0; i < tr.size(); i++) {
            yValues.add(new Entry(tr.get(i), i));
        }
    }


    LineDataSet set1 = new LineDataSet(yValues, "Data set 1");
    set1.setFillAlpha(110);
    set1.setColor(Color.RED);
    set1.setLineWidth(3f);
    set1.setValueTextSize(10f);

    ArrayList<ILineDataSet> dataSets = new ArrayList<>();
    dataSets.add(set1);
    LineData data = new LineData(dataSets);
    mChart.setData(data);

    String[] values = {"first", "second", "third", "anything", "testing", "likewise", "finally"};

    XAxis xAxis = mChart.getXAxis();
    xAxis.setValueFormatter(new MyXAxisValueFormatter(values));
    xAxis.setGranularity(1f);


}

public class MyXAxisValueFormatter implements IAxisValueFormatter {
    private String[] mValues;
    public MyXAxisValueFormatter(String[] values){
        this.mValues = values;
    }

    @Override
    public String getFormattedValue(float value, AxisBase axis) {
        return mValues[(int)value];
    }
}

}

这是我的下载课程

public class downloadChart extends AsyncTask<Void,Integer,String> {

Context c;
String address;
//ListView lv;

ProgressDialog pd;

public downloadChart(Context c, String address) {
    this.c = c;
    this.address = address;
    //this.lv = lv;
}

//B4 JOB STARTS
@Override
protected void onPreExecute() {
    super.onPreExecute();

    pd=new ProgressDialog(c);
    pd.setTitle("Fetch Data");
    pd.setMessage("Fetching Data...Please wait");
    //pd.show();
}

@Override
protected String doInBackground(Void... params) {
    String data=downloadData();
    return data;
}

@Override
protected void onPostExecute(String s) {
    super.onPostExecute(s);

    pd.dismiss();;

    if(s != null)
    {
        parseChart p=new parseChart(c,s);

        p.execute();

    }else
    {
        Toast.makeText(c,"Unable to download data",Toast.LENGTH_SHORT).show();
    }
}

private String downloadData()
{
    //connect and get a stream
    InputStream is=null;
    String line =null;

    try {
        URL url=new URL(address);
        HttpURLConnection con= (HttpURLConnection) url.openConnection();
        is=new BufferedInputStream(con.getInputStream());

        BufferedReader br=new BufferedReader(new InputStreamReader(is));

        StringBuffer sb=new StringBuffer();

        if(br != null) {

            while ((line=br.readLine()) != null) {
                sb.append(line+"n");
            }

        }else {
            return null;
        }

        return sb.toString();

    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }finally {
        if(is != null)
        {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return null;
}
}

最后是班级

public class parseChart extends AsyncTask<Void,Integer,Integer> {

Context c;
//ListView lv;
String data;

public static ArrayList<Integer> players=new ArrayList<>();
ProgressDialog pd;

public parseChart(Context c, String data) {
    this.c = c;
    this.data = data;
    //this.lv = lv;
}

@Override
protected void onPreExecute() {
    super.onPreExecute();

    pd=new ProgressDialog(c);
    pd.setTitle("Parser");
    pd.setMessage("Parsing ....Please wait");
    //pd.show();
}

@Override
protected Integer doInBackground(Void... params) {

    return this.parse();
}

@Override
protected void onPostExecute(Integer integer) {
    super.onPostExecute(integer);

    if(integer == 1)
    {
        //ADAPTER
        ArrayAdapter<Integer> adapter=new ArrayAdapter<Integer>(c,android.R.layout.simple_list_item_1,players);

        //ADAPT TO LISTVIEW

        //lv.setAdapter(adapter);

        //LISTENET
      //copy code

    }else
    {
        Toast.makeText(c,"Unable to Parse",Toast.LENGTH_SHORT).show();
    }

    pd.dismiss();
}

//PARSE RECEIVED DATA
private int parse()
{
    try
    {
        //ADD THAT DATA TO JSON ARRAY FIRST
        JSONArray ja=new JSONArray(data);

        //CREATE JO OBJ TO HOLD A SINGLE ITEM
        JSONObject jo=null;

        players.clear();

        //LOOP THRU ARRAY
        for(int i=0;i<ja.length();i++)
        {
            jo=ja.getJSONObject(i);

            //RETRIOEVE NAME
            String name=jo.getString("id");

            //ADD IT TO OUR ARRAYLIST
            players.add(Integer.parseInt(name));
        }

        return 1;

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

    return 0;
}
}

这是我的完整错误日志

E/AndroidRuntime: FATAL EXCEPTION: main
              Process: com.example.android.apptry, PID: 4401
              java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
                  at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255)
                  at java.util.ArrayList.get(ArrayList.java:308)
                  at com.github.mikephil.charting.data.DataSet.getEntryForIndex(DataSet.java:286)
                  at com.github.mikephil.charting.utils.Transformer.generateTransformedValuesLine(Transformer.java:184)
                  at com.github.mikephil.charting.renderer.LineChartRenderer.drawValues(LineChartRenderer.java:547)
                  at com.github.mikephil.charting.charts.BarLineChartBase.onDraw(BarLineChartBase.java:264)
                  at android.view.View.draw(View.java:14465)
                  at android.view.View.getDisplayList(View.java:13362)
                  at android.view.View.getDisplayList(View.java:13404)
                  at android.view.View.draw(View.java:14182)
                  at android.view.ViewGroup.drawChild(ViewGroup.java:3103)
                  at android.view.ViewGroup.dispatchDraw(ViewGroup.java:2940)
                  at android.view.View.getDisplayList(View.java:13357)
                  at android.view.View.getDisplayList(View.java:13404)
                  at android.view.View.draw(View.java:14182)
                  at android.view.ViewGroup.drawChild(ViewGroup.java:3103)
                  at android.view.ViewGroup.dispatchDraw(ViewGroup.java:2940)
                  at android.view.View.getDisplayList(View.java:13357)
                  at android.view.View.getDisplayList(View.java:13404)
                  at android.view.View.draw(View.java:14182)
                  at android.view.ViewGroup.drawChild(ViewGroup.java:3103)
                  at android.view.ViewGroup.dispatchDraw(ViewGroup.java:2940)
                  at android.view.View.draw(View.java:14468)
                  at com.android.internal.widget.ActionBarOverlayLayout.draw(ActionBarOverlayLayout.java:381)
                  at android.view.View.getDisplayList(View.java:13362)
                  at android.view.View.getDisplayList(View.java:13404)
                  at android.view.View.draw(View.java:14182)
                  at android.view.ViewGroup.drawChild(ViewGroup.java:3103)
                  at android.view.ViewGroup.dispatchDraw(ViewGroup.java:2940)
                  at android.view.View.draw(View.java:14468)
                  at android.widget.FrameLayout.draw(FrameLayout.java:472)
                  at com.android.internal.policy.impl.PhoneWindow$DecorView.draw(PhoneWindow.java:2326)
                  at android.view.View.getDisplayList(View.java:13362)
                  at android.view.View.getDisplayList(View.java:13404)
                  at android.view.HardwareRenderer$GlRenderer.buildDisplayList(HardwareRenderer.java:1569)
                  at android.view.HardwareRenderer$GlRenderer.draw(HardwareRenderer.java:1448)
                  at android.view.ViewRootImpl.draw(ViewRootImpl.java:2381)
                  at android.view.ViewRootImpl.performDraw(ViewRootImpl.java:2253)
                  at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1883)
                  at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1000)
                  at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5670)
                  at android.view.Choreographer$CallbackRecord.run(Choreographer.java:761)
                  at android.view.Choreographer.doCallbacks(Choreographer.java:574)
                  at android.view.Choreographer.doFrame(Choreographer.java:544)
                  at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:747)
                  at android.os.Handler.handleCallback(Handler.java:733)
                  at android.os.Handler.dispatchMessage(Handler.java:95)
                  at android.os.Looper.loop(Looper.java:136)
                  at android.app.ActivityThread.main(ActivityThread.java:5017)
                  at java.lang.reflect.Method.invokeNative(Native Method)
                  at java.lang.reflect.Method.invoke(Method.java:515)
                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
                  at dalvik.system.NativeStart.main(Native Method)

申请已终止。

2 个答案:

答案 0 :(得分:0)

我使用了改造库来从我的服务器获取json数据 它正在工作:)

答案 1 :(得分:0)

首先,该错误发生在dataSet中。然后仔细检查您的代码。yValues为空。会影响结果吗?最后,您的downloadChart是异步的,因此您的代码

    ArrayList<Entry> yValues = new ArrayList<>();

    if(tr!=null && tr.size()!=0){
    tr.addAll(parseChart.players);
    for (int i = 0; i < tr.size(); i++) {
        yValues.add(new Entry(tr.get(i), i));
    }
}

是没有意义的,请再次检查您的代码并确保数据合法,然后对其进行调试。