更新:我通过HashMap填充数组,Iam使用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 onPreExecute()
{
}
protected void onPostExecute(String result)
{
if(response.equalsIgnoreCase("Success"))
{
ResultList_List = prServices_resultList;
int z=0;
for (HashMap<String, String> hashList : prServices_resultList)
{
Av_List[z] = hashList.get(android_Av_ID);
Av_Lat[z] = Double.parseDouble(hashList.get(android_Av_LAT));
Av_Lng[z] = Double.parseDouble(hashList.get(android_Av_LONG));
z++;
}
}
}
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;
}
}
在我按下按钮时的主课:
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()];
现在我收到一个错误:java.lang.ArrayIndexOutOfBoundsException:length = 0;索引= 0
答案 0 :(得分:0)
首先,将值添加到可从后台线程访问UI线程的静态字段ResultList_Services
是非常糟糕的做法。您应该将代码重写为线程安全的。有几个选项,一个是:
private class JsonResponse extends AsyncTask<String, Void, String> {
private ArrayList<HashMap<String, String>> resultList = new ArrayList<HashMap<String, String>>();
...
protected String doInBackground(final String... args)
{
...
// adding HashList to private JsonResponse's field
resultList.add(hashServices);
...
}
protected void onPostExecute(String result)
{
if (response.equalsIgnoreCase("Success"))
{
ResultList_Services = resultList;
//TODO: notify your Activity/Dialog on completion
}
}
}
关于您的问题 - 没有看到新记录的原因是您在ResultList中没有值时显示对话框。例如,您应该要求onPostExecute
显示它。
答案 1 :(得分:0)
你需要这样做 -
for (HashMap<String, String> hashServices : ResultList_Services)
{
Db_Services[s] = hashServices.get(android_S_CName);
Db_ServicesID[s] = hashServices.get(android_S_ID);
s++;
}
在asynctask的 onPostExecute()块中。