更新了之前的问题:我通过 HashMap 填充了一个数组,我使用 Asynctask 进行 http 请求,并在填充数组后将该数组放入对话框中。当我第一次运行我的应用程序时,它给了我一个空对话框并且没有给出任何错误,但是当我重新运行我的应用程序时,它完美地显示了对话框中的所有数组元素。原因是什么?
//JsonResponse Inner Class in main class
private class JsonResponse extends AsyncTask<String, Void, String>
{
String response = "";
private ArrayList<HashMap<String, String>> prServices_resultList =
new ArrayList<HashMap<String, String>>();
protected void onPostExecute(String result)
{
if(response.equalsIgnoreCase("Success"))
{
ResultList_List = prServices_resultList;
int s=0;
for (HashMap<String, String> hashServices : prServices_resultList)
{
Db_Services[s] = hashServices.get(android_S_CName);
Db_ServicesID[s] = hashServices.get(android_S_ID);
s++;
}
}
}
protected String doInBackground(final String... args)
{
JSONParser jParser = new JSONParser();
JSONArray jArrayServices = jParser.getJSONFromUrl(url_Services);
try
{
for (int i = 0; i < jArrayServices.length(); i++)
{
JSONObject jsonElements = jArrayServices.getJSONObject(i);
String S_id = jsonElements.getString(android_S_ID);
String S_name = jsonElements.getString(android_S_NAME);
HashMap<String, String> hashServices = new HashMap<String, String>();
// adding each child node to HashMap key
hashServices.put(android_S_ID, S_id);
hashServices.put(android_S_NAME, S_name);
// adding HashList to ArrayList
prServices_resultList.add(hashServices);
}
response = "Success";
}
catch(JSONException e)
{
e.printStackTrace();
}
return response;
}
}
在我的主类中有一个按钮,当我按下时我执行 AsyncTask:
new JsonResponse().execute;
在 onCreate 上面的主类中我声明如下:
static ArrayList<HashMap<String, String>> ResultList_Services =
new ArrayList<HashMap<String, String>>();
String[] Db_Services = new String[ResultList_Services.size()];
String[] Db_ServicesID = new String[ResultList_Services.size()];
最佳答案
您正在此处创建一个空 map :
ResultList_Services = new ArrayList<HashMap<String, String>>();
然后尝试用空映射的大小初始化两个数组 - 为零。
// ResultList_Services.size() will be zero
String[] Db_Services = new String[ResultList_Services.size()];
String[] Db_ServicesID = new String[ResultList_Services.size()];
因此,当您尝试添加到这些数组时,它将抛出 OutOfBoundsException
您可以将这些数组放入列表中,然后您可以根据需要动态添加元素,而无需指定开始时的大小。如果您需要一个数组(用于其他方法),您可以使用 List#toArray()
从列表中获取数组。
根据您的评论
您可以创建临时数组,向其中添加所有元素,然后将其分配给其他数组,例如
protected void onPostExecute(String result)
{
if(response.equalsIgnoreCase("Success"))
{
ResultList_List = prServices_resultList;
String[] tmp_dbServ = new String[prServices_resultList.size()];
String[] tmp_dbServID = new String[prServices_resultList.size()];
int s=0;
for (HashMap<String, String> hashServices : prServices_resultList)
{
tmp_dbServ[s] = hashServices.get(android_S_CName);
tmp_dbServID[s] = hashServices.get(android_S_ID);
s++;
}
Db_Services = tmp_dbServ;
Db_ServicesID = tmp_dbServID;
}
}
关于java - ArrayException越界,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21029246/