我如何修复 java.lang.IndexOutOfBoundsException: Index: 0, Size: 0 in android?我正在尝试学习 ArrayList

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42607994/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 06:45:35  来源:igfitidea点击:

How do i fix java.lang.IndexOutOfBoundsException: Index: 0, Size: 0 in android? I am trying to learn ArrayList

javaandroidarraylistindexoutofboundsexception

提问by Bokch

What the hell is this thing

这是什么鬼东西

public class MainActivity extends AppCompatActivity {
ArrayList<String> celebrityURL = new ArrayList<>();
int chosenCeleb = 0;
ImageView celebrityImage;
int locationAnswer = 0;
//random answers


ArrayList<String> answers = new ArrayList<>();
//random buttons reference
Button button01;
Button button02;
Button button03;
Button button04;


ArrayList<String> names = new ArrayList<>();

public void selectCeleb(View view) {

    if (view.getTag().toString().equals(Integer.toString(locationAnswer))) {
        Toast.makeText(getApplicationContext(), "CORRECT ", Toast.LENGTH_LONG).show();



    } else {
        Toast.makeText(getApplicationContext(), "WRONG, IT WAS: " + names.get(chosenCeleb), Toast.LENGTH_SHORT).show();



    }

    randomCelebrity();
}

public class imagesGet extends AsyncTask<String, Void, Bitmap> {

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

        try {
            URL imagesURL = new URL(params[0]);
            HttpURLConnection connection = (HttpURLConnection)   imagesURL.openConnection();
            connection.connect();
            InputStream inputStream = connection.getInputStream();
            Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
            return bitmap;

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

        return null;
    }
}


public class getData extends AsyncTask<String, Void, String> {

    @Override
    protected String doInBackground(String... urls) {

        String result = "";
        URL url;
        HttpURLConnection connection = null;
        try {
            url = new URL(urls[0]);
            connection = (HttpURLConnection) url.openConnection();
            InputStream inputStream = connection.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
            int data = inputStreamReader.read();
            while (data != -1) {
                char current = (char) data;
                result += current;
                data = inputStreamReader.read();
            }
            return result;
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }


        return null;
    }
}


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    celebrityImage = (ImageView) findViewById(R.id.celebrityID);
    button01 = (Button) findViewById(R.id.celebrity01);
    button02 = (Button) findViewById(R.id.celebrity02);
    button03 = (Button) findViewById(R.id.celebrity03);
    button04 = (Button) findViewById(R.id.celebrity04);

    getData task = new getData();
    String resultData = null;
    try {
        try {
            resultData = task.execute("http://www.posh24.se/kandisar").get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        String[] spResult = resultData.split("<div class\"sidebarContainer\">");

        //images
        Pattern pattern = Pattern.compile("img src=\"(.*?)\"");
        Matcher matcher = pattern.matcher(spResult[0]);
        while (matcher.find()) {
            celebrityURL.add(matcher.group(1));
        }

        //names of the celebrities
        pattern = Pattern.compile("alt=\"(.*?)\"");
        matcher = pattern.matcher(spResult[0]);
        while (matcher.find()) {
            names.add(matcher.group(1));
        }


    }  catch (ExecutionException e) {
        e.printStackTrace();
    }
    randomCelebrity();
}

public void randomCelebrity() {
    //random  celebrity
    Random random = new Random();
    chosenCeleb = random.nextInt
            //between zero and the size of celebURL
                    (celebrityURL.size());

    //update imageView with new celebrity image
    imagesGet imagesGet = new imagesGet();
    Bitmap celebBitmap;
    try {
        celebBitmap = imagesGet.execute(celebrityURL.get(chosenCeleb)).get();
        celebrityImage.setImageBitmap(celebBitmap);
        int incorrectLocation;
        locationAnswer = random.nextInt(4);


        for (int i = 0; i < answers.size(); i++) {
            if (i == locationAnswer) {
                //update answers
                answers.get(chosenCeleb);

            } else {
                //create random celebrity from celebs urls
                incorrectLocation = random.nextInt(celebrityURL.size());

                //avoid getting the correct and wrong answer in same location
                //generate random answer if this condition is met
                while (incorrectLocation == chosenCeleb) {
                    incorrectLocation = random.nextInt(celebrityURL.size());
                }

                //assign wrong location answer in answers array
                answers.get(names.indexOf(incorrectLocation));
            }
        }


        button01.setText(answers.get(0));
        button02.setText(answers.get(1));
        button03.setText(answers.get(2));
        button04.setText(answers.get(3));
    } catch (ExecutionException e) {
        e.printStackTrace();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }

  }
  }

I divide the code so you can see it better. I am not idea how to fix this, but i know it is something with the ArrayList answers thing. I am trying to make an app that will random take html data and display it in android app. I am making an app to ques the celebrity name.

