2017-03-05 1 views
-3

Qu'est-ce que l'enfer est cette choseComment réparer java.lang.IndexOutOfBoundsException: Index: 0, Taille: 0 dans android? Je suis en train d'apprendre ArrayList

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(); 
    } 

    } 
    } 

Je divise le code afin que vous puissiez le voir mieux. Je ne sais pas comment résoudre ce problème, mais je sais que c'est quelque chose avec les réponses ArrayList. J'essaie de faire une application qui prendra au hasard les données html et l'afficher dans l'application android. Je fais une application pour interroger le nom de la célébrité.

Edit: Désolé j'ai oublié d'inclure l'erreur

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)  
+2

line_ _which est l'exception? –

+0

Copie possible de [Array index out of bound in C] (http://stackoverflow.com/questions/671703/array-index-out-of-bound-in-c) – Farid

+0

Pouvez-vous partager la trace et la marque de la pile? les lignes auxquelles il correspond? En général, vous avez une ArrayList vide (Size: 0) et vous essayez d'accéder au premier élément, qui n'existe pas. – Larce

Répondre

0

Jusqu'à ce que vous mettez en évidence ce ligne provoque le problème, je ne serai pas en mesure de vous aider à le résoudre avec précision


IndexOutOfBoundsException est un exception levée lorsque vous essayez d'accéder à un tableau et demandez un index trop élevé. Exemple: (cela vaut pour ArrayList et d'autres types de tableau)

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

L'exception est levée lorsque vous essayez d'obtenir un objet de la liste dont l'index est hors limites. Un autre exemple:

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

L'indice maximum dans ce cas est de 9 (0-9) et dans le cas où vous essayez d'obtenir 10 ou plus, vous obtenez l'exception.

La solution: (besoin de la ligne où l'exception est levée pour réponse précise)

Assurez-vous de ne pas essayer d'obtenir un objet dont l'index est plus grand que la quantité d'objets dans la liste. Une autre solution consiste à vérifier combien d'objets se trouvent dans ArrayList (en utilisant .size()) et assurez-vous que vous n'essayez pas d'accéder à un index plus grand que la quantité d'objets dans la liste. De l'analyse de votre code, je vois (en supposant que tout le code est dans la question) que vous n'ajoutez jamais rien au tableau "réponses" - donc il n'y a aucun objet dans la liste et il provoque l'exception. Assurez-vous d'ajouter des objets à la liste par:

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

Voir aussi

Java Documentation - IndexOutOfBoundsException

Java Arraylist got java.lang.IndexOutOfBoundsException?