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

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

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

RSS(Really Simple Syndication)はブログのエントリやニュースの見出し、標準のフォーマットの音声やビデオなどを発行するために使われるウェブフィードのフォーマットの集合体です。

Android Studio

Android Studioは、 Google社によって開発された、 Androidのネイティブアプリケーション開発に特化した統合開発ツールです。

Kotlin

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

Q&A

0回答

1641閲覧

Kotlinでのローダーの呼び出し方

hego

総合スコア1

RSS

RSS(Really Simple Syndication)はブログのエントリやニュースの見出し、標準のフォーマットの音声やビデオなどを発行するために使われるウェブフィードのフォーマットの集合体です。

Android Studio

Android Studioは、 Google社によって開発された、 Androidのネイティブアプリケーション開発に特化した統合開発ツールです。

Kotlin

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

0グッド

0クリップ

投稿2020/05/31 03:41

RSSリーダーアプリの作成で参考書を見ながらコードを打ち込んでいるのですが途中でエミュレータを起動したら繰り返しアプリが停止していますと出てしまいます。
参考書のローダーを呼び出すコードが
LoaderManager.initLoader(1,null,this)
なのですが自分なりに調べた所現在は使えないという事で
LoaderManager.getInstance(this).initLoader(1,null,this)
に変更しエラーも消えたのですが繰り返しアプリが停止してしまい行き詰まっています。
試しにローダーを呼び出すコードを消してエミュレーターを起動させるとアプリは停止せず何も無い画面が表示されました。
どうすれば正常に起動するでしょうか。ご教授お願いいたします。

MainActivity

html

