尽管调用了api,但仍列出完整的null

时间:2018-10-25 03:21:34

标签: android android-recyclerview kotlin

我当时正在开发新闻应用程序,但对于android来说我还是很陌生,只是终于了解了它的要旨。

我创建了一个自定义阵列适配器,该适配器可传递新闻数据对象。这样,我想显示自定义对象。我遇到的问题是由于某种我根本不了解的原因,使用空值传递了数组适配器。

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)
}

但是出于某种原因对mu api调用提出了争议,每当我测试运行该应用程序时,它仍然说列表为空

JSON {"status":"ok","totalResults":20,"articles":[{"source":{"id":null,"name":"Espn.com"},"author":null,"title":"David Price, Red Sox stay hot, take 2-0 lead in World Series","description":"At a frigid Fenway Park, Boston roasted the Dodgers again to take a commanding World Series lead.","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","publishedAt":"2018-10-25T03:26:30Z","content":"BOSTON -- Two frigid games at Fenway Park left Red Sox fans feeling plenty warm. Now the Dodgers have to hope they can thaw quickly back in sunny California. J.D. Martinez capped yet another Red Sox two-out rally with a two-run single in the fifth inning, lif… [+4034 chars]"},{"source":{"id":"the-new-york-times","name":"The New York Times"},"author":null,"title":"'See How Nice I'm Behaving?': After Bomb Scares, Trump Tries Bipartisanship","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":"the-washington-post","name":"The Washington Post"},"author":null,"title":"Gillum-DeSantis debate descends into a personal brawl","description":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,"name":"Usnews.com"},"author":null,"title":"City in South Carolina's 'Golden Strip' Sells Winning Lottery Ticket","description":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","name":"CNBC"},"author":"Eustance Huang","title":"Asia markets tumble following Wall Street sell-off","description":"Markets in Greater China fell in the morning session while major indexes in Japan, South Korea and Australia continued to trade in negative territory.","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","publishedAt":"2018-10-25T01:58:01Z","content":"Stocks in Asia tumbled in morning trade following a plunge on Wall Street overnight. div > div.group > p:first-child\"> China's Shanghai composite retraced some of its early losses of more than 2.5 percent to trade down 1.32 percent. The Shenzhen comp… [+1822 chars]"},{"source":{"id":"reuters","name":"Reuters"},"author":"Ben Blanchard","title":"China's defense minister vows never to cede any territory","description":"China's army will take action \"at any cost\" to foil attempts to separate the self-ruled island of Taiwan, which Beijing claims as its own, the country's defense minister said on Thursday.","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","publishedAt":"2018-10-25T01:48:00Z","content":"BEIJING (Reuters) - China’s army will take action “at any cost” to foil attempts to separate the self-ruled island of Taiwan, which Beijing claims as its own, the country’s defense minister said on Thursday. Beijing has been infuriated by recent U.S. sanction… [+2743 chars]"},{"source":{"id":null,"name":"Fansided.com"},"author":null,"title":"Jon Gruden insists Derek Carr won't be traded","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","content":null},{"source":{"id":"usa-today","name":"USA Today"},"author":"Joel Shannon","title":"Florida girls plotted to stab dozens of students and drink victims' blood, police say","description":"Two Florida girls allegedly brought knives to school hoping to kill dozens of students as a part of a plot they hatched after watching scary movies.","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/GenericImages/2014/07/25/1406322778000-FLORIDA.jpg?width=3200&height=1680&fit=crop","publishedAt":"2018-10-25T00:05:00Z","content":"Florida State Promo (Photo: Shane Music) Two Florida girls brought knives to their middle school in an alleged attempt to kill and mutilate fellow students for satanic reasons, officials said Wednesday. No one was harmed in the foiled plot, which was discover… [+2129 chars]"},{"source":{"id":"the-new-york-times","name":"The New York Times"},"author":null,"title":"2 Dead After Gunman Opens Fire at Kentucky Kroger, Police Say","description":null,"url":"https://www.nytimes.com/2018/10/24/us/kroger-shooting-kentucky.html","urlToImage":null,"publishedAt":"2018-10-24T23:39:27Z","content":null},{"source":{"id":"the-washington-post","name":"The Washington Post"},"author":null,"title":"Explosive device targets George Soros amid escalating political attacks against billionaire hedge fund founder","description":null,"url":"https://www.washingtonpost.com/politics/explosive-device-targets-george-soros-amid-escalating-political-attacks-against-billionaire-hedge-fund-founder/2018/10/24/7d387982-d79b-11e8-aeb7-ddcad4a0a54e_story.html","urlToImage":null,"publishedAt":"2018-10-24T23:34:23Z","content":null},{"source":{"id":"abc-news","name":"ABC News"},"author":"Bopha Phorn","title":"Man sets home on fire after using blowtorch to kill spiders","description":"A man who minded his home while his parents away set his home on fire when he used a blowtorch to kill spiders, Fresno Fire official says.","url":"https://abcnews.go.com/US/man-sets-home-fire-blowtorch-kill-spiders/story?id=58716474","urlToImage":"https://s.abcnews.com/images/US/fire-spider-1-abc-er-181024_hpMain_16x9_992.jpg","publishedAt":"2018-10-24T23:05:00Z","content":"A man who was house-sitting for his parents set their home on fire when he used a blowtorch to kill spiders, according to authorities. Fire fighters responded to a 911 call about a fire Tuesday night at a home in Fresno, California. The tenant of a two-story … [+1657 chars]"},{"source":{"id":"the-new-york-times","name":"The New York Times"},"author":null,"title":"She Helped Save Her Husband's Life With CPR, Then Gave Birth to Their Son","description":"Ashley Goette was 39 weeks pregnant when she was awakened by her husband going into cardiac arrest.","url":"https://www.nytimes.com/2018/10/24/health/woman-saves-husband-cpr-birth.html","urlToImage":"https://static01.nyt.com/images/2018/10/25/health/25xp-cpr/merlin_145786836_e8dff15c-90e0-4363-8cfd-bcc207dd90c1-facebookJumbo.jpg","publishedAt":"2018-10-24T22:13:31Z","content":"The hospital sedated Mr. Goette and began lowering his body temperature in what would be a daylong procedure to induce mild hypothermia and reduce damage to the brain. “While they were doing that, it was the most terrifying thing to see,” Ms. Goette said. “Hi… [+1157 chars]"},{"source":{"id":"the-washington-post","name":"The Washington Post"},"author":null,"title":"Trump signs sweeping opioid bill. Expect to hear about it on the campaign trail.","description":null,"url":"https://www.washingtonpost.com/politics/trump-signs-sweeping-opioid-bill-expect-to-hear-about-it-on-the-campaign-trail/2018/10/24/1328598c-d7a9-11e8-aeb7-ddcad4a0a54e_story.html","urlToImage":null,"publishedAt":"2018-10-24T21:50:15Z","content":null},{"source":{"id":"the-washington-post","name":"The Washington Post"},"author":null,"title":"Extreme Category 5 Typhoon makes a devastating landfall in Northern Mariana Islands, a US territory","description":null,"url":"https://www.washingtonpost.com/energy-environment/2018/10/24/extreme-category-typhoon-yutu-makes-devastating-landfall-northern-mariana-islands-us-commonwealth/","urlToImage":null,"publishedAt":"2018-10-24T21:49:21Z","content":null},{"source":{"id":"the-washington-post","name":"The Washington Post"},"author":null,"title":"Judge orders Ga. officials to stop tossing absentee ballots over signatures","description":"The ruling provided a win to voting-rights activists, who said that a spike in absentee ballot rejections in suburban Gwinnett County amounted to voter suppression.","url":"https://www.washingtonpost.com/politics/judge-orders-ga-officials-to-stop-tossing-absentee-ballots-over-signatures/2018/10/24/9c5a5b06-d7bd-11e8-a10f-b51546b10756_story.html","urlToImage":"https://www.washingtonpost.com/resizer/m6oKED5arJO2NlIeDWXQ80wXNBc=/1484x0/arc-anglerfish-washpost-prod-washpost.s3.amazonaws.com/public/24XMQFWXY4I6RLVX3XFNJIFFJY.jpg","publishedAt":"2018-10-24T21:36:14Z","content":"A federal judge on Wednesday ordered Georgia election officials to stop summarily tossing absentee ballots because of mismatched signatures, delivering a crucial win to voting-rights advocates — and to Democratic gubernatorial candidate Stacey Abrams — less t… [+3792 chars]"},{"source":{"id":"the-new-york-times","name":"The New York Times"},"author":null,"title":"FBI Arrests White Nationalist Leader Who Fled the Country for Central America","description":"Robert Rundo is the founder of the Rise Above Movement, a violent California neo-Nazi gang. He and three other gang members were accused of inciting riots.","url":"https://www.nytimes.com/2018/10/24/us/fbi-white-nationalist-robert-paul-rundo-rise-above.html","urlToImage":"https://static01.nyt.com/images/2018/10/25/us/25rundo-print/25rundo-facebookJumbo.jpg","publishedAt":"2018-10-24T20:01:12Z","content":"Earlier this month, another four members of the Rise Above Movemen t — Benjamin Daley, Michael Miselis, Thomas Gillen and Cole White — were indicted on conspiracy to riot charges for attacking counterprotesters during last year’s Unite The Right rally in Char… [+1431 chars]"},{"source":{"id":"fox-news","name":"Fox News"},"author":"Christopher Carbone","title":"An entire Hawaiian island has vanished beneath the waves","description":"An entire island has vanished under the waves in the wake of Hurricane Walaka.","url":"https://www.foxnews.com/science/an-entire-hawaiian-island-has-vanished-beneath-the-waves","urlToImage":"https://static.foxnews.com/foxnews.com/content/uploads/2018/10/eastisland.jpg","publishedAt":"2018-10-24T18:20:56Z","content":"An entire Hawaiian island has vanished under the waves in the wake of Hurricane Walaka. East Island, which is part of the Papahanaumokuakea Marine National Monument and serves as a critical habitat for endangered Hawaiian monk seals and sea turtles, was basic… [+1926 chars]"},{"source":{"id":"cnn","name":"CNN"},"author":null,"title":"CNN evacuated in New York: How we covered the news","description":null,"url":"https://www.cnn.com/2018/10/24/media/cnn-coverage-of-evacuation/index.html","urlToImage":null,"publishedAt":"2018-10-24T17:17:56Z","content":null},{"source":{"id":"cnn","name":"CNN"},"author":"Brian Stelter, CNN Business","title":"NBC shows Megyn Kelly no mercy over blackface comments","description":"Some of the best known hosts at NBC News condemned their colleague Megyn Kelly's remarks about blackface Halloween costumes.","url":"https://www.cnn.com/2018/10/24/media/megyn-kelly-blackface-al-roker/index.html","urlToImage":"https://cdn.cnn.com/cnnnext/dam/assets/181024133610-kelly-roker-melvin-split-restricted-super-tease.jpg","publishedAt":"2018-10-24T12:35:17Z","content":null},{"source":{"id":"the-hill","name":"The Hill"},"author":"Aris Folley","title":"Jeff Flake doesn't know if he believes Kavanaugh weeks after confirmation","description":"Republican Sen. Jeff Flake (Ariz.) said he still isn’t sure he believes Supreme Court Justice Brett Kavanaugh’s denial of sexual assault allegations after voting to confirm the judge earlier this month.","url":"https://thehill.com/homenews/senate/412803-jeff-flake-still-doesnt-know-if-he-believes-kavanaugh","urlToImage":"https://thehill.com/sites/default/files/flakejeff_092818am3_lead.jpg","publishedAt":"2018-10-23T20:04:55Z","content":null}]}

模型类 https://imgur.com/a/4rNVwQY

体内物品计数 https://imgur.com/a/Z5g0B4t

1 个答案:

答案 0 :(得分:2)

尝试一下...

1。 AndroidManifest.xml

     <manifest >
         ....
        <uses-permission android:name="android.permission.INTERNET"/>
         .....
     </manifest>

2。 activity_main.xml

<?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>

3。 row_article.xml

<?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>

4。 Source.kt

 class Source {
   var id: Any? = null
   var name: String? = null

   override fun toString(): String {
return "Source [id = $id, name = $name]"
   }
 }

5。 Articles.kt

 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]"
   }
 }

6。响应.kt

   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]"
     }
   }

7。 MainActivity.kt

  .....
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)
    }
  }

}

8。结果

The final look

9。编码愉快...