0
其實當我從我的MainActivity調用異步類我得到錯誤(「不是封閉類」),儘可能努力,但無法總之出這個問題是不是在Android中的封閉類,而我呼叫異步類
MainActivity代碼:
Button listview=(Button)findViewById(R.id.inListView);
listview.setOnClickListener(new View.OnClickListener() {
String Restaurant = "restaurant";
@Override
public void onClick(View v) {
Log.d("onClick", "Button is Clicked");
String url = getUrl(latitude, longitude, Restaurant);
Object[] DataTransfer = new Object[2];
DataTransfer[0] = mMap;
DataTransfer[1] = url;
Log.d("onClick", url);
listviewActivity.GetNearbyPlaceData getNearbyPlacesListdata = new listviewActivity.GetNearbyPlaceData();
getNearbyPlacesListdata.execute(DataTransfer);
Toast.makeText(MapsActivity.this,"Nearby Restaurants", Toast.LENGTH_LONG).show();
}
});
的AsyncTask代碼:
public class listviewActivity extends AppCompatActivity {
static ArrayList<HashMap<String, String>> placesListItems = new ArrayList<HashMap<String,String>>();
// KEY Strings
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_listview);
Intent intent = getIntent();
// Getting listview
lv = (ListView) findViewById(R.id.list);
}
private void ShowNearbyPlaces(List<HashMap<String, String>> nearbyPlacesList) {
placesListItems.add((HashMap<String, String>) nearbyPlacesList);
// list adapter
ListAdapter adapter = new SimpleAdapter(listviewActivity.this, placesListItems,
R.layout.list_item,
new String[] { KEY_REFERENCE, KEY_NAME}, new int[] {
R.id.reference, R.id.name });
// Adding data into listview
lv.setAdapter(adapter);
}
public class GetNearbyPlaceData extends AsyncTask<Object, String, String> {
private GoogleMap mMap;
private String url;
private String googlePlacesData;
@Override
protected String doInBackground(Object... params) {
try {
Log.d("GetNearbyPlacesData", "doInBackground entered");
mMap = (GoogleMap) params[0];
url = (String) params[1];
DownloadUrl downloadUrl = new DownloadUrl();
googlePlacesData = downloadUrl.readUrl(url);
Log.d("GooglePlacesReadTask", "doInBackground Exit");
} catch (Exception e) {
Log.d("GooglePlacesReadTask", e.toString());
}
return googlePlacesData;
}
@Override
protected void onPostExecute(String result) {
Log.d("GooglePlacesReadTask", "onPostExecute Entered");
List<HashMap<String, String>> nearbyPlacesList = null;
DataParser dataParser = new DataParser();
nearbyPlacesList = dataParser.parse(result);
ShowNearbyPlaces(nearbyPlacesList);
Log.d("GooglePlacesReadTask", "onPostExecute Exit");
}
}
}
您需要使'GetNearbyPlaceData'靜態才能夠像那樣訪問。 – Shaishav
是的,但新問題出現像** ShowNearbyPlaces **需要是靜態的,然後在Activity上下文錯誤顯示**不能從靜態上下文引用** – techDigi
當然...這就是爲什麼我沒有發佈它作爲答案!你的代碼需要認真的重構......你爲什麼要從另一個活動(通過'AsyncTask')調用一個實例方法'private void ShowNearbyPlaces()',爲什麼要將整個地圖對象傳遞給另一個活動的內部類?也許,使'AsyncTask'成爲它自己的類(一個輔助類)。 – Shaishav