Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/203.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 尽管调用了api,但仍列出了全部空值_Android_Android Recyclerview_Kotlin - Fatal编程技术网

Android 尽管调用了api,但仍列出了全部空值

Android 尽管调用了api,但仍列出了全部空值,android,android-recyclerview,kotlin,Android,Android Recyclerview,Kotlin,我当时正在开发一个新闻应用程序,我对安卓系统还是相当陌生,只是最终理解了它的要点 我已经创建了一个自定义数组适配器,用于传入新闻数据对象。有了它,我想显示自定义对象。我遇到的问题是,由于我完全不理解的原因,数组适配器被传递了空值 val body = response?.body()?.string() val gson = GsonBuilder().create() val news = gson.fromJson(body, News::class.java) print(news)

我当时正在开发一个新闻应用程序,我对安卓系统还是相当陌生,只是最终理解了它的要点

我已经创建了一个自定义数组适配器,用于传入新闻数据对象。有了它,我想显示自定义对象。我遇到的问题是,由于我完全不理解的原因,数组适配器被传递了空值

val body = response?.body()?.string()

val gson = GsonBuilder().create()

val news = gson.fromJson(body, News::class.java)
print(news)
runOnUiThread {
    recycler_view_source_news.adapter = NewsAdapter(news)
}
但出于某种原因,它仍然表示,每当我测试运行应用程序时,列表都是空的

