简体   繁体   中英

Scope of Variables in Java

In a Java Class, I have three List as fields in a class. 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"; 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?

EDIT: Below is the complete Task class (slightly cleaned up for posting)

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? If yes then you just see "size 0" because Log.d("Size", String.valueOf(items.size())); was executed before 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.

Try using the protected access level instead

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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