Search code examples
androidjsonapijsonexception

How do I display the JSON results from UrbanDictionary in my app?


I'm working on an app that simply has to go out to UrbanDictionary and return the results of a word search in JSON format...then display it in an Android project.

Here is my code in its entirety:

package org.twodee.mitchemc.webapi;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ListActivity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends ListActivity {
    private ArrayList<String> definitionsList;
    private ArrayAdapter<String> adapter;
    private EditText wordText;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        wordText = (EditText) findViewById(R.id.wordText);
        Button defineButton = (Button) findViewById(R.id.defineButton);

        definitionsList = new ArrayList<String>();
        adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, definitionsList);
        setListAdapter(adapter);

        defineButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                String word = wordText.getText().toString();
                new DownloadTask().execute(word);
            }
        });
    }

    private ArrayList<String> getDefs(String word) {
        ArrayList<String> definitions = new ArrayList<String>();
        try {
            URL url = new URL("http://api.urbandictionary.com/v0/define?term="
                    + word);

            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            InputStream in = connection.getInputStream();

            String json = Utilities.slurp(in);
            Log.d("FOO", json);

            JSONArray array = new JSONArray(json);

            for (int i = 0; i < array.length(); ++i) {
                JSONObject object = array.getJSONObject(i);
                definitions.add(object.getString("definition"));
            }

            in.close();
        } catch (MalformedURLException e) {
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return definitions;
    }

    class DownloadTask extends AsyncTask<String, Void, ArrayList<String>> {

        @Override
        protected ArrayList<String> doInBackground(String... params) {
            String word = params[0];
            return getDefs(word);
        }

        @Override
        protected void onPostExecute(ArrayList<String> defs) {
            super.onPostExecute(defs);

            definitionsList.clear();
            definitionsList.addAll(defs);
            adapter.notifyDataSetChanged();
        }

    }

}

Pay no attention to the Utilities.slurp behind the curtain.

So, if I run this, it doesn't crash, and it actually does give me results, but it throws them in LogCat...not my app. I previously found the following exception:

of type org.json.jsonarray cannot be converted to jsonobject

I looked over this forum and found the notion that I've got objects within an array (or something like that) but I can't figure out how to reflect that in code.

What I'd like to have happen is you type, say, "Hey" into the app, hit "Define" and then there's a list of definitions below it. Only the definitions...so the JSON part of it should be "definition"

Here's some JSON output that I get in LogCat. I hope this is readable:

