Android Studio で Livedoor の お天気Webサービス(JSON) を読み込んで ListView に表示する

Livedoor の お天気Webサービス はこの手のテストに最適な API です。結果は JSON フォーマットで返されるので、 Google Gson を使用します。

※ Google Gson のオンラインドキュメント

読み込んだ後、SharedPreferences で書き込んでいます。


 

001.package app.lightbox.winofsql.jp.weather;
002. 
003.import android.app.Activity;
004.import android.content.Intent;
005.import android.content.SharedPreferences;
006.import android.net.Uri;
007.import android.os.AsyncTask;
008.import android.os.Bundle;
009.import android.util.Log;
010.import android.view.Menu;
011.import android.view.MenuItem;
012.import android.view.View;
013.import android.widget.AdapterView;
014.import android.widget.ArrayAdapter;
015.import android.widget.Button;
016.import android.widget.ListView;
017.import android.widget.Toast;
018. 
019.import com.google.gson.Gson;
020. 
021.public class MainActivity extends Activity {
022. 
023.        private ArrayAdapter<PinpointLocation> arrayMyData = null;
024.        private HttpGet hg = new HttpGet();
025. 
026.        @Override
027.        protected void onCreate(Bundle savedInstanceState) {
028.                super.onCreate(savedInstanceState);
029.                setContentView(R.layout.activity_main);
030. 
031.                // WEBアクセス( HttpGet )
032.                Button button = (Button) this.findViewById(R.id.button);
033.                button.setOnClickListener(new View.OnClickListener() {
034.                        @Override
035.                        public void onClick(View v) {
036.                                new AsyncTask<String, Void, String>() {
037. 
038.                                        // 非同期処理
039.                                        @Override
040.                                        protected String doInBackground(String... params) {
041.                                                String result = null;
042.                                                HttpGet hg = new HttpGet();
043.                                                result =
044.                                                                hg.execute(
045.                                                                                params[0],
046.                                                                                params[1],
047.                                                                                null
048.                                                                );
049. 
050.                                                return result;
051.                                        }
052. 
053.                                        // UI スレッド処理
054.                                        @Override
055.                                        protected void onPostExecute(String json) {
056.                                                super.onPostExecute(json);
057. 
058.                                                // ListView のインスタンスを取得
059.                                                ListView listview = (ListView) MainActivity.this.findViewById(R.id.listView);
060.                                                // 専用クラス用
061.                                                arrayMyData = new ArrayAdapter<PinpointLocation>(
062.                                                                MainActivity.this,
063.                                                                android.R.layout.simple_list_item_1,
064.                                                                android.R.id.text1
065.                                                );
066. 
067.                                                Gson gson = new Gson();
068.                                                Weather weatherData = gson.fromJson(json, Weather.class);
069. 
070.                                                // Weather クラス内の配列部分をセット
071.                                                arrayMyData.addAll(weatherData.pinpointLocations);
072.                                                listview.setAdapter(arrayMyData);
073. 
074.                                                String reJson = gson.toJson(weatherData);
075.                                                SharedPreferences sp = getSharedPreferences("lightbox", MODE_PRIVATE);
076.                                                SharedPreferences.Editor editor = sp.edit();
077.                                                editor.putString("json", reJson);
078.                                                editor.commit();
079. 
080.                                        }
081.                                }.execute("http://weather.livedoor.com/forecast/webservice/json/v1?city=270000", "utf-8");
082.                        }
083.                });
084. 
085.                // クリックした時のイベント作成
086.                ListView listview = (ListView) MainActivity.this.findViewById(R.id.listView);
087.                listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
088.                        @Override
089.                        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
090.                                // クリックされたビューの内部データ
091.                                Object data = (Object) parent.getItemAtPosition(position);
092. 
093.                                PinpointLocation myData = (PinpointLocation) data;
094.                                Log.i("lightbox", "url:" + myData.link);
095. 
096.                                // ブラウザの呼び出し
097.                                callBrowser(myData.link);
098. 
099.                        }
100.                });
101.        }
102. 
103.        private void callBrowser( String url ) {
104.                // ブラウザの呼び出し
105.                Uri uri = Uri.parse(url);
106.                Intent intent = new Intent(Intent.ACTION_VIEW, uri);
107.                if (intent.resolveActivity(getPackageManager()) != null) {
108.                        startActivity(intent);
109.                        return;
110.                }
111. 
112.                // 対応するアプリが無い
113.                Toast.makeText(
114.                                MainActivity.this,
115.                                "ブラウザを呼び出せません",
116.                                Toast.LENGTH_LONG
117.                ).show();
118.                return;
119. 
120.        }
121. 
122.        public class PinpointLocation {
123.                String link;
124.                String name;
125. 
126.                @Override
127.                public String toString() {
128.                        return name;
129.                }
130.        }
131. 
132.        @Override
133.        public boolean onCreateOptionsMenu(Menu menu) {
134.                getMenuInflater().inflate(R.menu.menu_main, menu);
135.                return true;
136.        }
137. 
138.        @Override
139.        public boolean onOptionsItemSelected(MenuItem item) {
140.                int id = item.getItemId();
141. 
142.                if (id == R.id.lv_action1) {
143.                        if ( arrayMyData == null || arrayMyData.getCount() == 0 ) {
144.                                Toast.makeText(MainActivity.this,"データがありません",Toast.LENGTH_LONG).show();
145.                                return true;
146.                        }
147. 
148.                        PinpointLocation data = new PinpointLocation();
149.                        // 久留米市
150.                        data.name = "\u4e45\u7559\u7c73\u5e02";
151.                        data.link = "http://weather.livedoor.com/area/forecast/4020300";
152.                        arrayMyData.insert(data,3);
153. 
154.                        return true;
155.                }
156. 
157.                if (id == R.id.lv_action2) {
158.                        if ( arrayMyData == null || arrayMyData.getCount() == 0 ) {
159.                                Toast.makeText(MainActivity.this,"データがありません",Toast.LENGTH_LONG).show();
160.                                return true;
161.                        }
162. 
163.                        PinpointLocation data = null;
164.                        int count = arrayMyData.getCount();
165.                        for ( int i = 0; i < count; i++ ) {
166.                                data = arrayMyData.getItem(i);
167.                                Log.i("lightbox",data.name + ":" + data.link);
168.                        }
169. 
170.                        return true;
171.                }
172. 
173. 
174.                return super.onOptionsItemSelected(item);
175.        }
176.}

