我在使用以下代码时遇到问题。似乎有些事情我不太明白。我初始化类变量请求数组。然后我在getHelpRequests(( -function中添加一些数据。但是,当我尝试从另一个函数(onMapReady(访问数据时,数组是空的。这是为什么呢?
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
private List<HelpRequest> requestArray = new ArrayList<HelpRequest>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
private void getHelpRequests() {
// Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(this);
String url ="***/gethelprequests.php";
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try {
JSONArray jsonArray = new JSONArray(response);
for(int i=0 ; i<jsonArray.length() ; i++) {
HelpRequest rq = new HelpRequest();
rq.setLogo(Integer.parseInt(jsonArray.getJSONObject(i).get("logo").toString()));
rq.setUsername(jsonArray.getJSONObject(i).get("username").toString());
rq.setAge(Integer.parseInt(jsonArray.getJSONObject(i).get("age").toString()));
rq.setReputation(Integer.parseInt(jsonArray.getJSONObject(i).get("age").toString()));
rq.setDescription(jsonArray.getJSONObject(i).get("description").toString());
rq.setLat(Float.valueOf(jsonArray.getJSONObject(i).get("lat").toString()));
rq.setLng(Float.valueOf(jsonArray.getJSONObject(i).get("lng").toString()));
requestArray.add(rq);
/*Log.d("Person " + i, " logo: " + rq.getLogo());
Log.d("Person " + i, " username: " + rq.getUsername());
Log.d("Person " + i, " age: " + rq.getAge());
Log.d("Person " + i, " reputation: " + rq.getReputation());
Log.d("Person " + i, " description: " + rq.getDescription());
Log.d("Person " + i, " latitude: " + rq.getLat());
Log.d("Person " + i, " longitude: " + rq.getLng());*/
}
} catch (final JSONException e) {
Log.e("ERROR: ", "Json parsing error: " + e.getMessage());
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.d("ERROR:", error.getMessage());
}
});
// Add the request to the RequestQueue.
queue.add(stringRequest);
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
getHelpRequests();
Log.d("EMPTY:", String.valueOf(requestArray.size()));
for(int i=0 ; i<requestArray.size() ; i++) {
Log.d("REQ:", requestArray.get(i).getUsername());
}
LatLng stpetersburg = new LatLng(27.88, -82.83);
Marker burg = mMap.addMarker(new MarkerOptions().position(stpetersburg).title("Marker in St. Petersburg"));
burg.showInfoWindow();
mMap.moveCamera(CameraUpdateFactory.newLatLng(stpetersburg));
}
}
编辑:问题似乎与异步等有关...谁能提示我解决这个问题的正确方向,并获得这方面的知识,以便我下次遇到此类问题时了解问题?
首先在你的类中创建一个带有接口的侦听器(或创建新的接口文件(:
public interface OnReceivedResponse{
void onSuccessResponse(List<HelpRequest> myArray);
}
将此侦听器添加到 getHelpRequests:
private void getHelpRequests(OnReceivedResponse mListener)
阵列准备就绪后,只需调用mListener.onSuccessResponse(requestArray)
现在,在调用 getHelRequest 时,创建新的侦听器:
getHelpRequests(new OnReceivedResponse(){
@Override
public void onSuccessResponse(List<HelpRequest> myArray){
//Do whatever you want with myArray received
}
});
这里有完整的示例代码:
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
private List<HelpRequest> requestArray = new ArrayList<HelpRequest>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager(OnReceivedResponse mListener)
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
private void getHelpRequests(OnReceivedResponse mListener) {
// Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(this);
String url ="***/gethelprequests.php";
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try {
JSONArray jsonArray = new JSONArray(response);
for(int i=0 ; i<jsonArray.length() ; i++) {
HelpRequest rq = new HelpRequest();
rq.setLogo(Integer.parseInt(jsonArray.getJSONObject(i).get("logo").toString()));
rq.setUsername(jsonArray.getJSONObject(i).get("username").toString());
rq.setAge(Integer.parseInt(jsonArray.getJSONObject(i).get("age").toString()));
rq.setReputation(Integer.parseInt(jsonArray.getJSONObject(i).get("age").toString()));
rq.setDescription(jsonArray.getJSONObject(i).get("description").toString());
rq.setLat(Float.valueOf(jsonArray.getJSONObject(i).get("lat").toString()));
rq.setLng(Float.valueOf(jsonArray.getJSONObject(i).get("lng").toString()));
requestArray.add(rq);
/*Log.d("Person " + i, " logo: " + rq.getLogo());
Log.d("Person " + i, " username: " + rq.getUsername());
Log.d("Person " + i, " age: " + rq.getAge());
Log.d("Person " + i, " reputation: " + rq.getReputation());
Log.d("Person " + i, " description: " + rq.getDescription());
Log.d("Person " + i, " latitude: " + rq.getLat());
Log.d("Person " + i, " longitude: " + rq.getLng());*/
}
mListener.onSuccessResponse(requestArray)
} catch (final JSONException e) {
Log.e("ERROR: ", "Json parsing error: " + e.getMessage());
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.d("ERROR:", error.getMessage());
}
});
// Add the request to the RequestQueue.
queue.add(stringRequest);
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
getHelpRequests(new OnReceivedResponse(){
@Override
public void onSuccessResponse(List<HelpRequest> myArray){
Log.d("EMPTY:", String.valueOf(myArray.size()));
for(int i=0 ; i<myArray.size() ; i++) {
Log.d("REQ:", myArray.get(i).getUsername());
}
LatLng stpetersburg = new LatLng(27.88, -82.83);
Marker burg = mMap.addMarker(new MarkerOptions().position(stpetersburg).title("Marker in St. Petersburg"));
burg.showInfoWindow();
mMap.moveCamera(CameraUpdateFactory.newLatLng(stpetersburg));
}
});
}
public interface OnReceivedResponse{
void onSuccessResponse(List<HelpRequest> myArray);
}