我对从我网站上存储的 JSON 中获取值有疑问。总而言之,我使用了 Retrofit、ModelView 和 Repository 来获取这些值,但是我的 GridView 没有填充内容。没有错误,因为它符合完成条件。该文件的 URL 是:https://www.androidparadise.site/shop-categories/ 一个 Json 对象是:
[
{
"category": "Clothes",
"image": "R.drawable.ic_baseline_shopping",
"stores" : [
{"name": "Macy's", "url": "www.macys.com"},
{"name": "Amazon", "url": "www.amazon.com"}
]
}
]
// 使用 JSon to Kotlin 类插件来提供这个数据类
data class ShoppingCategoriesDataClass(
val category: String,
val image: Int,
val stores: List<Store>
)
interface ShoppingCategoriesInterface {
@GET("/shop-categories/")
suspend fun getAllCategoriesIcons() : Response<List<ShoppingCategoriesDataClass>>
}
我的 Appmodule 示例是:
private const val BASE_URL = "https://www.androidparadise.site"
@Singleton
@Provides
fun provideShoppingCategoriesApi() : ShoppingCategoriesInterface {
return Retrofit.Builder()
.baseUrl((BASE_URL))
.addConverterFactory(GsonConverterFactory.create())
.build()
.create(ShoppingCategoriesInterface::class.java)
}
ShopCategoryRepositoryImpl
class ShopCategoryRepositoryImpl(private val categoryApi:
ShoppingCategoriesInterface,
val app: Application): ShopCategoryRepository {
override suspend fun getAllCategoriesIcons():
Resource<List<ShoppingCategoriesDataClass>> {
return try{
val response = categoryApi.getAllCategoriesIcons()
val result = response.body()
if (response.isSuccessful && result != null){
Resource.Success(result)
}
else{
Resource.Error(response.message())
}
}catch(e: Exception){
Resource.Error(e.message ?: "An error occurred")
}
}
回收器视图适配器
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.tritongames.shopwishlist.R
import com.tritongames.shopwishlist.data.models.ShoppingCategoriesDataClass
import javax.inject.Inject
class RecyclerViewAdapter @Inject constructor(private var categoryList:
ArrayList<ShoppingCategoriesDataClass>):
RecyclerView.Adapter<RecyclerViewAdapter.RecylerViewHolder>() {
class RecylerViewHolder(itemView: View): RecyclerView.ViewHolder(itemView) {
var tv: TextView = itemView.findViewById(R.id.categoriesText)
var iv: ImageView = itemView.findViewById(R.id.categoriesPic)
}
override fun onCreateViewHolder(
parent: ViewGroup,
viewType: Int
): RecylerViewHolder {
val view: View =
LayoutInflater.from(parent.context).inflate(R.layout.wish_layout, parent)
return RecylerViewHolder(view)
}
override fun onBindViewHolder(holder: RecylerViewHolder, position: Int) {
holder.tv.text = categoryList[position].category
holder.iv.setImageResource(categoryList[position].image)
}
override fun getItemCount(): Int {
return categoryList.size
}
}
最后,名为 Shop 的 MainActivity
@AndroidEntryPoint
class Shop : AppCompatActivity() {
val recipientVM: RecipientViewModel by viewModels()
val shoppingVM: ShoppingDataViewModel by viewModels()
private lateinit var newCategoryList: ArrayList<ShoppingCategoriesDataClass>
@RequiresApi(Build.VERSION_CODES.N)
@Override
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_shop)
mName = ArrayList<String>()
spinName = findViewById(R.id.spinName)
lifecycleScope.launch() {
recipientVM.recipientLoad.collect{
event->
when(event){
is RecipientViewModel.RecipientLoadingEvent.Success ->{
nameAdapter = ArrayAdapter(this@Shop,
android.R.layout.simple_spinner_item,
recipientVM.loadRecipientNames()
)
}
is RecipientViewModel.RecipientLoadingEvent.Failure ->{
}`
`
else -> Unit
}
}
}
spinName?.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
@Override
override fun onItemSelected(parent: AdapterView<*>?, view: View?,
position: Int, id: Long) {
// TODO Auto-generated method stub
val selected_name: String = spinName!!.selectedItem.toString()
}
@Override
override fun onNothingSelected(parent: AdapterView<*>?) {
// TODO Auto-generated method stub
}
}
w1Text = findViewById(R.id.wish1Text)
w2Text = findViewById(R.id.wish2Text)
w3Text = findViewById(R.id.wish3Text)
category1 = findViewById(R.id.wish1Cat)
category2 = findViewById(R.id.wish2Cat)
category3 = findViewById(R.id.wish3Cat)
nextBTN = findViewById<Button>(R.id.buttonNext)
nextBTN?.setOnClickListener { // click to jump to next class WishList
val wlIntent = Intent(this@Shop, WishList::class.java)
startActivity(wlIntent)
}
lifecycleScope.launch {
shoppingVM.shopDataLoad.collect{event->
when(event){
is ShoppingDataViewModel.ShopDataLoadEvent.Success ->{
val recView: RecyclerView = findViewById(R.id.recViewGrid)
val catList = shoppingVM.getCategoryList()
val recViewAdapter = RecyclerViewAdapter( getUserData(catList))
val gLayoutManager = GridLayoutManager(this@Shop, 3)
recView.layoutManager = gLayoutManager
recView.adapter = recViewAdapter
}
is ShoppingDataViewModel.ShopDataLoadEvent.Error ->{
Resource.Error<ShoppingCategoriesDataClass>("Error Loading
Categories")
}
else -> Unit
}
}
}
val cDragListener1 = Category1DragEventListener()
val cDragListener2 = Category2DragEventListener()
val cDragListener3 = Category3DragEventListener()
category1?.setOnDragListener(cDragListener1)
category2?.setOnDragListener(cDragListener2)
category3?.setOnDragListener(cDragListener3)
cLongClickListener = CategoryOnItemLongClickListener()
gv?.onItemLongClickListener = cLongClickListener
}
private fun getUserData(catList: List<ShoppingCategoriesDataClass>):
ArrayList<ShoppingCategoriesDataClass> {
for (i in catList.indices){
val category = ShoppingCategoriesDataClass(catList[i].category,
catList[i].image, listOf())
newCategoryList.add(category)
}
return newCategoryList
}