2017-07-12 17 views
0

次のコードに問題があります。私はかなり理解していないものがあるようです。私は、クラス変数requestArrayを初期化します。次に、getHelpRequests()関数内にデータを追加します。しかし、私が他の関数(onMapReady)からデータにアクセスしようとすると、配列は空です。どうしてこれなの?設定後の変数null(アンドロイド開発)

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


} 

}

EDITは:問題は、誰もがこの問題を修正し、これについての知識を得るために正しい方向に私をヒントでした...など非同期とは何かを持っていると思われるので、私は理解して問題は次回私はこの種の問題にぶつかる?

+1

あなたはそれが – Chol

+0

ありがとう充填した前のArrayListのvallueにアクセスしようとしているので、あなたは、非同期でgetHelpRequests()です。これを修正するために何をすべきか?あなたはこのような問題を防ぐために正しい方向に私をヒントしたり、...? – user3629146

+0

getHelpRequests()でレスポンスを受け取ったら、onMapReady(getHelpRequest()呼び出し後)のコードを置く必要があります。 – Chol

答えて

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); 
     } 
関連する問題