質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.48%
JSON

JSON(JavaScript Object Notation)は軽量なデータ記述言語の1つである。構文はJavaScriptをベースとしていますが、JavaScriptに限定されたものではなく、様々なソフトウェアやプログラミング言語間におけるデータの受け渡しが行えるように設計されています。

Kotlin

Kotlinは、ジェットブレインズ社のアンドリー・ブレスラフ、ドミトリー・ジェメロフが開発した、 静的型付けのオブジェクト指向プログラミング言語です。

Q&A

解決済

1回答

1139閲覧

kotlinのFragmentでJSONデータをspinnerに表示する

sin_cos_tan

総合スコア10

JSON

JSON(JavaScript Object Notation)は軽量なデータ記述言語の1つである。構文はJavaScriptをベースとしていますが、JavaScriptに限定されたものではなく、様々なソフトウェアやプログラミング言語間におけるデータの受け渡しが行えるように設計されています。

Kotlin

Kotlinは、ジェットブレインズ社のアンドリー・ブレスラフ、ドミトリー・ジェメロフが開発した、 静的型付けのオブジェクト指向プログラミング言語です。

0グッド

0クリップ

投稿2022/08/12 02:18

編集2022/08/12 02:39

前提

fragmentを利用しているSpinnerActivityで、JSONのvalueをspinnerに表示させたいのですが、spinnerにadapterをセットしている箇所でspinnerがnullになってしまい、セットされません。

実現したいこと

fragmentを利用しているSpinnerActivityで、JSONのvalueをspinnerに表示させたい。

発生している問題・エラーメッセージ

なし

該当のソースコード

Main_Activity.kt