我将代码分开,以便您可以更好地看到它。我不知道如何解决这个问题,但我知道它与 ArrayList 答案有关。我正在尝试制作一个应用程序,它会随机获取 html 数据并将其显示在 android 应用程序中。我正在制作一个应用程序来查询名人的名字。

Edit: Sorry i forgot to include the error

编辑:对不起,我忘了包括错误

FATAL EXCEPTION: main
Process: com.stringmanipulation.stringmanipulation, PID: 24397
                                                 java.lang.IllegalStateException: Could not execute method for android:onClick
                                                   at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:293)
                                                   at android.view.View.performClick(View.java:5610)
                                                   at android.view.View$PerformClick.run(View.java:22265)
                                                   at android.os.Handler.handleCallback(Handler.java:751)
                                                   at android.os.Handler.dispatchMessage(Handler.java:95)
                                                   at android.os.Looper.loop(Looper.java:154)
                                                   at android.app.ActivityThread.main(ActivityThread.java:6077)
                                                   at java.lang.reflect.Method.invoke(Native Method)
                                                   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
                                                   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
                                                Caused by: java.lang.reflect.InvocationTargetException
                                                   at java.lang.reflect.Method.invoke(Native Method)
                                                   at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
                                                   at android.view.View.performClick(View.java:5610)?
                                                   at android.view.View$PerformClick.run(View.java:22265)?
                                                   at android.os.Handler.handleCallback(Handler.java:751)?
                                                   at android.os.Handler.dispatchMessage(Handler.java:95)?
                                                   at android.os.Looper.loop(Looper.java:154)?
                                                   at android.app.ActivityThread.main(ActivityThread.java:6077)?
                                                   at java.lang.reflect.Method.invoke(Native Method)?
                                                   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)?
                                                   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)?
                                                Caused by: java.lang.IndexOutOfBoundsException: Index: 103, Size: 100
                                                   at java.util.ArrayList.get(ArrayList.java:411)
                                                   at com.stringmanipulation.stringmanipulation.MainActivity.randomCelebrity(MainActivity.java:183)
                                                   at com.stringmanipulation.stringmanipulation.MainActivity.selectCeleb(MainActivity.java:53)
                                                   at java.lang.reflect.Method.invoke(Native Method)?
                                                   at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)?
                                                   at android.view.View.performClick(View.java:5610)?
                                                   at android.view.View$PerformClick.run(View.java:22265)?
                                                   at android.os.Handler.handleCallback(Handler.java:751)?
                                                   at android.os.Handler.dispatchMessage(Handler.java:95)?
                                                   at android.os.Looper.loop(Looper.java:154)?

回答by Zoe

Until you highlight what line causes the problem, I will not be able to help you solve it accurately

除非您突出显示是哪条线导致问题,否则我将无法帮您准确解决



IndexOutOfBoundsException is an exception thrown when you try to access an array and request an index that is too high. Example:(this goes for ArrayList and other types of array)

IndexOutOfBoundsException 是当您尝试访问数组并请求太高的索引时抛出的异常。示例:(这适用于 ArrayList 和其他类型的数组)

ArrayList<Integer> ex = new ArrayList<>();
int exceptionThrownHere = ex.get(0);

The exception is thrown when you try to get an object from the list whose index is out of bounds. Another example:

当您尝试从索引超出范围的列表中获取对象时,将引发异常。另一个例子:

int[] ex = new int[10];
//initialize for this example to be valid
int exceptionThrownHere = ex[10];

The max index in this case is 9(0-9) and in the event you try to get 10 or more, you get the exception.

在这种情况下,最大索引为 9(0-9),如果您尝试获得 10 或更多,则会出现异常。

The solution:(need the line where the exception is thrown for accurate answer)

解决办法:(需要抛出异常的那一行才能准确回答)

Make sure you don't try to get an object whose index is bigger than the amount of objects in the list. Another solution is to check how many objects are in the ArrayList(using .size()) and make sure you aren't trying to access an index that is bigger than the amount of objects in the list.

确保您不要尝试获取索引大于列表中对象数量的对象。另一种解决方案是检查 ArrayList 中有多少对象(使用.size())并确保您没有尝试访问大于列表中对象数量的索引。

From analyzing your code, I see(assuming all the code is in the question) that you never add anything to the array "answers" - thus there are no objects in the list and it causes the exception. Make sure to add objects to the list by:

通过分析您的代码,我看到(假设所有代码都在问题中)您从不向数组“答案”中添加任何内容 - 因此列表中没有对象并导致异常。确保通过以下方式将对象添加到列表中:

answers.add("whatever string you need here");

Also see

另见

Java Documentation - IndexOutOfBoundsException

Java 文档 - IndexOutOfBoundsException

Java Arraylist got java.lang.IndexOutOfBoundsException?

Java Arraylist 得到 java.lang.IndexOutOfBoundsException?