简体   繁体   中英

Issue accessing a variable in a Java class

I am trying to access the variable ArrayofTaxiDrivers in the class DownloadTask from the onCreate method of my activity file. However the variable is blank when accessed this way. The content does show when accessed from within the onPostExecute method of DownloadTask though.

Any help is greatly appreciated!

public class DownloadTask extends AsyncTask<String,Void,String> {

        ArrayList<TaxiDriver> ArrayofTaxiDrivers = new ArrayList<TaxiDriver>();

        @Override
        protected String doInBackground(String... urls) {
          String result = "";
          URL url;
          HttpURLConnection urlConnection = null;

          try {

            url = new URL(urls[0]);
            urlConnection = (HttpURLConnection) url.openConnection();
            InputStream in = urlConnection.getInputStream();
            InputStreamReader reader = new InputStreamReader(in);
            int data = reader.read();

            while (data != -1) {
                char current = (char) data;
                result += current;
                data = reader.read();
            }

            return result;

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
      }
        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            try {
                JSONObject jsonObject = new JSONObject(s);
                JSONArray items = jsonObject.getJSONArray("items");
                DownloadTask task = new DownloadTask();
                for(int i=0; i<items.length(); i++) {
                    JSONObject itemsObject = items.getJSONObject(i);
                    JSONObject fields = itemsObject.getJSONObject("fields");

                    task.addTaxiDriver(new TaxiDriver(fields.getString("name"), fields.getString("contact")));(asList(fields.getString("name"), fields.getString("contact"))));
                }
                Log.i("info",task.ArrayofTaxiDrivers.toString());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

}

protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_taxi_main);

        DownloadTask task = new DownloadTask();
        task.execute("https://test.com/json");

        Log.i("info",task.ArrayofTaxiDrivers.toString());
}

When you call task.execute("https://test.com/json"); the task will be executed based on its priority. For this reason the onPostExecute will be called after some time and probably after the onCreate

Log.i("info",task.ArrayofTaxiDrivers.toString());

I suggest you to think that "execute" is an instruction that exits immediatly and only after a while it will be executed.

I am trying to access the variable ArrayofTaxiDrivers in the class DownloadTask from the onCreate method of my Activity .

That is because when you created DownloadTask , the List ArryofTaxiDrivers is initialized and at that time the size of the List is zero.

If you have the data in the onPostExecute() method, that means it was probably added by AsyncTask 's doInBackground() method. Could be somewhere else entirely depending on your code.

Now the AsyncTask works asynchronously: it means that while it has been kicked to start executing, it doesn't start right away. However it will eventually start executing.

So when you access the list in onCreate() of the Activity , the list doesn't have any data because you haven't added to it.

What you should do

Instead implement an interface / callback to notify the Activity that the data is loaded and ready to be used. This callback can come from onPostExecute() .

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