Download JSON in an AsyncTask
You need to actually do a network operation in order to download the JSON response. Then, you need to parse it correctly.
Here is code that would download the JSON response and parse it, you need to iterate over each JSONObject in the JSONArray:
//@Override
protected List<DublinBusObject> doInBackground(String... params) {
String liveUpdateUrl = params[0];
List<DublinBusObject> dublinBusObjects = new ArrayList<>();
try {
//Use JSONParser to download the JSON
JSONParser jsonParser = new JSONParser();
JSONObject jsonObject = jsonParser.makeHttpRequest(
liveUpdateUrl, "GET", new HashMap<String, String>());
JSONArray jsonArray= jsonObject.getJSONArray("stops");
for (int x = 0; x < jsonArray.length(); x++) {
JSONObject jsonItem = jsonArray.getJSONObject(x);
this.busRoute = jsonItem.getString("bus_num");
this.busDescription = jsonItem.getString("description");
this.bueTime = jsonItem.getString("exected_dep");
this.busStopId = jsonItem.getString("stop_id");
DublinBusObject dublinBusObject = new DublinBusObject(busRoute, busDescription, bueTime, busStopId);
dublinBusObjects.add(dublinBusObject);
}
} catch (JSONException e) {
e.printStackTrace();
}
return dublinBusObjects;
}
This uses this JSONParser class from another answer of mine:
import android.util.Log;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
public class JSONParser {
String charset = "UTF-8";
HttpURLConnection conn;
DataOutputStream wr;
StringBuilder result;
URL urlObj;
JSONObject jObj = null;
StringBuilder sbParams;
String paramsString;
public JSONObject makeHttpRequest(String url, String method,
HashMap<String, String> params) {
sbParams = new StringBuilder();
int i = 0;
for (String key : params.keySet()) {
try {
if (i != 0){
sbParams.append("&");
}
sbParams.append(key).append("=")
.append(URLEncoder.encode(params.get(key), charset));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
i++;
}
if (method.equals("POST")) {
// request method is POST
try {
urlObj = new URL(url);
conn = (HttpURLConnection) urlObj.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Accept-Charset", charset);
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.connect();
paramsString = sbParams.toString();
wr = new DataOutputStream(conn.getOutputStream());
wr.writeBytes(paramsString);
wr.flush();
wr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
else if(method.equals("GET")){
// request method is GET
if (sbParams.length() != 0) {
url += "?" + sbParams.toString();
}
try {
urlObj = new URL(url);
conn = (HttpURLConnection) urlObj.openConnection();
conn.setDoOutput(false);
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept-Charset", charset);
conn.setConnectTimeout(15000);
conn.connect();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
//Receive the response from the server
InputStream in = new BufferedInputStream(conn.getInputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
Log.d("JSON Parser", "result: " + result.toString());
} catch (IOException e) {
e.printStackTrace();
}
conn.disconnect();
// try parse the string to a JSON object
try {
jObj = new JSONObject(result.toString());
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON Object
return jObj;
}
}
why is AsyncTask doing deprecated lines ? in my code?
HttpGet, HttpClient ,HttpResponse and HttpEntity are depreceated.
Now you have to use HttpUrlConnection
URL url = new URL("http://www.android.com/");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
readStream(in);
finally {
urlConnection.disconnect();
}
}
Related Topics
Variable Is Accessed Within Inner Class. Needs to Be Declared Final
How to Add a Shadow and a Border on Circular Imageview Android
Firestore Query - Checking If Username Already Exists
How to Make Rjava Use the Newer Version of Java on Osx
Import Maven Dependencies in Intellij Idea
Tracing Xml Request/Responses with Jax-Ws
How to Write Console Output to a Txt File
I Would Like to Set My Variables at the Top of My Class Instead of in the Method
How to Get Rjava 0.9-3 to Work on Os X 10.7.4 with Oracle Java 1.7
Sockets: Discover Port Availability Using Java
Running Code After Spring Boot Starts
How to Iterate Through the Unicode Codepoints of a Java String