У меня есть вид статьи, в котором каждое мое сообщение будет отображать детали (представьте, что это сообщение в блоге), но я не могу разобрать данные, поэтому закрываю свое приложение вместо сведений о моих статьях.
code
ArticlesAdapter.kt
class ArticlesAdapter(val article : ArrayList<Article>) : RecyclerView.Adapter<ArticlesAdapter.ViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view: View =
LayoutInflater.from(parent.context).inflate(R.layout.fragment_articles, parent, false)
return ViewHolder(view)
}
override fun getItemCount(): Int {
return article.size
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.textView.text = article.get(position).name
Glide.with(holder.aImage.context)
.load(article.get(position).image)
.placeholder(R.drawable.placeholder2)
.error(R.drawable.placeholder2)
.fallback(R.drawable.placeholder2) // if load was null
.into(holder.aImage)
Log.e("ImageURL", "URL = " + article.get(position).image)
}
class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
var textView: TextView
var aImage: ImageView
init {
textView = itemView.findViewById(R.id.text_name)
aImage = itemView.findViewById(R.id.a_image)
}
}
}
ArticlesDetail.tk (my activity)
class ArticlesDetail : AppCompatActivity() {
private lateinit var appBarConfiguration: AppBarConfiguration
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.article_details)
callAPIDemo()
}
// api code
private fun callAPIDemo() {
val mySlugValue: String = intent.getStringExtra("my_slug")
Log.d("myslug in:", mySlugValue)
// Instantiate the RequestQueue.
val queue = Volley.newRequestQueue(this)
val url = "https://example.com/api/articles/$mySlugValue"
// Request a string response from the provided URL.
val stringRequest = StringRequest(
Request.Method.GET, url,
Response.Listener<String> { response ->
val list: ArrayList<Article> = ArrayList()
getPosts(response,list)
// here you will have the complete list of data in your "list" variable
article_det.layoutManager = LinearLayoutManager(this)
Log.d("my list", list.toString())
article_det.adapter = ArticlesAdapter(list)
},
Response.ErrorListener { error ->
//displaying the error in toast if occurrs
Toast.makeText(applicationContext, error.message, Toast.LENGTH_SHORT)
.show()
})
// Add the request to the RequestQueue.
queue.add(stringRequest)
}
fun getPosts(response: String,list:ArrayList<Article>) {
var jsonObject = JSONObject(response)
val jsonArray = jsonObject.getJSONArray("article")
for (i in 0 until jsonArray.length()) {
val jsonObject1 = jsonArray.getJSONObject(i)
var listingObject = Article(
jsonObject1.getInt("id"),
jsonObject1.getString("name"),
jsonObject1.getString("slug"),
jsonObject1.getString("image"),
jsonObject1.getString("body"),
jsonObject1.getString("icon"),
jsonObject1.getString("quote"),
jsonObject1.getString("video"),
jsonObject1.getString("user"),
jsonObject1.getString("created_at"),
jsonObject1.getString("updated_at")
)
list.add(listingObject)
}
}
}
Article.kt (my class)
data class Article (
val id: Int,
val name: String?,
val slug: String?,
val image: String?,
val body: String?,
val icon: String?,
val quote: String?,
val user: String?,
val video: String?,
val created_at: String?,
val updated_at: String?
)
тогда для просмотра у меня есть 2 файла:
article_details.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/article_det"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:textAlignment="center"
android:textSize="20sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
и fragment_articles.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="8dp">
<ImageView
android:id="@+id/a_image"
android:layout_width="80dp"
android:layout_height="80dp"
android:contentDescription="@string/image"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="@+id/text_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="20dp"
android:layout_marginEnd="20dp"
android:textSize="18sp"
app:layout_constraintBottom_toBottomOf="@+id/a_image"
app:layout_constraintStart_toEndOf="@+id/a_image"
app:layout_constraintTop_toTopOf="@+id/a_image" />
</androidx.constraintlayout.widget.ConstraintLayout>
Очевидно, что этот последний xml файл будет отредактирован в будущем для получения более подробной информации. моих статей, таких как body или user et c. но сейчас, чтобы проверить возвращенные данные, я думаю, что достаточно иметь имя и изображение статьи.
Данные
Вот так выглядят мои возвращенные данные в этом упражнении,
![one](https://i.stack.imgur.com/yJchD.png)
Ошибка
Caused by: org.json.JSONException: No value for article
at org.json.JSONObject.get(JSONObject.java:392)
at org.json.JSONObject.getJSONArray(JSONObject.java:587)
at ui.ArticlesDetail.ArticlesDetail.getPosts(ArticlesDetail.kt:63)
at ui.ArticlesDetail.ArticlesDetail$callAPIDemo$stringRequest$1.onResponse(ArticlesDetail.kt:43)
at ui.ArticlesDetail.ArticlesDetail$callAPIDemo$stringRequest$1.onResponse(ArticlesDetail.kt:18)
моя линия 63: val jsonArray = jsonObject.getJSONArray("article")
моя линия 43: getPosts(response,list)
моя строка 18: class ArticlesDetail : AppCompatActivity() {
Вопрос
- Есть идеи, какая часть моей функции
callAPIDemo()
или getPosts()
вызывает ошибку? - как я могу это исправить?
Обновление
мои json данные:
{
"id": 4,
"user": "...",
"name": "...",
"slug": "...",
"image": "...",
"body": "...",
"icon": null,
"quote": null,
"video": null,
"categories": [
{
"id": 10,
"name": "...",
"slug": "...",
"icon": "..",
"body": "...",
"image": "...",
"created_at": "2019-11-23 05:35:31",
"updated_at": "2019-11-26 11:25:17"
}
],
"created_at": "2019-11-23 07:34:10",
"updated_at": "2019-11-23 07:37:52"
}