не могу загрузить ShapeOfView в Picasso? - PullRequest
0 голосов
/ 20 октября 2019

Я занимаюсь разработкой новостей. Я загружаю imageurl, добавляя дополнительные и начинающие действия внутри onBindViewholder в recyclerviewadapter и получая URL-адрес изображения с использованием getextra в detailacctivity, затем я хочу загрузить этот URL-адрес с помощью Picasso, но я получаю следующую ошибку

imagerurl error

ниже класса адаптера, где я начинаю деятельность

@Suppress("UNREACHABLE_CODE")
class BBCSportAdapter(private val context: Context) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
    var articleList: List<Article> = listOf()
    companion object {
        const val urlKey = "urlKey"
        const val imageUrl = "imageUrl"
    }


    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.bbc_sport_item, null)
        return ViewHolder(view)
    }

    @SuppressLint("NewApi")
    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {

        (holder as ViewHolder).apply {
            when(position){
                0 -> {
                    header.visibility = ViewGroup.VISIBLE
                    item.visibility = ViewGroup.GONE

                    Picasso.get().load(articleList[position].urlToImage)
                        .into(bigImage)
                }
                else -> {
                    header.visibility = ViewGroup.GONE
                    item.visibility = ViewGroup.VISIBLE

                    articleTitle.text = articleList[position].title
                    articleSourceName.text = articleList[position].source.name
                    Picasso.get().load(articleList[position].urlToImage).into(image)
                    val input = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssX", Locale.getDefault())
                    val output = SimpleDateFormat("dd/MM/yyyy", Locale.getDefault())
                    var d = Date()
                    try {
                        d = input.parse(articleList[5].publishedAt)
                    } catch (e: ParseException) {
                        try {
                            val fallback = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.getDefault())
                            fallback.timeZone = TimeZone.getTimeZone("UTC")
                            d = fallback.parse(articleList[5].publishedAt)
                        } catch (e2: ParseException) {
                            // TODO handle error
                            val formatted = output.format(d)
                            val timelinePoint = LocalDateTime.parse(formatted)
                            val now = LocalDateTime.now()

                            val elapsedTime = Duration.between(timelinePoint, now)

                            println(timelinePoint)
                            println(now)
                            elapsedTime.toMinutes()

                            articleTime.text = "${elapsedTime.toMinutes()}"

                            holder.itemView.setOnClickListener { v->
                                val intent = Intent(v.context, DetailActivity::class.java)
                                intent.putExtra("urlKey", articleList[position].url)
                                intent.putExtra("imageUrl", articleList[position].urlToImage)
                                v.context.startActivity(intent)
                            }
                        }
                    }
                }
            }
        }
    }
    override fun getItemCount(): Int {
        return articleList.size
    }

    fun setMovieListItems(articleList: List<Article>) {
        this.articleList = articleList
        notifyDataSetChanged()
    }

    inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val image: ImageView = itemView.imageView
        val articleTitle: TextView = itemView.articleTitle
        val articleSourceName: TextView = itemView.articleSourceName
        val imageCategory: ImageView = itemView.imageCategory
        val articleTime: TextView = itemView.articleTime

        val bigImage = itemView.bigImage
        val header: CardView = itemView.header
        val item: CardView = itemView.item
    }
}

ниже DetailActivity.kt, где я получаю URL-адрес изображения

класс DetailActivity:AppCompatActivity () {

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_detail)
    val webView = findViewById<WebView>(R.id.article)
    val dioganalView = findViewById<DiagonalView>(R.id.diagonalView)
    val toolbar = findViewById<Toolbar>(R.id.toolbar)

    setSupportActionBar(toolbar)
    supportActionBar!!.setDisplayHomeAsUpEnabled(true)
    supportActionBar!!.setDisplayShowHomeEnabled(true)
    toolbar!!.setNavigationIcon(R.drawable.ic_arrow_white)
    val url = intent.extras!!.getString("urlKey")
    val imageUrls = intent.extras!!.getString("imageUrl")


    Picasso.get().load(imageUrls).into(dioganalView)

    webView!!.webViewClient = WebViewClient()

    webView!!.loadUrl(url)


}