Common Intents ( Web Browser ) | Android Developers

JSON 用 Weather クラス
01.package app.lightbox.winofsql.jp.weather;
02. 
03. 
04.public class Weather {
05. 
06.        class Text {
07.                String text;
08.                String publicTime;
09.        }
10. 
11.        class Location {
12.                String city;
13.                String area;
14.                String prefecture;
15.        }
16. 
17.        class IntTest {
18.                ImageSize image;
19.        }
20. 
21.        class ImageSize {
22.                int width;
23.                int height;
24.        }
25. 
26.        MainActivity.PinpointLocation[] pinpointLocations;
27.        Location location;
28.        IntTest copyright;
29.        Text description;
30. 
31.        // Getter と Setter で処理する
32.        private String publicTime;
33. 
34.        String getPublicTime() {
35.                return publicTime.substring(0, 10);
36.        }
37.        void setPublicTime(String publicTime) {
38.                this.publicTime = publicTime;
39.        }
40. 
41.}

HttpGet.java
01.package app.lightbox.winofsql.jp.weather;
02. 
03.import java.io.BufferedReader;
04.import java.io.InputStream;
05.import java.io.InputStreamReader;
06.import java.net.CookieHandler;
07.import java.net.CookieManager;
08.import java.net.HttpURLConnection;
09.import java.net.URL;
10.import java.net.URLEncoder;
11.import java.util.Iterator;
12.import java.util.Map;
13. 
14.public class HttpGet {
15. 
16.        // **********************************************
17.        // コンストラクタ
18.        // **********************************************
19.        public HttpGet() {
20.        }
21. 
22.        // **********************************************
23.        // 指定した URL へ 任意の charset で処理
24.        // **********************************************
25.        public String execute(String targetUrl,String targetCharset,Map<String,String> params) {
26. 
27.                StringBuffer web_data = new StringBuffer();
28. 
29.                try {
30.                        // **********************************************
31.                        // Query String の作成( 必要無ければ引数を null とする )
32.                        // **********************************************
33.                        String data = "";
34.                        if ( params != null ) {
35.                                Iterator<String> it =  params.keySet().iterator();
36.                                String key = null;
37.                                String value = null;
38.                                while(it.hasNext()) {
39.                                        key = it.next().toString();
40.                                        value = params.get(key);
41.                                        if ( !data.equals("") ) {
42.                                                data += "&";
43.                                        }
44.                                        data += key + "=" + URLEncoder.encode(value, targetCharset) ;
45.                                }
46.                                if ( !data.equals("") ) {
47.                                        targetUrl = targetUrl + "?" + data;
48.                                }
49.                        }
50. 
51.                        // **********************************************
52.                        // インターネットへの接続
53.                        // **********************************************
54.                        // 読み込む WEB上のターゲット
55.                        URL url = new URL(targetUrl);
56.                        // 接続オブジェクト
57.                        HttpURLConnection http = (HttpURLConnection)url.openConnection();
58.                        // GET メソッド
59.                        http.setRequestMethod("GET");
60.                        // 接続
61.                        http.connect();
62. 
63.                        // **********************************************
64.                        // ストリームとして読み込む準備
65.                        // **********************************************
66.                        // 以下読み込み3点セット InputStream / InputStreamReader / BufferedReader
67.                        InputStream input_stream = http.getInputStream();
68.                        // UTF-8 でリーダーを作成
69.                        InputStreamReader input_stream_reader = new InputStreamReader(input_stream, targetCharset);
70.                        // 行単位で読み込む為の準備
71.                        BufferedReader buffered_reader = new BufferedReader(input_stream_reader);
72. 
73.                        // **********************************************
74.                        // 行の一括読み込み
75.                        // **********************************************
76.                        String line_buffer = null;
77.                        // BufferedReader は、readLine が null を返すと読み込み終了
78.                        while ( null != (line_buffer = buffered_reader.readLine() ) ) {
79.                                web_data.append( line_buffer );
80.                                web_data.append( "\n" );
81.                        }
82. 
83.                        // **********************************************
84.                        // 接続解除
85.                        // **********************************************
86.                        http.disconnect();
87.                }
88.                catch(Exception e) {
89.                        // 失敗
90.                        System.out.println( e.getMessage());
91.                }
92.                return web_data.toString();
93.        }
94.}

メニュー定義
01.<menu xmlns:android="http://schemas.android.com/apk/res/android"
02.          xmlns:tools="http://schemas.android.com/tools"
03.          tools:context=".MainActivity">
04.        <item
05.                android:id="@+id/lv_action1"
06.                android:title="処理1"
07.                android:orderInCategory="100"
08.                android:showAsAction="never"/>
09.        <item
10.                android:id="@+id/lv_action2"
11.                android:title="処理2"
12.                android:orderInCategory="100"
13.                android:showAsAction="never"/>
14.        <item
15.                android:id="@+id/lv_action3"
16.                android:title="処理3"
17.                android:orderInCategory="100"
18.                android:showAsAction="never"/>
19.        <item
20.                android:id="@+id/lv_action4"
21.                android:title="処理4"
22.                android:orderInCategory="100"
23.                android:showAsAction="never"/>
24.        <item
25.                android:id="@+id/lv_action5"
26.                android:title="処理5"
27.                android:orderInCategory="100"
28.                android:showAsAction="never"/>
29. 
30.</menu>