1 package org.robolectric.shadows;
2 
3 import android.location.Address;
4 import android.location.Geocoder;
5 import com.google.common.base.Preconditions;
6 import java.io.IOException;
7 import java.util.ArrayList;
8 import java.util.List;
9 import org.robolectric.annotation.Implementation;
10 import org.robolectric.annotation.Implements;
11 import org.robolectric.annotation.Resetter;
12 
13 @Implements(Geocoder.class)
14 public final class ShadowGeocoder {
15 
16   private static boolean isPresent = true;
17   private List<Address> fromLocation = new ArrayList<>();
18 
19   /** @return `true` by default, or the value specified via {@link #setIsPresent(boolean)} */
20   @Implementation
isPresent()21   protected static boolean isPresent() {
22     return isPresent;
23   }
24 
25   /**
26    * Returns an empty list by default, or the last value set by {@link #setFromLocation(List)}
27    *
28    * `latitude` and `longitude` are ignored by this implementation, except to check that they are in
29    * appropriate bounds. `maxResults` determines the
30    * maximum number of addresses to return.
31    */
32   @Implementation
getFromLocation(double latitude, double longitude, int maxResults)33   protected List<Address> getFromLocation(double latitude, double longitude, int maxResults)
34       throws IOException {
35     Preconditions.checkArgument(
36         -90 <= latitude && latitude <= 90, "Latitude must be between -90 and 90, got %s", latitude);
37     Preconditions.checkArgument(
38         -180 <= longitude && longitude <= 180,
39         "Longitude must be between -180 and 180, got %s",
40         longitude);
41     return fromLocation.subList(0, Math.min(maxResults, fromLocation.size()));
42   }
43 
44   /**
45    * Sets the value to be returned by {@link Geocoder#isPresent()}.
46    *
47    * This value is reset to `true` for each test.
48    */
setIsPresent(boolean value)49   public static void setIsPresent(boolean value) {
50     isPresent = value;
51   }
52 
53   /** Sets the value to be returned by {@link Geocoder#getFromLocation(double, double, int)}. */
setFromLocation(List<Address> list)54   public void setFromLocation(List<Address> list) {
55     fromLocation = list;
56   }
57 
58   @Resetter
reset()59   public static void reset() {
60     isPresent = true;
61   }
62 }
63