Google Places API循环无法限制结果,求获取前5条结果的解决方法
Fixing Google Places API to Return Only 5 Results
Hey there, let's sort out this issue with limiting your Places API results to 5. The problem with your counter approach might have been a missing break, or not handling the buffer correctly. Here are a couple of solid solutions:
Solution 1: Counter with Loop Break
Make sure you increment the counter inside the loop and break once it hits 5. Also, don't forget to release the buffer when you're done (critical for memory management):
result.setResultCallback(new ResultCallback<PlaceLikelihoodBuffer>() { @Override public void onResult(PlaceLikelihoodBuffer likelyPlaces) { int count = 0; try { for (PlaceLikelihood placeLikelihood : likelyPlaces) { if (count >= 5) { break; // Exit loop once we have 5 results } // Process your place here (e.g., get name, address) String placeName = placeLikelihood.getPlace().getName().toString(); Log.d("Places", "Place: " + placeName); count++; } } finally { likelyPlaces.release(); // Always release the buffer to avoid memory leaks } } });
Solution 2: Use Indexed Access to Limit Results Directly
A more concise way is to loop only through the first 5 items (or fewer if there aren't enough results available):
result.setResultCallback(new ResultCallback<PlaceLikelihoodBuffer>() { @Override public void onResult(PlaceLikelihoodBuffer likelyPlaces) { try { // Get the first 5 results (or all available if less than 5) int limit = Math.min(5, likelyPlaces.getCount()); for (int i = 0; i < limit; i++) { PlaceLikelihood placeLikelihood = likelyPlaces.get(i); // Process your place here String placeName = placeLikelihood.getPlace().getName().toString(); Log.d("Places", "Place: " + placeName); } } finally { likelyPlaces.release(); } } });
Why Your Initial Counter Might Have Failed
- You might have forgotten to add a
breakstatement once the counter reached 5, so the loop kept running through all results. - Or you didn't wrap the loop in a try-finally block to release the buffer, which could lead to unexpected behavior or memory leaks.
Either of the above solutions should work perfectly to limit your results to 5. Just pick the one that fits your code style better!
内容的提问来源于stack exchange,提问作者Gastón Saillén
相关产品推荐
相关产品推荐

