私は、UrbanDictionaryにアクセスして、単語検索の結果をJSON形式で返すだけのアプリに取り組んでいます...その後、Androidプロジェクトに表示します。
これが私のコード全体です:
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();
}
}
}
カーテンの後ろにあるUtilities.slurpには注意を払わないでください。
したがって、これを実行してもクラッシュせず、実際には結果が得られますが、アプリではなくLogCatにスローされます。私は以前に次の例外を見つけました:
of type org.json.jsonarray cannot be converted to jsonobject
このフォーラムを調べて、配列(またはそのようなもの)内にオブジェクトがあるという概念を見つけましたが、それをコードに反映する方法がわかりません。
私がしたいのは、アプリに「Hey」と入力し、「Define」をクリックすると、その下に定義のリストが表示されることです。定義のみ...したがって、そのJSON部分は「定義」である必要があります
LogCatで取得したJSON出力を次に示します。私はこれが読みやすいことを願っています:
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
どんな助けでも大歓迎です!前もって感謝します!
更新:動作するコードは次のとおりです。
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"));
}