手順1 AndroidManifest.xml に、以下を追加する <uses-permission android:name="android.permission.INTERNET"/> 手順2 build.gradle(Module) に、Okhttp と Google Gson の記述を追加する
dependencies { implementation fileTree(dir: 'libs', include: ['*.jar']) implementation 'com.android.support:appcompat-v7:28.0.0' implementation 'com.android.support.constraint:constraint-layout:1.1.3' testImplementation 'junit:junit:4.12' androidTestImplementation 'com.android.support.test:runner:1.0.2' androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2' implementation 'com.google.code.gson:gson:2.8.5' implementation 'com.squareup.okhttp3:okhttp:4.1.0' }
activity_main.xml に ListView をセット
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <ListView android:id="@+id/listView" android:layout_width="match_parent" android:layout_height="match_parent"/> </LinearLayout>
JSON データをデシリアイズする為のクラスを作成
public class Weather { WebData[] pinpointLocations; }
public class WebData { String link; String name; @Override public String toString() { return name; } }
インターネットアクセス用のクラス HttpAccess クラスを追加
import android.os.AsyncTask; import java.io.IOException; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; public class HttpAccess { private OkHttpClient okHttpClient; private String url; public interface OnAsyncTaskListener { abstract public void onAsyncTaskListener(String s); } public HttpAccess(String url) { this.okHttpClient = new OkHttpClient(); this.url = url; } public void sendGet(final OnAsyncTaskListener listener ) { new AsyncTask<Void,Void,String>(){ @Override protected String doInBackground(Void... params) { String result = "[\"error\"]"; Request.Builder builder = new Request.Builder(); builder.url(HttpAccess.this.url); Request request = builder.build(); Response response = null; try { response = HttpAccess.this.okHttpClient.newCall(request).execute(); result = response.body().string(); } catch (IOException e) { e.printStackTrace(); } return result; } // UI スレッド処理 @Override protected void onPostExecute(String s) { super.onPostExecute(s); listener.onAsyncTaskListener(s); } }.execute(); } }
private 変数を三つ作成
private ListView listView; private ArrayAdapter<WebData> arrayAdapter; private HttpAccess httpAccess;
ListView と ArrayAdapter のインスタンスを作成 以降 onCreate にて。
listView = (ListView) MainActivity.this.findViewById(R.id.listView); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // クリックされたアイテムを取得 WebData mydata = (WebData) parent.getItemAtPosition(position); // LogCatに表示 Log.i("lightbox", mydata.name); Log.i("lightbox", mydata.link); // URL を開く Uri uri = Uri.parse(mydata.link); Intent intent = new Intent(Intent.ACTION_VIEW, uri); if (intent.resolveActivity(MainActivity.this.getPackageManager()) != null) { MainActivity.this.startActivity(intent); return; } } }); arrayAdapter = new ArrayAdapter<WebData>(MainActivity.this,android.R.layout.simple_list_item_1);
ListView に ArrayAdapter をセット listView.setAdapter(arrayAdapter); API を呼び出して結果をリストビューにセット 最新の Android では、https 通信以外では設定が必要なので、Firebase にJSON を登録してテストしました ( http://weather.livedoor.com/forecast/webservice/json/v1?city=270000 )
new HttpAccess("https://your-project-xxxxx.firebaseio.com/weather.json") .sendGet(new HttpAccess.OnAsyncTaskListener() { @Override public void onAsyncTaskListener(String s) { Gson gson = new Gson(); Weather weather = gson.fromJson(s, Weather.class); arrayAdapter.clear(); arrayAdapter.addAll(weather.pinpointLocations); } });
さらに Intent で第二画面 Android Studio : LiveDoor のお天気情報をリストビューに表示した後、第二画面で name を変更して第一画面で再表示する手順
|
【Androidの最新記事】
- Android のメニュー項目を条件が満たされた時のみ利用可能にする / onPrepareOptionsMenu
- Android Studio : LiveDoor のお天気情報をリストビューに表示した後、第二画面で name を変更して第一画面で再表示する手順
- Android の教科書到着しました。
- Android Studio をちょっと古い PC で使うと エミュレータが実行されなかった。
- Android Studio で、Failed to find target with hash string というエラーが出たら、Module の build.gradle を変更します
- Android Studio で Fragment の tools:layout で画面を指定して MainActivity には処理を書かないアプリケーション
- Android の SeekBar を縦方向で使用する設定
- Android 5.1(API 22) と Android 4.4(API 19) でのそれぞれの DatePicker ダイアログの扱い
- Android 5.1(API 22) と Android 4.4(API 19) でのそれぞれの DatePicker コントロールの扱い
- Android Studio でプロジェクトを読み込むと、Error : C:\Users\User\.gradle\caches... と表示されて gradle の処理が出来なくなる場合の対処
- Android Studio 1.4.1 : Android 純正 Data Binding テンプレート
- Android アプリ作成の基礎 : PDF で問題
- Android Chrome の 謎の(?) 241文字仕様 / 241文字以上のコンテンツは文字が大きく表示される
- Android Studio : 行の途中で改行した時のインデント数を 1 にする
- Android Studio : キャラクタセット
- Android Studio : 起動時にプロジェクトを読み込まない設定
- Android Studio の SDK ヘのパスの変更
- armeabi-v7a しか動かない、ちょっと古い PC で、どーしてもエミュレータが起動しなくてやった事( 動いた、万歳 )
- Android 5.1 + Pleiades( Luna ) + ADT Plugin
- Android 5.1 エミュレータ + Android Studio 1.1.0 実行イメージ