Created
May 17, 2017 12:58
-
-
Save pteacher/03b0734d5d2aa33c3e2314edfa06982c to your computer and use it in GitHub Desktop.
Gson Example (JSON to Object)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
compile 'com.android.volley:volley:1.0.0' | |
compile 'com.google.code.gson:gson:2.2.4' | |
compile 'com.squareup.retrofit2:retrofit:2.3.0' | |
*/ | |
public void sendRequest(View view) { | |
RequestQueue queue = Volley.newRequestQueue(getApplicationContext()); | |
String url = "https://pteachertest.herokuapp.com/json/"; | |
final ListView listView = (ListView) findViewById(R.id.listView); | |
JsonArrayRequest request = new JsonArrayRequest(url, new Response.Listener<JSONArray>() { | |
@Override | |
public void onResponse(JSONArray jsonArray) { | |
try { | |
for (int i = 0; i < jsonArray.length(); i++) { | |
JSONObject jsonObject = (JSONObject) jsonArray.get(i); | |
Player player = gson.fromJson(jsonObject.toString(), Player.class); | |
players.add(player); | |
} | |
ArrayList<String> playerName = new ArrayList<>(); | |
for (int i = 0; i < players.size(); i++) { | |
if (players.get(i).name != null) | |
playerName.add(players.get(i).name); | |
} | |
ArrayAdapter<String> adapter = new ArrayAdapter<>(getApplicationContext(), | |
android.R.layout.simple_list_item_1, playerName); | |
listView.setAdapter(adapter); | |
} | |
catch (JSONException e) { | |
e.printStackTrace(); | |
} | |
} | |
}, new Response.ErrorListener() { | |
@Override | |
public void onErrorResponse(VolleyError volleyError) { | |
textView.setText(volleyError.getMessage()); | |
} | |
} | |
); | |
queue.add(request); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment