Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8742223
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 13, 20262026-06-13T11:27:41+00:00 2026-06-13T11:27:41+00:00

I have a an activity with AsyncTask sub-classed. I lose all my variables once

  • 0

I have a an activity with AsyncTask sub-classed. I lose all my variables once the async task is executed. I am stepping through my code in debug mode. As soon as “MyAsync().execute()” finishes the “formatedURL” variable (and all the others) have no values. before that, they have the correct values. Then, for some odd reason, they lose the values. Am i making a simple OO mistake or is garbage collection doing something i am not aware of.

public class NearbyList extends Activity {

    double lat;
    double lng;
    String restName;
    GPSHandling gps;
    String formatedURL;
    JSONObject jobject;
    ArrayList<HashMap<String, String>> listOfHM;
    ArrayList<String> listOfValues;
    String currentName;
    ListView lv;
    Context context;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.nearby_places_list);

        context = getApplicationContext();
        gps = new GPSHandling(this);
        lat = gps.getMyLatitude();
        lng = gps.getMyLongitude();
        restName ="";
        formatedURL = GooglePlacesStuff.placesURL(lat, lng, 16000, "food", restName, true);  //make a proper url. next step is to get a JSON object from this.


        new MyAsync().execute();// in order to run networking it must not be done in the UIthread. I use async task to take care of this in order to 
           //reduce the code of doing complex threading since this is a simple calculation
    }
        class MyAsync extends AsyncTask<Void, Integer, Boolean>{
            @Override
            protected Boolean doInBackground(Void... params) {
                try {
                    jobject = GooglePlacesStuff.getTheJSON(formatedURL);
                    listOfHM = JSONextractor.getJSONHMArrayL(jobject);
                    // iterate through and get the names of the nearby restaurants from the array of hasmap strings
                    for(int i =0 ; i < listOfHM.size() ;i++ ){
                        currentName = listOfHM.get(i).get(JSONextractor.TAG_NAME);
                        listOfValues.add(currentName);
                    }
                    return true;
                } catch (Exception e){
                    Log.e("Nearby List Activity", "exception", e);
                    return false;}
            }

            @Override
            protected void onPostExecute(Boolean result){
                super.onPostExecute(result);
                if (result){
                    ListAdapter adapter = new SimpleAdapter(context, listOfHM, R.layout.nearby_places_list, new String[]{JSONextractor.TAG_NAME,
                            JSONextractor.TAG_VICINITY, JSONextractor.TAG_GEO_LOC_LAT}, new int[]{ R.id.name, R.id.vicinity, R.id.phone});

                    // adding data to listview
                    lv.setAdapter(adapter);
                } else{
                    Toast.makeText(getApplicationContext(), "Need Internet & GPS access for this to work", Toast.LENGTH_LONG).show();
                }
                gps.stopUsingGPS();  // stop using the gps after i get the list to save on resource
            }
        }
}

Edit1:
looks like it is trying to run “super.onCreate(Bundle savedInstanceState)” multiple times in the doinbackground() method

Edit2: if i make the values static they don’t get lost. Its weird, even the variable “jobject” which is assigned inside the async task wont take an assignment unless its a static variable…. never seen anything like this

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-13T11:27:42+00:00Added an answer on June 13, 2026 at 11:27 am

    When you say they have no values, are you checking them inside the AsyncTask? If so, this might be the reason (from AsyncTask):

    Memory observability

    AsyncTask guarantees that all callback calls are synchronized in such a way that the following operations are safe without explicit synchronizations.

    • Set member fields in the constructor or onPreExecute(), and refer to them in doInBackground(Params…).
    • Set member fields in doInBackground(Params…), and refer to them in onProgressUpdate(Progress…) and onPostExecute(Result).

    Basically, you shouldn’t access your instance variables from doInBackground() because it’s not thread-safe. Like the function says, it runs in a separate (background) thread. You can work around it by making them static (which you tried) or synchronize them, but it’s probably better to use AsyncTask the way it’s intended.

    So I think you should do the following:

    1. Pass in formatedURL as a parameter to the AsyncTask

    2. return ArrayList<HashMap<String, String>> from doInBackground() (listOfHM)

    3. Use the passed in ArrayList<HashMap<String, String>> in onPostExecute()

    4. I would also additionally set the ListAdapter in onCreate, and just update the data backing the ListAdapter onPostExecute(). But I won’t discuss that here since it’s probably a separate question. This one is optional.

    Code:

    class MyAsync extends AsyncTask<String, Integer, ArrayList<HashMap<String, String>>> {
        @Override
        protected ArrayList<HashMap<String, String>> doInBackground(String... urls) {
            ArrayList<HashMap<String, String>> listOfHM = null;
            if (urls != null && urls.length > 0 && urls[0] != null) {
                String formattedUrl = urls[0];
                try {
                    JSONObject jobject = GooglePlacesStuff.getTheJSON(formattedURL);
                    listOfHM = JSONextractor.getJSONHMArrayL(jobject);
                } catch (Exception e) {
                    // log error
                }
            }
            return listOfHM;
        }
    
        @Override
        protected void onPostExecute(ArrayList<HashMap<String, String>> listOfHM){
            if (listOfHM != null && !listOfHM.isEmpty()) {
                // iterate through and get the names of the nearby restaurants from the array of hasmap strings
                for(int i =0 ; i < listOfHM.size() ;i++ ){
                    String currentName = listOfHM.get(i).get(JSONextractor.TAG_NAME);
                    listOfValues.add(currentName);
                }
                // do your adapter stuff
            }
            gps.stopUsingGPS();  // stop using the gps after i get the list to save on resource
        }
    }
    

    And in your onCreate() you would do

    new MyAsync(formattedUrl).execute();
    

    Hope it helps!

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have an application and every new created activity will start an async task
i bascially have an activity that calls an async task to set up the
I have an Activity that runs an AsyncTask on a TimerTask. While the task
I have an Activity class which has an attribute that references an AsyncTask instance
I have the following asynctask class which is not inside the activity. In the
I have some problem with Android AsyncTask. There is an Activity which contains some
An activity I have starts an AsyncTask. What is the best way of getting
I have a backgorund thread that extends AsyncTask and which I use in activity
I have an Activity Class with an inner protected class that extends AsyncTask. I
I have an activity, composed of an AsyncTask aiming to launch a request when

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.