我有一个 AsyncTask 子类的活动。执行异步任务后,我会丢失所有变量。我在调试模式下单步执行我的代码。一旦“MyAsync().execute()”完成,“formatedURL”变量(以及所有其他变量)就没有值了。在此之前,它们具有正确的值。然后,由于某种奇怪的原因,他们失去了价值观。我是在犯一个简单的 OO 错误,还是垃圾收集在做我不知道的事情。
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:看起来它正在尝试在 doinbackground() 方法中多次运行“super.onCreate(Bundle savedInstanceState)”
Edit2:如果我将值设为静态,它们就不会丢失。很奇怪,即使是在异步任务中分配的变量“jobject”也不会接受分配,除非它是一个静态变量......从来没有见过这样的事情