override fun onSupportNavigateUp(): Boolean {
    onBackPressed()
    return true
}

inner class WebViewController : WebViewClient() {

    override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean {
        view.loadUrl(url)
        return true


    }
}

}

ниже сетевого интерфейса

interface SportNewsInterface {

@GET("v2/top-headlines?country=us&apiKey=da331087e3f3462bb534b3b0917cbee9")
fun getNews(): Call<SportNewsResponse>


@GET("/v2/top-headlines?sources=bbc-sport&apiKey=")
fun getBBCSport(): Call<SportNewsResponse>

companion object {

    var BASE_URL = "https://newsapi.org/"

    fun create(): SportNewsInterface {

        val interceptor = HttpLoggingInterceptor()
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY)

        val client = OkHttpClient.Builder()
            .addInterceptor(interceptor)
            .connectTimeout(60, TimeUnit.SECONDS)
            .readTimeout(60, TimeUnit.SECONDS)
            .writeTimeout(30, TimeUnit.SECONDS)
            .build()

        val retrofit = Retrofit.Builder()
            .addConverterFactory(GsonConverterFactory.create())
            .baseUrl(BASE_URL)
            .client(client)
            .build()
        return retrofit.create(SportNewsInterface::class.java)

    }
}

}

ниже NewsResponse.kt

data class SportNewsResponse(
    val articles: List<Article>,
    val status: String,
    val totalResults: Int
)

ниже Article.kt Класс модели

data class Article(
    val author: String,
    val content: String,
    val description: String,
    val publishedAt: String,
    val source: Source,
    val title: String,
    val url: String,
    val urlToImage: String
)

ниже jsonResponse

