I’m trying to parse a JSON result fetched from a URL in my Android app…
I have tried a few examples on the Internet, but can’t get it to work. The JSON data looks like this:
[
{
"city_id": "1",
"city_name": "Noida"
},
{
"city_id": "2",
"city_name": "Delhi"
},
{
"city_id": "3",
"city_name": "Gaziyabad"
},
{
"city_id": "4",
"city_name": "Gurgaon"
},
{
"city_id": "5",
"city_name": "Gr. Noida"
}
]
What’s the simplest way to fetch the URL and parse the JSON data show it in the listview
You could use
AsyncTask, you’ll have to customize to fit your needs, but something like the followingAsync task has three primary methods:
onPreExecute()– most commonly used for setting up and starting a progress dialogdoInBackground()– Makes connections and receives responses from the server (Do NOT try to assign response values to GUI elements, this is a common mistake, that cannot be done in a background thread).onPostExecute()– Here we are out of the background thread, so we can do user interface manipulation with the response data, or simply assign the response to specific variable types.First we will start the class, initialize a
Stringto hold the results outside of the methods but inside the class, then run theonPreExecute()method setting up a simple progress dialog.Then we need to set up the connection and how we want to handle the response:
Lastly, here we will parse the return, in this example it was a JSON Array and then dismiss the dialog: