2222import android .widget .AdapterView ;
2323import android .widget .GridView ;
2424
25+ import com .google .gson .Gson ;
2526import com .google .gson .JsonArray ;
2627import com .google .gson .JsonElement ;
2728import com .google .gson .JsonParser ;
29+ import com .google .gson .reflect .TypeToken ;
2830
2931import java .io .IOException ;
3032import java .io .InputStream ;
3133import java .io .InputStreamReader ;
3234import java .util .ArrayList ;
35+ import java .util .Arrays ;
36+ import java .util .Collection ;
3337import java .util .List ;
3438
3539import io .realm .Realm ;
@@ -84,8 +88,6 @@ protected void onDestroy() {
8488 }
8589
8690 private List <City > loadCities () {
87- List <City > items = new ArrayList <City >();
88-
8991 // In this case we're loading from local assets.
9092 // NOTE: could alternatively easily load from network
9193 InputStream stream = null ;
@@ -95,23 +97,20 @@ private List<City> loadCities() {
9597 return null ;
9698 }
9799
98- JsonParser parser = new JsonParser ();
99- JsonArray jsonArray = parser .parse (new InputStreamReader (stream )).getAsJsonArray ();
100+ // GSON can parse the data.
101+ // Note there is a bug in GSON 2.3.1 that can cause it to StackOverflow in some cases.
102+ // Downgrading to GSON 1.7.1 usually fixes this.
103+ // See more here: https://code.google.com/p/google-gson/issues/detail?id=440
104+ JsonArray json = new JsonParser ().parse (new InputStreamReader (stream )).getAsJsonArray ();
105+ List <City > cities = new Gson ().fromJson (json .toString (), new TypeToken <List <City >>(){}.getType ());
100106
101107 // Open a transaction to store items into the realm
108+ // Use copyToRealm() to convert the objects into proper RealmObjects managed by Realm.
102109 realm .beginTransaction ();
103- for (JsonElement e : jsonArray ) {
104- // Create a realm capable object
105- City realmCity = realm .createObject (City .class );
106- realmCity .setName (e .getAsJsonObject ().get ("name" ).getAsString ());
107- realmCity .setVotes (e .getAsJsonObject ().get ("votes" ).getAsInt ());
108- // Minor optimization to keep the new cities in a list
109- // so it doesn't have to be reloaded the first time
110- items .add (realmCity );
111- }
110+ Collection <City > realmCities = realm .copyToRealm (cities );
112111 realm .commitTransaction ();
113112
114- return items ;
113+ return new ArrayList < City >( realmCities ) ;
115114 }
116115
117116 public void updateCities () {
0 commit comments