简体   繁体   English

Java中的变量范围

[英]Scope of Variables in Java

In a Java Class, I have three List as fields in a class. 在Java类中,我在一个类中具有三个List作为字段。 So I believe I made them available to the whole class? 所以我相信我让全班同学都可以使用它们? and all inner classes? 和所有内部阶级?

However, this does not work: (For the example, I will only show one list here, not all three) 但是,这不起作用:(例如,在此仅显示一个列表,而不是全部三个)

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

 }

Once I exit the task, I seem to lose the items in the List. 退出任务后,我似乎丢失了列表中的项目。 It Logs "size 0"; 记录“ size 0”; if I do it inside the task, it shows the proper amount of items. 如果我在任务中执行此操作,则会显示适当数量的项目。 Am I missing a very basic point about the scope of List variables here? 我是否在这里缺少有关List变量范围的基本要点?

EDIT: Below is the complete Task class (slightly cleaned up for posting) 编辑:下面是完整的Task类(稍作清理以进行发布)

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


    }
}

I am not Android developer but isn't AsyncTask something like new Thread? 我不是Android开发人员,但AsyncTask是否不是新线程之类的东西? If yes then you just see "size 0" because Log.d("Size", String.valueOf(items.size())); 如果是,那么您只会看到“ size 0”,因为Log.d("Size", String.valueOf(items.size())); was executed before new task().execute(); new task().execute();之前new task().execute(); updated your list. 更新了您的列表。

You'll want to read through this tutorial 您将要通读本教程

Basically, the default access level is package private (I could be wrong on the description), but basically it means that so long as you're in the same package you can see the member, but it is not visible to sub classes. 基本上,默认访问级别是package private (我在描述中可能是错误的),但是基本上,这意味着,只要您在同一程序包中,您就可以看到该成员,但对子类而言是不可见的。

Try using the protected access level instead 尝试改用protected访问级别

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM