我有一个AsyncTask子类的活动。一旦执行异步任务,我将失去所有的变量。我正在调试模式下遍历我的代码。只要“MyAsync()。execute()”完成“formaticURL”变量(以及所有其他变量)没有值。在此之前,他们有正确的价值观。然后,出于某种奇怪的原因,他们失去了价值。我是在做一个简单的面向对象程序错误还是在做垃圾收集,我不知道。执行Async Task任务后,变量会丢失数据
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()方法
EDIT2运行 “super.onCreate(包savedInstanceState)” 多次:如果我做的值静态他们不走开。它的奇怪,即使是异步任务内分配的变量“jobject”也不会采取任务,除非它的静态变量....从来没有见过类似的东西
没有“没有价值”的可能性。 'null'仍然是一个值。你有什么价值? –
它们是否具有您期望的onPostExecute结尾的值? – toadzky
@ webnetMobile:当我查看它们没有设置为null的变量时,它看起来好像没有任何价值。通常,当它们为空时,它们会说“null” @taodzky:在doInBackground()和onpostexecute期间或之后仍未分配。 () –