12-06 19:00:57.647: W/System.err(1400): org.json.JSONException: Value {"total":32,"result_type":"exact","list":[{"thumbs_down":428,"author":"D.B. Echo","definition":"A contraction for \"Hello, I find you attractive and would like to dance with you, share some drinks with you, and then perhaps have sex with you.  Nothing serious, of course, and I doubt that this will result in a long term relationship, but I would appeciate you considering my proposal.\"","permalink":"http:\/\/hey.urbanup.com\/1099714","thumbs_up":1530,"word":"hey","current_vote":"","example":"Guy at bar to attractive girl: \"Hey.\"\r\n\r\nAttractive girl to guy: \"Go to hell, creep.\" (Moves to other side of bar.)","defid":1099714},{"thumbs_down":250,"author":"Erica","definition":"hey is a way to say \"hi\" or \"what's up\"\r\nthe type of 'hey' horses eat is hAy you morons!!!","permalink":"http:\/\/hey.urbanup.com\/574637","thumbs_up":541,"word":"Hey","current_vote":"","example":"hey what's up!?!\r\nhorses eat hay!","defid":574637},{"thumbs_down":144,"author":"SoMe RaNdOm PeRsOn","definition":"I word to use to get someone's attention. Even if you don't know the persons name by simply saying \"hey\" you can easily get their attention","permalink":"http:\/\/hey.urbanup.com\/1106278","thumbs_up":294,"word":"hey","current_vote":"","example":"guy 1:Hey Alex what's that guys name over there?\r\nAlex: How the hell should I know?\r\nGuy 1: Hey!!\r\nMystery guy: ::looks around confused::\r\nGuy 1: O hi.","defid":1106278},{"thumbs_down":120,"author":"Jamesrob92","definition":"1. The most informal form of greeting. Usually used in a friendly manner or to sound cool and relaxed.\r\n2. An exclamation used to get someone's attention","permalink":"http:\/\/hey.urbanup.com\/2153666","thumbs_up":249,"word":"hey","current_vote":"","example":"1. Hey, what's up?\r\n2. HEY! Wait for me!\r\n3. HEY YOU! Get away from my wife!","defid":2153666},{"thumbs_down":133,"author":"marshmallow","definition":"a slang term used by many people in place of hello","permalink":"http:\/\/hey.urbanup.com\/1129122","thumbs_up":219,"word":"hey","current_vote":"","example":"Hey Ma...whats crackin?","defid":1129122},{"thumbs_down":79,"author":"hey malasadas","definition":"an expression used to get someone's attention","permalink":"http:\/\/hey.urbanup.com\/198491","thumbs_up":128,"word":"hey","current_vote":"","example":"hey man, what the hell are you doing?!","defid":198491},{"thumbs_down":54,"author":"HappyGirl1993","definition":"Considered to be a lot more flirtatious than 'hello' or 'hi.'","permalink":"http:\/\/hey.urbanup.com\/5302185","thumbs_up":68,"word":"Hey","current_vote":"","example":"Example...\n\nGuy: Hey.\r\nGirl: Hi.\r\nGuy: *Whoa, total FAIL!*","defid":5302185},{"thumbs_down":37,"author":"Eric Klein...","definition":"1. Interjection, an informal greeting. \r\n\r\n2. Verb, to 'hey' someone.  The act of driving down public roads in a lane near a sidewalk, coming upon an unsuspecting pedestrian, and hollering \"HEY!\" as loudly as possible in their general direction.  Most effective if done with all windows rolled down, and all members of the vehicle participating. (Originating in Sioux Falls, SD)","permalink":"http:\/\/hey.urbanup.com\/2705914","thumbs_up":42,"word":"Hey","current_vote":"","example":"1. \"Hey buddy, how's the syphilis?\"\r\n\r\n2. \"Jimmy and I heyed a kid so bad the other day, he fell off his bike!\"","defid":2705914},{"thumbs_down":80,"author":"J-Lib","definition":"a slang interjection or prompt often used in place of \"eh\" or \"right\" in order to make a sentence into a question; used in parts of Canada","permalink":"http:\/\/hey.urbanup.com\/1262450","thumbs_up":67,"word":"hey","current_vote":"","example":"It's supposed to snow tomorrow, hey?\r\nThat guy was pretty attractive, hey?","defid":1262450},{"thumbs_down":7,"author":"Bam Bam Branson","definition":"Why would you even search this?","permalink":"http:\/\/hey.urbanup.com\/5850424","thumbs_up":8,"word":"Hey","current_vote":"","example":"Hey is Idk","defid":5850424}],"pages":4,"sounds":["http:\/\/media.urbandictiona

Any help would be greatly appreciated! Thanks in advance!

UPDATE: Here's the code that works:

                String json = Utilities.slurp(in);
            JSONObject jsonObject = new JSONObject(json);
            JSONArray array = jsonObject.getJSONArray("list");

            for (int i = 0; i < array.length(); ++i) {
                JSONObject object = array.getJSONObject(i);
                definitions.add(object.getString("definition"));
            }

Solution

  • Based on the json you get back from that request, you are setting up your JSONObject wrong. Here is an example of the json that comes back:

    {
        "has_related_words": true,
        "result_type": "exact",
        "list": [
            {
                "defid": 2957653,
                "word": "test",
                "author": "sm1g",
                "permalink": "http://test.urbanup.com/2957653",
                "definition": "To check if something coresponds the promised result or what effect does it have at all.",
                "example": "By typing in the word \"test\" you prolly tried to search if there was a definition for this word.",
                "thumbs_up": 123,
                "thumbs_down": 46,
                "current_vote": ""
            }
    ],
        "sounds": [
            "http://media.urbandictionary.com/sound/test-8076.mp3"
        ],
        "total": 20,
        "pages": 2
    }
    

    In your code, to grab an array like list, you would need to do:

    String json = Utilities.slurp(in);
    JSONObject jsonObject = new JSONObject(json);
    
    //now get the list array
    JSONArray list = new JSONArray(jsonObject.getArray("list"));
    

    The method names may not be exact.