JSON
{“status”:“ok”,“totalResults”:20,“articles”:[{“source”:{“id”:null,“name”:“Espn.com”},“author”:null,“title”:“David Price,红袜队保持热身,在世界系列赛中以2-0领先”,“description”:“在寒冷的芬威公园,波士顿再次烤了道奇队,使其在世界系列赛中遥遥领先。”,“url”:"http://www.espn.com/mlb/story/_/id/25072767/mlb-boston-red-sox-stay-hot-lead-world-series-2-0,“urlToImage”:http://a4.espncdn.com/combiner/i?img=%2Fphoto%2F2018%2F1024%2Fr452337_1296x729_16%2D9.jpg,“发布日期”:“2018-10-25T03:26:30Z”,“内容”:波士顿——在芬威公园的两场寒冷的比赛让红袜队的球迷们感到非常温暖。现在道奇队不得不希望他们能在阳光明媚的加利福尼亚州迅速解冻。J.D.马丁内斯在第五局以两分单打结束了红袜队的另一场两场对决,lif…[+4034个字符]”,{“来源”:{“id”:“纽约时报”,“姓名”:“纽约时报”},”作者“:null,“title”:“看看我的行为有多好?”:在炸弹恐慌之后,特朗普尝试两党合作“,”description“:null,“url”:”https://www.nytimes.com/2018/10/24/us/politics/trump-bomb-cnn-obama-clintons.html“,“urlToImage”:null,“publishedAt”:“2018-10-25T03:11:15Z”,“content”:null},{“source”:{“id”:“华盛顿邮报”,“name”:“华盛顿邮报”},”作者:null,“标题”:“吉勒姆·德桑蒂斯的辩论演变成了一场个人争吵”,“描述”:null,“url”:”https://www.washingtonpost.com/politics/gillum-desantis-debate-descends-into-a-personal-brawl/2018/10/24/6d525d02-d7fb-11e8-aeb7-ddcad4a0a54e_story.html“,”urlToImage“:null,“publishedAt”:“2018-10-25T03:01:15Z”,“content:null},{”source“:{”id:null,”名称“:“Usnews.com”},“作者”:null,“标题”:“南卡罗来纳州“金条”市出售中奖彩票”,“描述”:null,“url”:https://www.usnews.com/news/top-news/articles/2018-10-24/city-in-south-carolinas-golden-strip-sells-winning-lottery-ticket“,”urlToImage“:null,“publishedAt”:“2018-10-25T02:08:03Z”,“content”:null},{”source“:{”id“:”cnbc“,”姓名“:”cnbc“}”,作者“:”Eustence Huang“,”标题“:”华尔街抛售后亚洲市场暴跌“,”说明“:”大中华区市场早盘下跌,而日本、韩国和澳大利亚的主要指数继续在负区间交易。”,“url”:"https://www.cnbc.com/2018/10/25/asia-markets-wall-street-sell-off-geopolitics-currencies-in-focus.html,“urlToImage”:https://fm.cnbc.com/applications/cnbc.com/resources/img/editorial/2018/08/21/105406893-1534805574505gettyimages-1015965684.1910x1000.jpeg,“发布日期”:“2018-10-25T01:58:01Z”,“内容”:亚洲股市在华尔街一夜暴跌后早盘暴跌。p组:第一个孩子“中国上证综指收复了早盘超过2.5%的部分跌幅,下跌1.32%。深圳证券交易所…[+1822 chars]”,{“来源”:{“id”:“路透社”,“姓名”:“路透社”},“作者”:“本·布兰查德”,“头衔”:“中国国防部长发誓绝不放弃任何领土”,“描述:”中国国防部长周四表示,“中国军队将“不惜一切代价”采取行动,挫败分裂台湾自治岛的企图,台湾自治岛被北京称为自己的领土。”,“url”:https://www.reuters.com/article/us-china-defence/chinas-defense-minister-vows-never-to-cede-any-territory-idUSKCN1MZ05L?il=0,“urlToImage”:https://s4.reutersmedia.net/resources/r/?m=02&d=20181025&t=2&i=1318395566&w=1200&r=LYNXNPEE9O08S“,”发布日期“:”2018-10-25T01:48:00Z“,”内容“:”北京(路透社)-中国军队将采取行动中国国防部长周四表示,“不惜一切代价”挫败分裂台湾自治岛的企图,北京声称台湾是自己的。最近美国的制裁令北京感到愤怒……[+2743 chars],{“来源:{“id”:null,“name”:“Fansided.com”},“author”:null,“title”:“乔恩·格鲁登坚持德里克·卡尔不会被交易”description“:null,“url”:https://fansided.com/2018/10/24/jon-gruden-insists-raiders-wont-trade-derek-carr/“,”urlToImage“:null,”publishedAt“:”2018-10-25T00:47:21Z“,”内容“:null},{”来源“:{”id“:”今日美国“,”姓名“:”今日美国“,”作者“:”乔尔·香农“,”标题“:”佛罗里达女孩密谋刺伤数十名学生,并喝受害者的血,警方说“,”描述:““两名佛罗里达女孩据称携带刀具到学校,希望杀死数十名学生,这是她们在观看恐怖电影后策划的阴谋的一部分。”,“url”:”https://www.usatoday.com/story/news/nation-now/2018/10/24/florida-girls-plotted-satanic-school-stabbings-police-say/1756036002/,“urlToImage”:https://www.gannett-cdn.com/-mm-/8ab8c917a9e61a657b162df0858ba461fc2f8299/c=827-812-1698-1304/local/-/media/USATODAY/genericmages/2014/07/25/1406322778000-FLORIDA.jpg?宽度=3200,高度=1680,适合度=crop,“publishedAt”:“2018-10-25T00:05:00Z”,“内容”:“佛罗里达州宣传片(照片:Shane Music)官方周三称,两名佛罗里达女孩将刀带到了她们的中学,据称她们企图以恶魔的理由杀害和残害同学。在这场被挫败的阴谋中,没有人受到伤害,这场阴谋被发现……[+2129个字符]”,{“来源”:{“id”:“纽约时报”,“姓名”:“纽约时报”},“作者”:null,“头衔”:”持枪歹徒向肯塔基州克罗格开枪后2人死亡,警方称,“描述”:空,“url”:”https://www.nytimes.com/2018/10/24/us/kroger-shooting-kentucky.html“,”urlToImage“:null,“publishedAt:”2018-10-24T23:39:27Z“,”内容“:null},{”来源“:{”id“:”华盛顿邮报“,”姓名“:”华盛顿邮报“}”,作者“:null,”标题“:”解释
     <manifest >
         ....
        <uses-permission android:name="android.permission.INTERNET"/>
         .....
     </manifest>
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
  <android.support.v7.widget.RecyclerView
     android:id="@+id/articles"
     android:layout_width="0dp"
     android:layout_height="0dp" app:layout_constraintBottom_toBottomOf="parent"
     app:layout_constraintLeft_toLeftOf="parent"
     app:layout_constraintRight_toRightOf="parent"
     android:layout_marginTop="8dp" 
     app:layout_constraintTop_toBottomOf="@+id/textView"/>
     <TextView
       android:text="Latest news"
       android:layout_width="0dp"
       android:layout_height="wrap_content"
       android:id="@+id/textView"
       android:background="#329d92"
       android:gravity="center"
       android:textSize="16sp"
       android:textColor="@android:color/white"
       android:padding="8dp"
       app:layout_constraintEnd_toEndOf="parent"
       app:layout_constraintStart_toStartOf="parent"
       app:layout_constraintTop_toTopOf="parent"/>

 </android.support.constraint.ConstraintLayout>
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
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:layout_width="match_parent"
app:cardElevation="6dp"
android:layout_marginTop="1dp"
android:layout_height="124dp">

  <android.support.constraint.ConstraintLayout android:layout_width="match_parent"
       android:layout_height="wrap_content">

     <ImageView
         android:layout_width="112dp"
         android:layout_height="112dp"
         android:contentDescription="@string/app_name"
         android:id="@+id/preview"
         app:layout_constraintTop_toTopOf="parent"           
         app:layout_constraintStart_toStartOf="parent"
         android:layout_marginLeft="8dp" android:layout_marginStart="8dp"
     />
     <TextView
         android:text="Title"
         android:layout_width="0dp"
         android:layout_height="wrap_content"
         android:layout_marginLeft="8dp" android:layout_marginStart="8dp"
         app:layout_constraintEnd_toEndOf="parent" android:layout_marginEnd="8dp"
         android:layout_marginRight="8dp"
         android:textSize="16sp"
         android:maxLines="1"
         android:id="@+id/title" app:layout_constraintStart_toEndOf="@+id/preview"
         app:layout_constraintTop_toTopOf="parent" android:layout_marginTop="16dp"/>
     <TextView
         android:text="Descriptions"
         android:layout_width="0dp"
         android:layout_height="wrap_content"
         android:id="@+id/descriptions"      
         app:layout_constraintStart_toEndOf="@+id/preview"
         android:layout_marginLeft="8dp" android:layout_marginStart="8dp"
         app:layout_constraintEnd_toEndOf="parent" android:layout_marginEnd="8dp"
         android:layout_marginRight="8dp"
         android:textSize="12sp"
         android:maxLines="2"
         android:ellipsize="end"
         app:layout_constraintHorizontal_bias="0.0" android:layout_marginTop="16dp"
         app:layout_constraintTop_toBottomOf="@+id/title"/>
     <TextView
         android:text="Source"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:id="@+id/source"
         android:maxLines="1"
         android:layout_marginBottom="8dp" 
         app:layout_constraintBottom_toBottomOf="parent"
         app:layout_constraintEnd_toEndOf="parent" android:layout_marginEnd="8dp"
         android:layout_marginRight="8dp"/>
   </android.support.constraint.ConstraintLayout>

 </android.support.v7.widget.CardView>
 class Source {
   var id: Any? = null
   var name: String? = null

   override fun toString(): String {
return "Source [id = $id, name = $name]"
   }
 }
 class Articles {
   var content: String? = null
   var publishedAt: String? = null
   var author: String? = null
   var urlToImage: String? = null
   var title: String? = null
   var source: Source? = null
   var description: String? = null
   var url: String? = null

   override fun toString(): String {
     return "Articles [content = $content, publishedAt = $publishedAt, author = $author, urlToImage = $urlToImage, title = $title, source = $source, description = $description, url = $url]"
   }
 }
   class Response {
     var articles: Array<Articles>? = null
     var totalResults: String? = null
     var status: String? = null

     override fun toString(): String {
return "Response [articles = $articles, totalResults = $totalResults, status = $status]"
     }
   }
  .....
import com.google.gson.Gson
import okhttp3.OkHttpClient
import okhttp3.Request
import java.lang.Exception
import com.google.gson.reflect.TypeToken
import com.squareup.picasso.Picasso
import kotlinx.android.synthetic.main.activity_main.articles

class MainActivity : AppCompatActivity() {

  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    articles.layoutManager = LinearLayoutManager(this)

    val url =
    "https://newsapi.org/v2/top-headlines?country=us&apiKey=973163c29a164868b20716a8d64a5851"
    OkHttpHandler().execute(url)
  }

  inner class OkHttpHandler : AsyncTask<String, String, String>() {
    override fun doInBackground(vararg params: String?): String? {

      val client = OkHttpClient()
      val request = Request.Builder().url(params[0]).build()
      try {
        val response = client.newCall(request).execute()
        val result = response.body()?.string()
        return result
      } catch (e: Exception) {
        e.printStackTrace()
      }
      return null
    }

    override fun onPostExecute(result: String?) {
      super.onPostExecute(result)
      println("result: $result")
      val type = object : TypeToken<Response>() {}.type
      val latestNews: Response = Gson().fromJson(result, type)
      articles.adapter = latestNews.articles?.let { ArticlesAdapter(it) }
    }
  }

  inner class ArticlesAdapter(var articles: Array<Articles>) :     RecyclerView.Adapter<ArticlesAdapter.ArticleHolder>() {
    override fun onCreateViewHolder(p0: ViewGroup, p1: Int): ArticleHolder {
      val view = LayoutInflater.from(p0.context).inflate(R.layout.row_article, p0, false)
      return ArticleHolder(view)
    }

    override fun getItemCount(): Int = articles.size

    override fun onBindViewHolder(holder: ArticleHolder, position: Int) {
      val article = articles[position]
      holder.title.text = article.title
      holder.description.text = article.description
      holder.source.text = "-${article.source?.name}"
      Picasso.get().load(article.urlToImage).into(holder.preview)
    }

    inner class ArticleHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
      var title = itemView.findViewById<TextView>(R.id.title)
      var description = itemView.findViewById<TextView>(R.id.descriptions)
      var source = itemView.findViewById<TextView>(R.id.source)
      var preview = itemView.findViewById<ImageView>(R.id.preview)
    }
  }

}