Tools クラスで、Google Gson + ListView + Preferences + Intent

1) Livedoor の お天気Webサービス API を読み込んで JSON 文字列を取得します
2) Google Gson を使用して、JSON 文字列を Java のオブジェクトの配列に変換します
3) オブジェクトの配列を ArrayAdapter で ListView に表示します
4) メニューから『追加』『修正』『削除』『クリア』『一覧参照』の処理をテストします


5) Click と LongClick のイベントを使って、次画面に画面遷移します
6) Click では、Preferences を使い、LongClick では putExtra でオブジェクトを引き渡します 
7) 次画面では、引き渡した内容を表示して、url のデータで WEBブラウザを開きます


8) 閉じるボタンを使用すると、呼び出し元へデータ(時間文字列)を戻します
9) 呼び出し元の画面で、onActivityResult で受けた場合は AlertDialog で戻されたデータを表示します

Tools クラス

▼ Preferences の場所
 
 

MainActivity

001.package app.lightbox.winofsql.jp.weather;
002. 
003.import android.app.Activity;
004.import android.content.Intent;
005.import android.os.Bundle;
006.import android.util.Log;
007.import android.view.Menu;
008.import android.view.MenuItem;
009.import android.view.View;
010.import android.widget.AdapterView;
011.import android.widget.ArrayAdapter;
012.import android.widget.Button;
013.import android.widget.ListView;
014.import android.widget.Toast;
015. 
016.import com.google.gson.Gson;
017.import com.google.gson.GsonBuilder;
018. 
019.import jp.android.work.Tools;
020. 
021.public class MainActivity extends Activity {
022. 
023.        private ArrayAdapter<PinpointLocation> arrayMyData = null;
024. 
025.        @Override
026.        protected void onCreate(Bundle savedInstanceState) {
027.                super.onCreate(savedInstanceState);
028.                setContentView(R.layout.activity_main);
029. 
030.                // 専用クラス用
031.                arrayMyData = new ArrayAdapter<PinpointLocation>(
032.                        MainActivity.this,
033.                        android.R.layout.simple_list_item_1,
034.                        android.R.id.text1
035.                );
036. 
037.                // WEBアクセス( HttpGet )
038.                Button button = (Button) this.findViewById(R.id.button);
039.                button.setOnClickListener(new View.OnClickListener() {
040.                        @Override
041.                        public void onClick(View v) {
042. 
043.                                Tools.callHttpGet("http://weather.livedoor.com/forecast/webservice/json/v1?city=270000", "utf-8",
044.                                                new Tools.OnAsyncTaskListener() {
045.                                                        @Override
046.                                                        public void onAsyncTaskListener(String s) {
047.                                                                Gson gson = new Gson();
048.                                                                Weather weatherData = gson.fromJson(s, Weather.class);
049. 
050.                                                                // ListView のインスタンスを取得
051.                                                                ListView listview = (ListView) MainActivity.this.findViewById(R.id.listView);
052.                                                                // Weather クラス内の配列部分をセット
053.                                                                arrayMyData.clear();
054.                                                                arrayMyData.addAll(weatherData.pinpointLocations);
055.                                                                listview.setAdapter(arrayMyData);
056. 
057.                                                                // 整形した json 文字列を再作成
058.                                                                Gson prettyGson = new GsonBuilder().setPrettyPrinting().create();
059.                                                                String json = prettyGson.toJson(weatherData);
060. 
061.                                                                // アプリに保存
062.                                                                Tools.putPreferences(MainActivity.this, "lightbox", "init_all", json);
063. 
064.                                                        }
065.                                                });
066. 
067.                        }
068.                });
069. 
070.                // クリック(タップ)した時のイベント作成
071.                ListView listview = (ListView) MainActivity.this.findViewById(R.id.listView);
072.                listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
073.                                @Override
074.                                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
075.                                // クリックされたビューの内部データ
076.                                Object data = (Object) parent.getItemAtPosition(position);
077. 
078.                                PinpointLocation myData = (PinpointLocation) data;
079.                                Log.i("lightbox", "name:" + myData.name +", url:" + myData.link);
080. 
081.                                // アプリに保存
082.                                Tools.putPreferences(MainActivity.this, "lightbox", "url", myData.link);
083.                                Tools.putPreferences(MainActivity.this, "lightbox", "name", myData.name);
084. 
085.                                // 次画面の呼び出し
086.                                Tools.callActivity(MainActivity.this, NextPage.class,NextPage.NEXT_PAGE);
087.                        }
088.                });
089. 
090.                // 長押し
091.                listview.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
092.                        @Override
093.                        public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
094. 
095.                                PinpointLocation data = (PinpointLocation) parent.getItemAtPosition(position);
096. 
097.                                Intent intent = new Intent(MainActivity.this,NextPage.class);
098.                                // Serializable インターフェイスを持つオブジェクトのセット
099.                                intent.putExtra("LongClick",data);
100.                                startActivityForResult(intent, NextPage.NEXT_PAGE);
101. 
102.                                // 単純クリックイベントを処理しない
103.                                return true;
104.                        }
105.                });
106. 
107.        }
108. 
109.        // JSON 内の配列フォーマット
110.        public class Weather {
111. 
112.                PinpointLocation[] pinpointLocations;
113. 
114.        }
115. 
116.        @Override
117.        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
118.                if ( requestCode == NextPage.NEXT_PAGE ) {
119.                        if ( resultCode == RESULT_OK) {
120.                                String result = data.getStringExtra("時間");
121.                                Tools.messageBox(MainActivity.this, result, null);
122.                        }
123.                }
124. 
125.                super.onActivityResult(requestCode, resultCode, data);
126.        }
127. 
128.        // メニューの処理
129.        @Override
130.        public boolean onOptionsItemSelected(MenuItem item) {
131.                int id = item.getItemId();
132. 
133.                // リストビューに追加
134.                if (id == R.id.lv_action1) {
135.                        // データを取得して 1 件以上ある場合
136.                        if ( arrayMyData.getCount() != 0 ) {
137.                                // 新しくデータを追加
138.                                PinpointLocation data = new PinpointLocation();
139.                                // 久留米市
140.                                data.name = "\u4e45\u7559\u7c73\u5e02";
141.                                data.link = "http://weather.livedoor.com/area/forecast/4020300";
142.                                // 4番目に追加
143.                                arrayMyData.insert(data,3);
144. 
145.                                return true;
146.                        }
147. 
148.                }
149. 
150.                // 一覧を LogCat に表示
151.                if (id == R.id.lv_action2) {
152.                        if ( arrayMyData.getCount() != 0 ) {
153. 
154.                                // ArrayAdapter からひとつづつ取り出す
155.                                PinpointLocation data = null;
156.                                int count = arrayMyData.getCount();
157.                                for (int i = 0; i < count; i++) {
158.                                        data = arrayMyData.getItem(i);
159.                                        Log.i("lightbox", data.name + ":" + data.link);
160.                                }
161. 
162.                                return true;
163.                        }
164.                }
165. 
166.                // 全てクリア
167.                if (id == R.id.lv_action3) {
168.                        if ( arrayMyData.getCount() != 0 ) {
169. 
170.                                arrayMyData.clear();
171. 
172.                                return true;
173.                        }
174.                }
175. 
176.                // 4番目を削除
177.                if (id == R.id.lv_action4) {
178.                        if ( arrayMyData.getCount() != 0 ) {
179. 
180.                                // 4番目の内容を取り出す
181.                                PinpointLocation data = null;
182.                                data = arrayMyData.getItem(3);
183.                                arrayMyData.remove(data);
184. 
185.                                return true;
186.                        }
187.                }
188. 
189.                // 4番目を変更
190.                if (id == R.id.lv_action5) {
191.                        if ( arrayMyData.getCount() != 0 ) {
192. 
193.                                // 4番目の内容を取り出す
194.                                PinpointLocation data = null;
195.                                data = arrayMyData.getItem(3);
196. 
197.                                // 時間データをタイトルにする
198.                                String time = Tools.getDateString("HH'時'mm'分'ss'秒'");
199. 
200.                                // データを再設定
201.                                data.name = time;
202.                                // 変更を通知
203.                                arrayMyData.notifyDataSetChanged();
204. 
205.                                return true;
206.                        }
207.                }
208. 
209. 
210.                Toast.makeText(MainActivity.this,"データがありません",Toast.LENGTH_LONG).show();
211.                return super.onOptionsItemSelected(item);
212.        }
213. 
214.        // メニュー作成
215.        @Override
216.        public boolean onCreateOptionsMenu(Menu menu) {
217.                getMenuInflater().inflate(R.menu.menu_main, menu);
218.                return true;
219.        }
220. 
221.}