{
    "status": "ok",
    "totalResults": 10,
    "articles": [
        {
            "source": {
                "id": "bbc-sport",
                "name": "BBC Sport"
            },
            "author": "BBC Sport",
            "title": "Wicklow Brave dies after American Grand National fall at Far Hills",
            "description": "Wicklow Brave, one of racing's most popular and versatile horses, has died after a fall when leading in the American Grand National.",
            "url": "http://www.bbc.co.uk/sport/horse-racing/50114428",
            "urlToImage": "https://ichef.bbci.co.uk/onesport/cps/624/cpsprodpb/FCBC/production/_109300746_wicklow_brave.jpg",
            "publishedAt": "2019-10-20T05:53:56Z",
            "content": "Wicklow Brave won 17 races, including the 2016 Irish St Leger under Frankie Dettori\r\nWicklow Brave, one of racing's most popular and versatile horses, has died after a fall when leading in the American Grand National.\r\nThe 10-year-old, ridden by Paul Townend … [+1681 chars]"
        },
        {
            "source": {
                "id": "bbc-sport",
                "name": "BBC Sport"
            },
            "author": "BBC Sport",
            "title": "VAR is not being used correctly - Alan Shearer - BBC Sport",
            "description": "Match of the Day's Alan Shearer and Phil Neville discuss VAR and why referees have not being using pitch-side monitors this season.",
            "url": "http://www.bbc.co.uk/sport/av/football/50113314",
            "urlToImage": "https://m.files.bbci.co.uk/modules/bbc-morph-sport-page/3.3.2/images/bbc-sport-logo.png",
            "publishedAt": "2019-10-19T23:52:53.9831311Z",
            "content": null
        },
        {
            "source": {
                "id": "bbc-sport",
                "name": "BBC Sport"
            },
            "author": "BBC Sport",
            "title": "Mallorca 1-0 Real Madrid: Los Blancos' unbeaten run ended",
            "description": "Real Madrid suffer their first league defeat of the season as they are beaten by La Liga newcomers Mallorca on Saturday night.",
            "url": "http://www.bbc.co.uk/sport/football/50109887",
            "urlToImage": "https://ichef.bbci.co.uk/onesport/cps/624/cpsprodpb/E997/production/_109299795_gettyimages-1182111457.jpg",
            "publishedAt": "2019-10-19T21:20:29Z",
            "content": "Lago Junior's winner was his first ever La Liga goal\r\nReal Madrid suffered their first league defeat of the season as they lost at La Liga newcomers Mallorca on Saturday night.\r\nMallorca's Lago Junior scored the only goal of the game after just seven minutes … [+1828 chars]"
        },
        {
            "source": {
                "id": "bbc-sport",
                "name": "BBC Sport"
            },
            "author": "BBC Sport",
            "title": "Hawk-Eye company apologises for VAR confusion",
            "description": "The company which provides the Premier League's Video Assistant Referee technology has apologised to Tottenham and Watford fans after confusion during Saturday's game.",
            "url": "http://www.bbc.co.uk/sport/football/50112447",
            "urlToImage": "https://ichef.bbci.co.uk/onesport/cps/624/cpsprodpb/6463/production/_109299652_hi057416301.jpg",
            "publishedAt": "2019-10-19T21:04:11Z",
            "content": "The big screen initially adjusted the scoreline to show Tottenham's goal had been given - but also read 'no goal' in an error by Hawk-Eye\r\nThe company that provides the Premier League's video assistant referee (VAR) technology has apologised to Tottenham and … [+872 chars]"
        },
        {
            "source": {
                "id": "bbc-sport",
                "name": "BBC Sport"
            },
            "author": "BBC Sport",
            "title": "Crystal Palace 0-2 Manchester City: Champions reduce gap to Liverpool with comfortable win",
            "description": "Champions Manchester City narrow the gap on Premier League leaders Liverpool with victory over Crystal Palace at Selhurst Park.",
            "url": "http://www.bbc.co.uk/sport/football/50024394",
            "urlToImage": "https://ichef.bbci.co.uk/onesport/cps/624/cpsprodpb/3A29/production/_109298841_gettyimages-1182090752.jpg",
            "publishedAt": "2019-10-19T18:40:59Z",
            "content": "David Silva volleyed in Manchester City's second just 93 seconds after Gabriel Jesus' opener\r\nChampions Manchester City narrowed the gap on Premier League leaders Liverpool with a comfortable victory over Crystal Palace at Selhurst Park.\r\nTwo weeks on from a … [+2981 chars]"
        },
        {
            "source": {
                "id": "bbc-sport",
                "name": "BBC Sport"
            },
            "author": "BBC Sport",
            "title": "Rugby World Cup 2019: France v Wales (Sun)",
            "description": "Preview and match details as Wales take on France in the Rugby World Cup quarter-final match on Sunday in Oita.",
            "url": "http://www.bbc.co.uk/sport/rugby-union/50096013",
            "urlToImage": "https://ichef.bbci.co.uk/onesport/cps/624/cpsprodpb/B3BF/production/_105451064_northugetpa.jpg",
            "publishedAt": "2019-10-19T16:33:40Z",
            "content": "Media playback is not supported on this device\r\nWales v France: 'Being favourites comes with the territory' - Gatland\r\n<table><tr><th>2019 Rugby World Cup quarter-final: Wales v France</th></tr>\r\n<tr><td>Venue: Oita Stadium, Oita Prefecture Date: Sunday, 20 O… [+7666 chars]"
        },
        {
            "source": {
                "id": "bbc-sport",
                "name": "BBC Sport"
            },
            "author": "BBC Sport",
            "title": "Haringey Borough v Yeovil Town: FA Cup tie abandoned after reports of racial abuse",
            "description": "Haringey and Yeovil's FA Cup fourth qualifying round match is abandoned after reports of racial abuse aimed at Haringey's goalkeeper.",
            "url": "http://www.bbc.co.uk/sport/football/50111754",
            "urlToImage": "https://ichef.bbci.co.uk/onesport/cps/624/cpsprodpb/13590/production/_97584297_breaking_news.png",
            "publishedAt": "2019-10-19T16:27:21Z",
            "content": "Cameroonian goalkeeper Douglas Pajetat joined Haringey Borough from Margate in 2017\r\nHaringey Borough and Yeovil Town's FA Cup fourth qualifying round match has been abandoned, after reports of racial abuse aimed at Haringey's goalkeeper.\r\nYeovil were leading… [+985 chars]"
        },
        {
            "source": {
                "id": "bbc-sport",
                "name": "BBC Sport"
            },
            "author": "BBC Sport",
            "title": "England demolish Australia but All Blacks await in Rugby World Cup semi-finals",
            "description": "England impressed in their 40-16 win over Australia, but now face the test of holders New Zealand for a place in the World Cup final.",
            "url": "http://www.bbc.co.uk/sport/rugby-union/50110605",
            "urlToImage": "https://ichef.bbci.co.uk/onesport/cps/624/cpsprodpb/A45F/production/_109297024_farrell_getty_1-2.jpg",
            "publishedAt": "2019-10-19T15:03:21Z",
            "content": "Owen Farrell, speaking to the England team after the win over Australia, has now scored 154 points against the Wallabies, more than other northern hemisphere player\r\n<table><tr><th>Rugby World Cup semi-final: England v New Zealand</th></tr>\r\n<tr><td>Venue: In… [+6083 chars]"
        },
        {
            "source": {
                "id": "bbc-sport",
                "name": "BBC Sport"
            },
            "author": "BBC Sport",
            "title": "Hadleigh Parkes column: World Cup quarter-final v France and naked onsens",
            "description": "Hadleigh Parkes on the World Cup quarter-final against France and how his Wales team-mates have taken to Japan's naked hot springs.",
            "url": "http://www.bbc.co.uk/sport/rugby-union/50093523",
            "urlToImage": "https://ichef.bbci.co.uk/onesport/cps/624/cpsprodpb/10638/production/_105382176_hadleigh_parkes_option_1.png",
            "publishedAt": "2019-10-19T12:32:53Z",
            "content": "<table><tr><th>2019 Rugby World Cup quarter-final: Wales v France</th></tr>\r\n<tr><td>Venue: Oita Stadium, Oita Prefecture Date: Sunday, 20 October Kick-off: 08:15 BST</td></tr><tr><td>Coverage: Full commentary on every Wales game across BBC Radio Wales and Ra… [+5645 chars]"
        },
        {
            "source": {
                "id": "bbc-sport",
                "name": "BBC Sport"
            },
            "author": "BBC Sport",
            "title": "Rugby World Cup: Japan 'not planning to stop' at South Africa quarter-final",
            "description": "Japan are not satisfied by reaching their first World Cup quarter-final, says flanker Lappies Labuschagne before their tie against South Africa.",
            "url": "http://www.bbc.co.uk/sport/rugby-union/50107523",
            "urlToImage": "https://ichef.bbci.co.uk/onesport/cps/624/cpsprodpb/14013/production/_109293918_1180784208-d277a8231b89490c6aa7a6a4d12756e7a5a69029.jpg",
            "publishedAt": "2019-10-19T08:47:26Z",
            "content": "Japan beat Scotland to reach the quarter-finals for the first time\r\n<table><tr><th>Rugby World Cup quarter-final: Japan v South Africa</th></tr>\r\n<tr><td>Venue: Tokyo Stadium Date: Sunday, 20 October Kick-off: 11:15 BST</td></tr><tr><td>Coverage: Live comment… [+5097 chars]"
        }
    ]
}

Я использую следующую библиотеку https://github.com/florent37

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...