在Java类中,我在一个类中有三个List作为字段。 所以我相信我让全班同学都可以参加?和所有内部类?
然而,这不起作用: (例如,我只会在这里显示一个列表,而不是全部三个)
class Items extends ListActivity {
List<String> items = null; // field
Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// stuff
items = new ArrayList<String>();
new Task().execute();
Log.d("Size", String.valueOf(items.size()));
}
class Task extends AsyncTask<String, String, Void> {
// in this subclass, I parse items from JSON and add to List "items".
items = add(item);
}
退出任务后,我似乎丢失了列表中的项目。它记录“大小0”;如果我在任务中执行此操作,则会显示正确数量的项目。我在这里错过了一个关于List变量范围的基本观点吗?
编辑:下面是完整的任务类(稍微清理过来)
class Task extends AsyncTask<String, String, Void> {
private InputStream is = null;
private String result = "";
@Override
protected Void doInBackground(String... params) {
String url_select = "items.php";
param = new ArrayList<NameValuePair>();
param.add(new BasicNameValuePair("category", Category));
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url_select);
try {
httpPost.setEntity(new UrlEncodedFormEntity(param));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
// read content
is = httpEntity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
}
try {
BufferedReader br = new BufferedReader(
new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = "";
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
// TODO: handle exception
Log.e("log_tag", "Error converting result " + e.toString());
}
return null;
}
protected void onPostExecute(Void v) {
try {
JSONArray jArray = new JSONArray(result);
JSONObject json_data = null;
for (int i = 0; i < jArray.length(); i++) {
json_data = jArray.getJSONObject(i);
item = json_data.getString("item");
items.add(item);
Log.d("Items", item);
}
} catch (JSONException e1) {
Toast.makeText(getBaseContext(), "No items!",
Toast.LENGTH_SHORT).show();
} catch (ParseException e1) {
e1.printStackTrace();
}
}
}
答案 0 :(得分:3)
我不是Android开发人员但不是AsyncTask
类似新线程的东西?如果是,那么您只看到“尺寸0”,因为在Log.d("Size", String.valueOf(items.size()));
更新您的列表之前执行了new task().execute();
。
答案 1 :(得分:1)
您需要仔细阅读此tutorial
基本上,默认访问级别是package private
(我可能在描述上有误),但基本上它意味着只要你在同一个包中就可以看到该成员,但它不是子类可见。
尝试使用protected
访问级别