0

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"
    }
]
leerob
  • 2,876
  • 1
  • 18
  • 38
  • Please show json string returned from server – ρяσѕρєя K Apr 02 '15 at 03:57
  • I added one, however I'm not sure how useful that is. The code I've provided correctly parses and returns this data. I'm just not sure if it's the most optimal/efficient way since I'm relatively new to Android development. Just looking for some feedback! – leerob Apr 02 '15 at 04:01
  • i believe Gson is best to operate on Json and combined with volley things become quite easy as well – Pankaj Nimgade Apr 02 '15 at 04:04
  • @leerob : approach is fine. just use [android-volley](http://developer.android.com/training/volley/index.html) for getting json string from server – ρяσѕρєя K Apr 02 '15 at 04:06
  • @leerob, this question I asked when just started to deal with json. However, there is show a really good practice I've found. Just take a look on the structure of parsing. Hope it is useful for you http://stackoverflow.com/questions/25771184/exception-parsing-json-from-url-unterminated-array-at-character-115 Gson I'd suggest to use only when you have a huuge piece of work with json, another way, I don't think you really need it – Yurets Apr 02 '15 at 04:07
  • Side note: This AsyncTask will create memory leaks and assuming from activity name, you are using google maps which will drain your resources... Consider using IntentService or any approach that don't restrain acitivities from releasing resources and destroying. – asylume Apr 02 '15 at 05:49
  • Guys, how about Volley? (is a networking library developed by Google and introduced during Google I/O 2013. ) – Jakub S. Jun 01 '16 at 16:50

2 Answers2

0

@leerob Hello, at one time I found myself in a dilemma where you are, but lately I have used base classes that brings Android to handle json and is pretty good, a good practice I recommend you is to declare constants for the keys of json, I share an example:

 public void insertMovieTypeFromJson(String movieTypeJsonStr) throws JSONException {
            final String ID = "id";
            final String TYPE = "type";
            final String DESCRIPTION = "description";

            if (movieTypeJsonStr == null)
                    return;

            try {
                    JSONArray movieTypeArrayJson = new JSONArray(movieTypeJsonStr);

                    Vector<ContentValues> cVVector = new Vector<>(movieTypeArrayJson.length());

                    for (int i = 0; i < movieTypeArrayJson.length(); i++) {

                            long id;
                            String type;
                            String description;

                            JSONObject movie = movieTypeArrayJson.getJSONObject(i);

                            id = movie.getLong(ID);
                            type = movie.getString(TYPE);
                            description = movie.getString(DESCRIPTION);

                            ContentValues movieTypeValues = new ContentValues();

                            movieTypeValues.put(MovieContract.MovieTypeEntry._ID, id);
                            movieTypeValues.put(MovieContract.MovieTypeEntry.COLUMN_TYPE, type);
                            movieTypeValues.put(MovieContract.MovieTypeEntry.COLUMN_DESCRIPTION, description);
                            cVVector.add(movieTypeValues);
                    }

                    int inserted = 0;

                    if (cVVector.size() > 0) {
                            ContentValues[] cvArray = new ContentValues[cVVector.size()];
                            cVVector.toArray(cvArray);
                            inserted = getContext().getContentResolver().bulkInsert(MovieContract.MovieTypeEntry.CONTENT_URI, cvArray);
                    }

                    Log.d(LOG_TAG, "MovieTask Complete. " + inserted + " MovieType Inserted");

            } catch (JSONException e) {
                    Log.e(LOG_TAG, e.getMessage(), e);
                    e.printStackTrace();
            }
    }

Json:

[
    {
        "id": "1",
        "type": "Action & Adventure",
        "description": "Action & Adventure"
    },
    {
        "id": "2",
        "type": "Animation",
        "description": "Animation"
    },
    {
        "id": "3",
        "type": "Comedy",
        "description": "Comedy"
    },
    {
        "id": "4",
        "type": "Terror",
        "description": "Terror"
    }
]
Nimantha
  • 6,405
  • 6
  • 28
  • 69
Gabriel Perez
  • 21
  • 1
  • 3
0

Try this...

private class TestJSONParsing extends AsyncTask<JSONArray, Void, JSONArray>
{
    ArrayList<HashMap<String, String>> arraylist;
    HashMap<String, String> map;

    @Override
    protected void onPreExecute()
    {
        super.onPreExecute();
        mProgressDialog = new ProgressDialog(MapActivity.this);
        mProgressDialog.setTitle("Downloading Data");
        mProgressDialog.setMessage("Loading...");
        mProgressDialog.setIndeterminate(false);
        mProgressDialog.show();

    }

    @Override
    protected JSONArray doInBackground(JSONArray... params)
    {
        return JSONFunctions.getJSONfromURL("myurl");

    }

    @Override
    protected void onPostExecute(JSONArray resultArray)
    {
        super.onPostExecute(resultArray);
        mProgressDialog.dismiss();
        if (null != resultArray)
        {
            int resultLength = resultArray.length();
            if (resultLength > 0)
            {
                try
                {
                    for (int i = 0; i < resultLength; i++)
                    {
                        JSONObject jsonObject = resultArray
                                .getJSONObject(i);
                        map.put("id", String.valueOf(i));
                        map.put("name", jsonObject.getString("name"));
                        arraylist.add(map);
                    }
                } catch (Exception e)
                {
                    // TODO: handle exception
                    e.printStackTrace();
                }

                if (arraylist.size() > 0)
                {
                    SimpleAdapter adapter = new SimpleAdapter(
                            MapActivity.this, arraylist,
                            R.layout.your_simple_row, new String[]
                            { "id", "name" }, new int[]
                            { R.id.nameId, R.id.name });
                    // bind adapter to your components
                    listView.setAdapter(adapter);
                }
            }
        } else
        {
            Toast.makeText(getApplicationContext(), "No data",
                    Toast.LENGTH_SHORT).show();
        }

    }

}
Nimantha
  • 6,405
  • 6
  • 28
  • 69
Silambarasan Poonguti
  • 9,386
  • 4
  • 45
  • 38