Asynctask期间的Android Indexoutofbounds Exception

时间:2012-11-26 09:37:56

标签: android android-asynctask media-player indexoutofboundsexception

我无法理解为什么在我的音乐游戏中复制10首歌曲之一时会收到IndexOutOfBound异常。 我认为即使使用等待计算完成的asynctask.get(),他也会以10首歌曲信息(dieciCanzoni)跳过填充列表。

你能帮我吗?

谢谢!

logcat的:

11-26 10:29:49.441: E/AndroidRuntime(7509): FATAL EXCEPTION: main
11-26 10:29:49.441: E/AndroidRuntime(7509): java.lang.IndexOutOfBoundsException: Invalid index 1, size is 1
11-26 10:29:49.441: E/AndroidRuntime(7509):     at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:251)
11-26 10:29:49.441: E/AndroidRuntime(7509):     at java.util.ArrayList.get(ArrayList.java:304)
11-26 10:29:49.441: E/AndroidRuntime(7509):     at com.guessthesetunes.Canzone.onCompletion(Canzone.java:539)
11-26 10:29:49.441: E/AndroidRuntime(7509):     at android.media.MediaPlayer$EventHandler.handleMessage(MediaPlayer.java:1528)
11-26 10:29:49.441: E/AndroidRuntime(7509):     at android.os.Handler.dispatchMessage(Handler.java:99)
11-26 10:29:49.441: E/AndroidRuntime(7509):     at android.os.Looper.loop(Looper.java:137)
11-26 10:29:49.441: E/AndroidRuntime(7509):     at android.app.ActivityThread.main(ActivityThread.java:4575)
11-26 10:29:49.441: E/AndroidRuntime(7509):     at java.lang.reflect.Method.invokeNative(Native Method)
11-26 10:29:49.441: E/AndroidRuntime(7509):     at java.lang.reflect.Method.invoke(Method.java:511)
11-26 10:29:49.441: E/AndroidRuntime(7509):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
11-26 10:29:49.441: E/AndroidRuntime(7509):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:556)
11-26 10:29:49.441: E/AndroidRuntime(7509):     at dalvik.system.NativeStart.main(Native Method)

我在这一行收到错误,该错误调用了一个初始化媒体播放器的方法:             PlayStream(dieciCanzoni.get(ⅰ)获得(0));

我正在使用的AsyncTask的代码:

class Json extends AsyncTask<String, String, String>
{
List<String> canzoni = new ArrayList<String>(5);
ProgressDialog pDialog;
int[] arrayGenere;
Context context;

public Json(int[] arrayGenere,Context context) 
{
    this.arrayGenere = arrayGenere;
    this.context = context;
}

@Override
protected void onPreExecute()
{
    super.onPreExecute();
    pDialog = new ProgressDialog(context);
    pDialog.setMessage("Preparazione Round...");
    pDialog.setIndeterminate(false);
    pDialog.setCancelable(false);
    pDialog.show();
}

protected String doInBackground(String... params) 
{
    try
    {       
        int randomLookupId;
        JSONObject obj;                         
        JSONArray jsonArray;    

        for(int i = 0; i < 10; i++)
        {
            canzoni = new ArrayList<String>();

            obj = getJSONObject(scegliClassifica(arrayGenere));
            jsonArray = obj.getJSONArray("resultIds");

            randomLookupId = new Random().nextInt(jsonArray.length());  

            JSONObject finalObj = getJSONObject("http://itunes.apple.com/lookup?id="+jsonArray.getString(randomLookupId)); 
            JSONArray finalJsonArray = finalObj.getJSONArray("results");    

            JSONObject returnObj = finalJsonArray.getJSONObject(0);

            canzoni.add(returnObj.getString("previewUrl"));
            canzoni.add(returnObj.getString("artistName"));
            canzoni.add(returnObj.getString("trackName"));
            canzoni.add(returnObj.getString("artistViewUrl"));
            canzoni.add(returnObj.getString("artworkUrl100"));

            Canzone.dieciCanzoni.add(i, new ArrayList<String>(canzoni));
        }
    }   
    catch (JSONException ignored)
    {
        ignored.getCause();
    }
    catch (MalformedURLException e) 
    {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    catch (IOException e) 
    {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return null;
}

private String scegliClassifica(int[] arrayGenere)
{
    int randomArrayPosition = new Random().nextInt(arrayGenere.length);
    return "http://itunes.apple.com/WebObjects/MZStoreServices.woa/ws/charts?cc=us&g="+arrayGenere[randomArrayPosition]+"&name=Songs&limit=300";
}

@Override
protected void onPostExecute(String stringa)
{
    pDialog.dismiss();
}

JSONObject getJSONObject(String url) throws IOException, MalformedURLException, JSONException
{

    HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();

    InputStream in = conn.getInputStream();

    try
    {
        StringBuilder sb = new StringBuilder();
        BufferedReader r = new BufferedReader(new InputStreamReader(new DoneHandlerInputStream(in)));
        for (String line = r.readLine(); line != null; line = r.readLine())
        {
            sb.append(line);
        }
        return new JSONObject(sb.toString());
    }
    finally
    {
        in.close();
    }
}
}

这是对Asynctask的调用:

try {
        new Json(arrayGenere,Canzone.this).execute().get(15000,TimeUnit.MILLISECONDS);
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ExecutionException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (TimeoutException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

编辑:

将JsonArray的大小更改为JsonArray.lenght() - 1后,它也不起作用! 例如,在一个案例中,Json类只填充了List的2个元素,但我无法理解为什么!

你能帮帮我吗? 感谢

2 个答案:

答案 0 :(得分:1)

请记住,数组的第一个元素是索引0.因此,长度将比最高索引高1,因此在使用之前需要从randomLookupId中减去1。

(考虑一个长度为1的数组,你应该总是随机选择索引0)

答案 1 :(得分:0)

在你身上doInBackground方法你怎么知道自己属于“合法规模”?

您的整个方法建立在错误/硬编码的假设上......