1class MainActivity : AppCompatActivity() { 2 override fun onCreate(savedInstanceState: Bundle?) { 3 super.onCreate(savedInstanceState) 4 setContentView(R.layout.activity_main) 5 val btn = findViewById<Button>(R.id.btn) 6 7 btn.setOnClickListener { 8 CoroutineScope(Dispatchers.Default).launch { 9 val jText = getAPIData() 10 val fragment: Fragment = SpinnerActivity() 11 val bundle = Bundle() 12 bundle.putString("getTypes", jText) 13 fragment.arguments = bundle 14 15 //Fragment呼び出し 16 val transaction = supportFragmentManager.beginTransaction() 17 transaction.replace(R.id.container, fragment) 18 transaction.commit() 19 } 20 } 21 val textView = findViewById<TextView>(R.id.textResult) 22 val keyItem = intent.getStringExtra("test_key") 23 textView.text = keyItem 24 } 25 26 fun getAPIData() :String { 27 var jsonText ="" 28 try { 29 // linkにファイルが置かれたURLを指定 30 val link = "http://192.168.1.197:8000/getTypes" 31 32 //API叩く 33 //URL化→文字に変換→読み込み 34 val br = BufferedReader(InputStreamReader(URL(link).openStream())) 35 36 jsonText = br.readText()//テキストファイルを読み込み、文字列として返す 37 38 } catch (e: Exception) { 39 Log.e(localClassName, "Cancel", e) 40 } 41 return jsonText 42 }

SpinnerActivity.kt

1class SpinnerActivity : Fragment() { 2 var rootview: View? = null 3 override fun onCreateView( 4 inflater: LayoutInflater, container: ViewGroup?, 5 savedInstanceState: Bundle? 6 ): View? { 7 // レイアウトをここでViewとして作成 8 rootview = inflater.inflate(R.layout.activity_spinner, container, false) 9 return rootview 10 } 11 12 val spinner = rootview?.findViewById<Spinner>(R.id.spinner) 13 val list = ArrayList<Pair<String, String>>() 14 15 //渡された値を取得⇒spinnerに表示 16 override fun onResume() { 17 super.onResume() 18 val jsontext = requireArguments().getString("getTypes") 19 val json = JSONArray(jsontext) 20 for (i in 0 until json.length()) { 21 val jsons = json.getJSONObject(i) 22 //JSONのデータを文字列としてlistに追加 23 list.add(Pair(jsons.getString("typeId"), jsons.getString("typeName"))) 24 } 25 26 27 // スピナーにアダプターを設定 28 val adapter = KeyValuePair(this.requireContext(), android.R.layout.simple_spinner_item, list) 29 adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item) 30 if (spinner != null) { 31 spinner.adapter = adapter 32 } 33 34 val setBtn = rootview?.findViewById<Button>(R.id.button) 35 36 setBtn?.setOnClickListener { 37 val item = adapter.getItem(spinner!!.getSelectedItemPosition()) 38 val key = item?.first 39 val intent = Intent(activity, MainActivity::class.java) 40 intent.putExtra("test_key", key) 41 startActivity(intent) 42 } 43 } 44}

KeyValuePair.kt

1class KeyValuePair ( 2 context: Context?, 3 resourceId: Int, 4 list: ArrayList<Pair<String, String>> 5 6) : ArrayAdapter<Pair<String?, String?>?>( 7 context!!, 8 resourceId, 9 list as List<Pair<String?, String?>?> 10) { 11 // スピナー表示用view取得 12 //ArrayAdapterをオーバーライドしてカスタマイズ 13 override fun getView(pos: Int, convertView: View?, parent: ViewGroup): View { 14 val textView = super.getView(pos, convertView, parent) as TextView 15 textView.text = getItem(pos)!!.second 16 return textView 17 } 18 19 // スピナードロップダウン表示用view取得 20 override fun getDropDownView(pos: Int, convertView: View?, parent: ViewGroup?): View { 21 val textView = super.getDropDownView(pos, convertView, parent) as TextView 22 textView.text = getItem(pos)!!.second 23 return textView 24 } 25}

activity_main.xml

1<?xml version="1.0" encoding="utf-8"?> 2<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" 3 xmlns:app="http://schemas.android.com/apk/res-auto" 4 xmlns:tools="http://schemas.android.com/tools" 5 android:layout_width="match_parent" 6 android:layout_height="match_parent" 7 android:id="@+id/container" 8 tools:context=".MainActivity"> 9 10 <TextView 11 android:id="@+id/textResult" 12 android:layout_width="200dp" 13 android:layout_height="100dp" 14 android:text="" 15 android:textSize="20sp" 16 app:layout_constraintBottom_toBottomOf="parent" 17 app:layout_constraintEnd_toEndOf="parent" 18 app:layout_constraintHorizontal_bias="0.497" 19 app:layout_constraintStart_toStartOf="parent" 20 app:layout_constraintTop_toTopOf="parent" 21 app:layout_constraintVertical_bias="0.713" /> 22 23 <Button 24 android:id="@+id/btn" 25 android:layout_width="wrap_content" 26 android:layout_height="wrap_content" 27 android:text="選択画面へ" 28 app:layout_constraintBottom_toTopOf="@+id/textResult" 29 app:layout_constraintEnd_toEndOf="parent" 30 app:layout_constraintStart_toStartOf="parent" 31 app:layout_constraintTop_toTopOf="parent" 32 app:layout_constraintVertical_bias="0.129" 33 tools:ignore="MissingConstraints" /> 34 35</androidx.constraintlayout.widget.ConstraintLayout>

activity_spinner.xml

1<?xml version="1.0" encoding="utf-8"?> 2<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" 3 xmlns:app="http://schemas.android.com/apk/res-auto" 4 xmlns:tools="http://schemas.android.com/tools" 5 android:layout_width="match_parent" 6 android:layout_height="match_parent" 7 android:background="#AEFF9800"> 8 9 <Spinner 10 android:id="@+id/spinner" 11 android:layout_width="250dp" 12 android:layout_height="wrap_content" 13 android:backgroundTint="#009688" 14 android:scrollbarSize="4dp" 15 app:layout_constraintBottom_toBottomOf="parent" 16 app:layout_constraintEnd_toEndOf="parent" 17 app:layout_constraintHorizontal_bias="0.496" 18 app:layout_constraintStart_toStartOf="parent" 19 app:layout_constraintTop_toTopOf="parent" 20 app:layout_constraintVertical_bias="0.261" 21 tools:ignore="MissingConstraints" /> 22 23 <Button 24 android:id="@+id/button" 25 android:layout_width="wrap_content" 26 android:layout_height="wrap_content" 27 android:text="選択" 28 app:layout_constraintBottom_toBottomOf="parent" 29 app:layout_constraintEnd_toEndOf="parent" 30 app:layout_constraintStart_toStartOf="parent" 31 app:layout_constraintTop_toBottomOf="@+id/spinner" 32 app:layout_constraintVertical_bias="0.149" /> 33 34 35</androidx.constraintlayout.widget.ConstraintLayout>

補足情報(FW/ツールのバージョンなど)

まだ右も左もわからない初心者です。よろしくお願いいたします。

↓参考にしたサイトです。
https://qiita.com/Helmos/items/6b65d40d355379dc7ffa

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

hoshi-takanori

2022/08/14 02:00

エラーの原因は、val spinner = 〜 はプロパティなので、SpinnerActivity のインスタンスが作られる時に初期化されますが、その時点ではまだ onResume が呼ばれてなくて rootview が存在しないためですね。 また、いろいろツッコミどころがあって、 ・Fragment のサブクラスなのに SpinnerActivity という名前なのは気持ち悪い ・KeyValuePair の親クラスは ? を付けずに ArrayAdapter<Pair<String, String>> で良いのでは ・Android では CoroutineScope よりも lifecycleScope を使うべきだし、  getAPIData は withContext(Dispatchers.IO) とかを使ってバックグランドで実行すべき  (参考: https://qiita.com/b150005/items/dfaf1b5e619131905512 )
sin_cos_tan

2022/08/15 00:36

解決いたしました。ありがとうございます。 ツッコミもありがとうございます、勉強していきたいと思います。
guest

回答1

0

自己解決

エラーの原因は、val spinner = 〜 はプロパティなので、SpinnerActivity のインスタンスが作られる時に初期化されますが、その時点ではまだ onResume が呼ばれてなくて rootview が存在しないためですね。

override fun onResume() { super.onResume() val spinner = rootview?.findViewById<Spinner>(R.id.spinner) }

という事で、onResumeの中で生成したら解決しました。
hoshi-takanoriさんありがとうございました。

投稿2022/08/15 00:54

sin_cos_tan

総合スコア10

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.48%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問