NextPage
01.package app.lightbox.winofsql.jp.weather;
02. 
03.import android.app.Activity;
04.import android.content.Intent;
05.import android.os.Bundle;
06.import android.view.View;
07.import android.widget.Button;
08.import android.widget.TextView;
09. 
10.import jp.android.work.Tools;
11. 
12./**
13. * Created by lightbox on 2015/06/15.
14. */
15.public class NextPage extends Activity {
16. 
17.        public static final int NEXT_PAGE = 100;
18.        private PinpointLocation data = null;
19. 
20.        @Override
21.        protected void onCreate(Bundle savedInstanceState) {
22.                super.onCreate(savedInstanceState);
23.                setContentView(R.layout.layout_nextpage);
24. 
25.                TextView textView = (TextView) NextPage.this.findViewById(R.id.textView);
26. 
27.                // 前画面から渡されたオブジェクトの取得
28.                Intent intent = NextPage.this.getIntent();
29.                data = (PinpointLocation)intent.getSerializableExtra("LongClick");
30.                // ただのクリック
31.                if ( data == null ) {
32.                        // data が null なので作成
33.                        data = new PinpointLocation();
34.                        data.link = Tools.getPreferences(NextPage.this, "lightbox", "url");
35.                        data.name = Tools.getPreferences(NextPage.this, "lightbox", "name");
36.                        textView.setText(data.name);
37.                }
38.                // 長押し
39.                else {
40.                        textView.setText(data.link);
41.                }
42. 
43.                Button webButton = (Button) NextPage.this.findViewById(R.id.button2);
44.                webButton.setOnClickListener(new View.OnClickListener() {
45.                        @Override
46.                        public void onClick(View v) {
47.                                Tools.callBrowser(NextPage.this,data.link);
48.                        }
49.                });
50. 
51.                // 終了ボタン
52.                Button closeButton = (Button) NextPage.this.findViewById(R.id.button3);
53.                closeButton.setOnClickListener(new View.OnClickListener() {
54.                        @Override
55.                        public void onClick(View v) {
56. 
57.                                Intent intent = NextPage.this.getIntent();
58.                                intent.putExtra("時間",Tools.getDateString("HH'時'mm'分'ss'秒'"));
59.                                setResult(RESULT_OK,intent);
60.                                finish();
61.                        }
62.                });
63. 
64. 
65.        }
66.}

