设置后变量null(android开发)

时间:2017-07-12 10:19:37

标签: android variables null

我在使用以下代码时出现问题。似乎有些事情我不太了解。我初始化类变量requestArray。然后我在getHelpRequests()函数中添加一些数据。但是,当我尝试从其他函数(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));


}

}

编辑:问题似乎与异步等有关...有人暗示我正确的方向来解决这个问题,并获得有关这方面的知识,所以我理解下一次碰到这种问题的问题问题

1 个答案:

答案 0 :(得分:2)

首先在类中创建一个带接口的侦听器(或创建新的接口文件):

public interface OnReceivedResponse{
            void onSuccessResponse(List<HelpRequest> myArray);
        }

将此侦听器添加到getHelpRequests:

private void getHelpRequests(OnReceivedResponse mListener)

当您的阵列准备就绪时,请拨打mListener.onSuccessResponse(requestArray)

现在,在调用getHelRequests时,创建新的侦听器:

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);
        }