1package com.example.rssreader 2 3import android.support.v7.app.AppCompatActivity 4import android.os.Bundle 5import android.support.v4.app.LoaderManager 6import android.support.v4.content.Loader 7import android.support.v7.widget.GridLayoutManager 8import android.support.v7.widget.RecyclerView 9 10 11class MainActivity : AppCompatActivity() , LoaderManager.LoaderCallbacks<Rss> { 12 13 override fun onCreate(savedInstanceState: Bundle?) { 14 super.onCreate(savedInstanceState) 15 setContentView(R.layout.activity_main) 16 17 //ローダーを呼び出す 18 LoaderManager.getInstance(this).initLoader(0,null,this) 19 } 20 //ローダーが要求される時に呼ばれる 21 override fun onCreateLoader(id: Int, args: Bundle?) = RssLoader(this) 22 23 //ローダーで行った処理が終了した時に呼ばれる 24 override fun onLoadFinished(loader: Loader<Rss>, data: Rss?) { 25 //処理結果がnullではない場合 26 if(data != null){ 27 //RecycleViewをレイアウトから探す 28 val recyclerView = findViewById<RecyclerView>(R.id.articles) 29 30 //RSSの記事一覧アダプター 31 val adapter = ArticlesAdapter(this,data.articles){article -> 32 //記事をタップした時の処理 33 } 34 recyclerView.adapter = adapter 35 36 //グリッド表示するレイアウトマネジャー 37 val layoutManager = GridLayoutManager(this,2) 38 39 recyclerView.layoutManager = layoutManager 40 } 41 } 42 43 //ローダーがリセットされた時に呼ばれる 44 override fun onLoaderReset(loader: Loader<Rss>) { 45 } 46 47}

ArticlesAdapter

html

1package com.example.rssreader 2 3import android.content.Context 4import android.support.v7.widget.RecyclerView 5import android.view.LayoutInflater 6import android.view.View 7import android.view.ViewGroup 8import android.widget.TextView 9 10class ArticlesAdapter( 11 private val context: Context, 12 private val articles: List<Article>, 13 private val onArticleClicked: (Article) -> Unit) 14 :RecyclerView.Adapter<ArticlesAdapter.ArticleViewHolder>() { 15 16 private val inflater = LayoutInflater.from(context) 17 18 override fun getItemCount() = articles.size 19 20 override fun onCreateViewHolder(parent: ViewGroup,viewType: Int): 21 ArticleViewHolder { 22 //viewを生成する 23 val view = inflater.inflate(R.layout.grid_article_cell,parent,false) 24 //ViewHolderを生成する 25 val viewHolder = ArticleViewHolder(view) 26 27 //Viewタップ時の処理 28 view.setOnClickListener { 29 //タップされた記事の位置 30 val position = viewHolder.adapterPosition 31 //タップされた位置に応じた記事を 32 val article = articles[position] 33 } 34 return viewHolder 35 } 36 //Viewに表示すべき値を設定する 37 override fun onBindViewHolder(holder: ArticleViewHolder, position: Int) { 38 //アダプター中の位置に応じた記事を得る 39 val article = articles[position] 40 //記事のタイトルを設定する 41 holder.title.text = article.title 42 //記事の発効日を設定する 43 holder.pubData.text = context.getString(R.string.pubDate,article.pubDate) 44 } 45 //ビューホルダー 46 class ArticleViewHolder(view: View) : RecyclerView.ViewHolder(view) { 47 val title = view.findViewById<TextView>(R.id.title) 48 val pubData = view.findViewById<TextView>(R.id.pubDate) 49 } 50}

RSS

html

1package com.example.rssreader 2 3import android.content.Context 4import android.support.v4.content.AsyncTaskLoader 5import org.w3c.dom.NodeList 6import java.io.InputStream 7import java.text.SimpleDateFormat 8import java.util.* 9import javax.xml.parsers.DocumentBuilderFactory 10import javax.xml.xpath.XPathConstants 11import javax.xml.xpath.XPathFactory 12 13//RSSの各記事を表すデータクラス 14data class Article(val title: String,val link: String, val pubDate: Date) 15 16//RSSを表現するデータクラス 17data class Rss(val title: String, 18 val pubDate: Date,val articles: List<Article>) 19 20fun parseRss(stream: InputStream) : Rss{ 21 22 //XMLをDOMオブジェクトに変換する 23 val doc = DocumentBuilderFactory.newInstance().newDocumentBuilder() 24 doc.parse(stream) 25 stream.close() 26 27 //XPathを生成する 28 val xPath = XPathFactory.newInstance().newXPath() 29 30 //RSS2.0の日付書式である、RFC1123をDate型に変換する為のクラス 31 val formatter = SimpleDateFormat("EEE,dd MMM yyyy HH:mm:ss z",Locale.US) 32 33 //チャンネル内の<Item>要素を全て取り出す 34 val items = xPath.evaluate("/rss/channel//item",doc,XPathConstants.NODESET) 35 as NodeList 36 37 //RSSフィード内の記事一覧 38 val articles = arrayListOf<Article>() 39 40 //<item>の要素ごとに繰り返す 41 for(i in 0 until items.length){ 42 val item = items.item(i) 43 44 //Articleオブジェクトにまとめる 45 val article = Article( 46 title = xPath.evaluate("./title/text()",item), 47 link = xPath.evaluate("./link/text()",item), 48 pubDate = formatter.parse(xPath.evaluate("./pubDate/text()",item))) 49 50 articles.add(article) 51 } 52 //RSSオブジェクトにまとめて返す 53 return Rss(title = xPath.evaluate("/rss/channel/title/text()",doc), 54 pubDate = formatter.parse(xPath.evaluate("/rss/channel/pubDate/text()",doc)), 55 articles = articles) 56} 57 58class RssLoader(context: Context) : AsyncTaskLoader<Rss>(context) { 59 private var cache : Rss? = null 60 61 //このローダーがバックグラウンドで行う処理 62 override fun loadInBackground(): Rss? { 63 //HTTPでXMLを取得する 64 val response = httpGet("https://www.sbbit.jp/rss/HotTopics.rss") 65 66 if(response != null){ 67 //取得したらパースして返す 68 return parseRss(response) 69 } 70 return null 71 } 72 73 //コールバックの前に通る処理 74 override fun deliverResult(data: Rss?){ 75 //破棄をされていたら結果を返さない 76 if(isReset || data == null) return 77 //結果をキャッシュする 78 cache = data 79 super.deliverResult(data) 80 } 81 82 override fun onStartLoading() { 83 //キャッシュがあるなら、キャッシュを返す 84 if(cache != null){ 85 deliverResult(cache) 86 } 87 //コンテンツが変化している場合やキャッシュがない場合は、バックグラウンド処理を行う 88 if(takeContentChanged() || cache == null){ 89 forceLoad() 90 } 91 } 92 //ローダーが停止する前に呼ばれる処理 93 override fun onStopLoading() { 94 cancelLoad() 95 } 96 97 override fun onReset() { 98 super.onReset() 99 onStopLoading() 100 cache = null 101 } 102} 103

Http

html

1package com.example.rssreader 2 3import java.io.BufferedInputStream 4import java.io.InputStream 5import java.net.URL 6import javax.net.ssl.HttpsURLConnection 7 8fun httpGet(url: String): InputStream?{ 9 10 //通信接続用のオブジェクトを作る 11 val con = URL(url).openConnection() as HttpsURLConnection 12 13 //接続設定を作る 14 con.apply { 15 requestMethod = "GET" //メソッド 16 connectTimeout = 3000 //接続のタイムアウト 17 readTimeout = 5000 //読み込みのタイムアウト 18 instanceFollowRedirects = true //リダイレクトの許可 19 } 20 21 //接続する 22 con.connect() 23 24 //ステータスコードの確認 25 if(con.responseCode in 200..299){ 26 //成功したら、レスポンスの入力ストリームを、BufferedInputStreamとして返す 27 return BufferedInputStream(con.inputStream) 28 } 29 30 return null 31}

activity_main.xml

html

1<?xml version="1.0" encoding="utf-8"?> 2<android.support.constraint.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 tools:context=".MainActivity"> 8 9 <android.support.v7.widget.RecyclerView 10 android:id="@+id/articles" 11 android:layout_width="0dp" 12 android:layout_height="0dp" 13 app:layout_constraintBottom_toBottomOf="parent" 14 app:layout_constraintEnd_toEndOf="parent" 15 app:layout_constraintStart_toStartOf="parent" 16 app:layout_constraintTop_toTopOf="parent" /> 17</android.support.constraint.ConstraintLayout>

grid_article_cell.xml

html

1<?xml version="1.0" encoding="utf-8"?> 2<android.support.constraint.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="wrap_content"> 7 8 <TextView 9 android:id="@+id/title" 10 android:layout_width="0dp" 11 android:layout_height="wrap_content" 12 android:layout_marginStart="8dp" 13 android:layout_marginTop="8dp" 14 android:layout_marginEnd="8dp" 15 android:layout_marginBottom="8dp" 16 android:text="@string/news_title" 17 android:textAppearance="@style/TextAppearance.AppCompat.Medium" 18 app:layout_constraintBottom_toBottomOf="parent" 19 app:layout_constraintEnd_toEndOf="parent" 20 app:layout_constraintStart_toStartOf="parent" 21 app:layout_constraintTop_toTopOf="parent" 22 app:layout_constraintVertical_bias="0.45" /> 23 24 <TextView 25 android:id="@+id/pubDate" 26 android:layout_width="wrap_content" 27 android:layout_height="wrap_content" 28 android:layout_marginTop="8dp" 29 android:layout_marginEnd="8dp" 30 android:text="@string/pubDate" 31 android:textAppearance="@style/TextAppearance.AppCompat.Small" 32 app:layout_constraintBottom_toBottomOf="parent" 33 app:layout_constraintEnd_toEndOf="parent" 34 app:layout_constraintHorizontal_bias="1.0" 35 app:layout_constraintStart_toStartOf="parent" 36 app:layout_constraintTop_toBottomOf="@+id/title" /> 37</android.support.constraint.ConstraintLayout>

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

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

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

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

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

guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

まだ回答がついていません

会員登録して回答してみよう

アカウントをお持ちの方は

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

ただいまの回答率
85.48%

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

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

質問する

関連した質問