PinpointLocation
01.package app.lightbox.winofsql.jp.weather;
02. 
03.import java.io.Serializable;
04. 
05./**
06. * Created by lightbox on 2015/06/15.
07. */
08.// 一行ぶんのデータフォーマット
09.public class PinpointLocation implements Serializable {
10.        String link;
11.        String name;
12. 
13.        @Override
14.        public String toString() {
15.                return name;
16.        }
17.}

activity_main.xml
01.<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
02.                                xmlns:tools="http://schemas.android.com/tools"
03.                                android:layout_width="match_parent"
04.                                android:layout_height="match_parent"
05.                                android:paddingLeft="@dimen/activity_horizontal_margin"
06.                                android:paddingRight="@dimen/activity_horizontal_margin"
07.                                android:paddingTop="@dimen/activity_vertical_margin"
08.                                android:paddingBottom="@dimen/activity_vertical_margin"
09.                                tools:context=".MainActivity">
10. 
11.        <Button
12.                android:layout_width="fill_parent"
13.                android:layout_height="wrap_content"
14.                android:text="HttpGet"
15.                android:id="@+id/button"
16.                android:layout_alignParentTop="true"
17.                android:layout_alignParentStart="true"/>
18. 
19.        <ListView
20.                android:layout_width="wrap_content"
21.                android:layout_height="wrap_content"
22.                android:id="@+id/listView"
23.                android:layout_below="@+id/button"
24.                android:layout_alignParentStart="true"/>
25.</RelativeLayout>

layout_nextpage.xml
01.<?xml version="1.0" encoding="utf-8"?>
02.<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
03.                                android:layout_width="match_parent"
04.                                android:layout_height="match_parent">
05. 
06.        <TextView
07.                android:layout_width="fill_parent"
08.                android:layout_height="wrap_content"
09.                android:textAppearance="?android:attr/textAppearanceLarge"
10.                android:id="@+id/textView"
11.                android:layout_alignParentTop="true"
12.                android:layout_alignParentStart="true"
13.                android:padding="10dp"/>
14. 
15.        <Button
16.                android:layout_width="fill_parent"
17.                android:layout_height="wrap_content"
18.                android:text="Webブラウザを開く"
19.                android:id="@+id/button2"
20.                android:layout_below="@+id/textView"
21.                android:layout_alignParentStart="true"
22.                android:textSize="20dp"/>
23. 
24.        <Button
25.                android:layout_width="fill_parent"
26.                android:layout_height="fill_parent"
27.                android:text="閉じる"
28.                android:id="@+id/button3"
29.                android:layout_below="@+id/button2"
30.                android:layout_centerHorizontal="true"
31.                android:textSize="60dp"/>
32.</RelativeLayout>

メニュー定義
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="追加"
07.                android:orderInCategory="100"
08.                android:showAsAction="never"/>
09.        <item
10.                android:id="@+id/lv_action2"
11.                android:title="一覧を LogCat に表示"
12.                android:orderInCategory="100"
13.                android:showAsAction="never"/>
14.        <item
15.                android:id="@+id/lv_action3"
16.                android:title="クリア"
17.                android:orderInCategory="100"
18.                android:showAsAction="never"/>
19.        <item
20.                android:id="@+id/lv_action4"
21.                android:title="削除"
22.                android:orderInCategory="100"
23.                android:showAsAction="never"/>
24.        <item
25.                android:id="@+id/lv_action5"
26.                android:title="変更"
27.                android:orderInCategory="100"
28.                android:showAsAction="never"/>
29. 
30.</menu>

関連するリンク集

Java 関連リンク ( 主に Android )