I've been researching how to query JSON data from a server and parse it for use in my application. However, I've found a number of different ways to do the same thing. I realize there are different JSON parsers out there, so let's assume I'm sticking with the standard one. The main question I have has to do with the server requests. Here is my current code for my MapActivity
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
@Override
protected void onPreExecute() {
super.onPreExecute();
// Create a Progress Dialog
mProgressDialog = new ProgressDialog(MapActivity.this);
mProgressDialog.setTitle("Downloading Data");
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
mProgressDialog.show();
}
@Override
protected Void doInBackground(Void... params) {
// Create an array
arraylist = new ArrayList<HashMap<String, String>>();
try {
// Retrieve JSON Objects from the given URL address
jsonarray = JSONFunctions.getJSONfromURL("myurl");
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject obj = jsonarray.getJSONObject(i);
// Retrieve JSON Objects
map.put("id", String.valueOf(i));
map.put("name", obj.getString("name"));
// Set the JSON Objects into the array
arraylist.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void args) {
// Do something with data
mProgressDialog.dismiss();
}
}
If the structure of my JSON data looks weird, it's because it's stored in an unnamed array so I don't have to create an object first. Anyway... I essentially based this off of this tutorial. However, they have soooo much more code. Is that all really necessary? I didn't think so. I searched around more and found other examples that used half the code and essentially did the same thing. So my question, as a beginning Android programmer, is what is the best practice for handling JSON data? Thanks!
Example of JSON file:
[
{
"name": "test",
"lat": "42.01108",
"long": "93.679196"
},
{
"name": "test",
"lat": "42.01108",
"long": "93.679196"
}
]