Kotlin AndroidStudio 类型不匹配
Kotlin AndroidStudio Type Mismatch
我的代码出现了一些错误,Type mismatch. Required : FavoriteData, Found : FavoriteData?
行 dataFavorite = activity!!.intent.getParcelableExtra(EXTRA_NOTE) as FavoriteData
和 Type mismatch. Required : UserData, Found : UserData?
行 dataUser = activity!!.intent.getParcelableExtra(EXTRA_DATA) as UserData
.
这是我的 class :
class FollowersFragment : Fragment() {
private var listUser: ArrayList<UserData> = ArrayList()
private lateinit var adapter: FollowersAdapter
private var favorite: FavoriteData? = null
private lateinit var dataFavorite: FavoriteData
private lateinit var dataUser: UserData
private lateinit var progressBarFollowers: ProgressBar
private lateinit var recyclerViewFollowers: RecyclerView
companion object {
private val TAG = FollowersFragment::class.java.simpleName
const val EXTRA_DATA = "extra_data"
const val EXTRA_NOTE = "extra_note"
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_followers, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
progressBarFollowers = getView()!!.findViewById(R.id.progressBarFollowers)
recyclerViewFollowers = getView()!!.findViewById(R.id.recyclerViewFollowers)
adapter = FollowersAdapter(listUser)
listUser.clear()
favorite = activity!!.intent.getParcelableExtra(UserDetailActivity.EXTRA_NOTE)
if (favorite != null) {
dataFavorite = activity!!.intent.getParcelableExtra(EXTRA_NOTE) as FavoriteData
showUserFollowers(dataFavorite.username.toString())
} else {
dataUser = activity!!.intent.getParcelableExtra(EXTRA_DATA) as UserData
showUserFollowers(dataUser.username.toString())
}
}
private fun showUserFollowers(id: String) {
progressBarFollowers.visibility = View.VISIBLE
val client = AsyncHttpClient()
client.addHeader("User-Agent", "request")
client.addHeader("Authorization", "token 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")
val url = "https://api.github.com/users/$id/followers"
client.get(url, object : AsyncHttpResponseHandler(){
override fun onSuccess(
statusCode: Int,
headers: Array<Header>,
responseBody: ByteArray
) {
progressBarFollowers.visibility = View.INVISIBLE
val result = String(responseBody)
Log.d(TAG, result)
try {
val jsonArray = JSONArray(result)
for (i in 0 until jsonArray.length()) {
val jsonObject = jsonArray.getJSONObject(i)
val username: String = jsonObject.getString("login")
showUserDetail(username)
}
} catch (e: Exception) {
Toast.makeText(activity, e.message, Toast.LENGTH_SHORT)
.show()
e.printStackTrace()
}
}
override fun onFailure(
statusCode: Int,
headers: Array<Header>,
responseBody: ByteArray,
error: Throwable
) {
progressBarFollowers.visibility = View.INVISIBLE
val errorMessage = when (statusCode) {
401 -> "$statusCode : Bad Request"
403 -> "$statusCode : Forbidden"
404 -> "$statusCode : Not Found"
else -> "$statusCode : ${error.message}"
}
Toast.makeText(activity, errorMessage, Toast.LENGTH_LONG)
.show()
}
})
}
private fun showUserDetail(id: String){
progressBarFollowers.visibility = View.VISIBLE
val client = AsyncHttpClient()
client.addHeader("User-Agent", "request")
client.addHeader("Authorization", "token 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")
val url = "https://api.github.com/users/$id"
client.get(url, object : AsyncHttpResponseHandler(){
override fun onSuccess(statusCode: Int, headers: Array<Header>, responseBody: ByteArray) {
progressBarFollowers.visibility = View.INVISIBLE
val result = String(responseBody)
Log.d(TAG, result)
try {
val jsonObject = JSONObject(result)
val username: String = jsonObject.getString("login").toString()
val name: String = jsonObject.getString("name").toString()
val avatar: String = jsonObject.getString("avatar_url").toString()
val company: String = jsonObject.getString("company").toString()
val location: String = jsonObject.getString("location").toString()
val repository: String? = jsonObject.getString("public_repos")
val followers: String? = jsonObject.getString("followers")
val following: String? = jsonObject.getString("following")
listUser.add(
UserData(
username,
name,
avatar,
company,
location,
repository,
followers,
following
)
)
showRecyclerList()
} catch (e: Exception) {
Toast.makeText(activity, e.message, Toast.LENGTH_SHORT)
.show()
e.printStackTrace()
}
}
override fun onFailure(statusCode: Int, headers: Array<Header>, responseBody: ByteArray, error: Throwable) {
progressBarFollowers.visibility = View.INVISIBLE
val errorMessage = when (statusCode) {
401 -> "$statusCode : Bad Request"
403 -> "$statusCode : Forbidden"
404 -> "$statusCode : Not Found"
else -> "$statusCode : ${error.message}"
}
Toast.makeText(activity, errorMessage, Toast.LENGTH_LONG)
.show()
}
})
}
private fun showRecyclerList() {
recyclerViewFollowers.layoutManager = LinearLayoutManager(activity)
val listAdapter = FollowersAdapter(followerFilter)
recyclerViewFollowers.adapter = adapter
listAdapter.setOnItemClickCallback(object : FollowersAdapter.OnItemClickCallback{
override fun onItemClicked(UserData: UserData) {
}
})
}
}
我不知道如何解决这个问题,感谢您的关注:)
我只是从你的问题中举出一个例子:
您已声明:
private lateinit var dataFavorite: FavoriteData
这意味着 FavoriteData
不能被赋予空值。
因此,当您从 parcelable 中获取数据时,由于某种原因它可能为 null,因此它为您提供了一个类型 FavoriteData?
,该类型可为 null,无法直接分配。
有两种方法可以解决这个问题
1.) 添加 Non-Null 断言 (!!) 如果数据为 NULL
将抛出 NullPointter
dataFavorite = (intent.getParcelableExtra(YOUR_KEY) as FavoriteData?)!!
2.) 使您的变量可空
private var dataFavorite: FavoriteData? = null
指定为
dataFavorite = intent.getParcelableExtra("") as FavoriteData?
根据您的用例进行选择,其他人也可以这样做
我的代码出现了一些错误,Type mismatch. Required : FavoriteData, Found : FavoriteData?
行 dataFavorite = activity!!.intent.getParcelableExtra(EXTRA_NOTE) as FavoriteData
和 Type mismatch. Required : UserData, Found : UserData?
行 dataUser = activity!!.intent.getParcelableExtra(EXTRA_DATA) as UserData
.
这是我的 class :
class FollowersFragment : Fragment() {
private var listUser: ArrayList<UserData> = ArrayList()
private lateinit var adapter: FollowersAdapter
private var favorite: FavoriteData? = null
private lateinit var dataFavorite: FavoriteData
private lateinit var dataUser: UserData
private lateinit var progressBarFollowers: ProgressBar
private lateinit var recyclerViewFollowers: RecyclerView
companion object {
private val TAG = FollowersFragment::class.java.simpleName
const val EXTRA_DATA = "extra_data"
const val EXTRA_NOTE = "extra_note"
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_followers, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
progressBarFollowers = getView()!!.findViewById(R.id.progressBarFollowers)
recyclerViewFollowers = getView()!!.findViewById(R.id.recyclerViewFollowers)
adapter = FollowersAdapter(listUser)
listUser.clear()
favorite = activity!!.intent.getParcelableExtra(UserDetailActivity.EXTRA_NOTE)
if (favorite != null) {
dataFavorite = activity!!.intent.getParcelableExtra(EXTRA_NOTE) as FavoriteData
showUserFollowers(dataFavorite.username.toString())
} else {
dataUser = activity!!.intent.getParcelableExtra(EXTRA_DATA) as UserData
showUserFollowers(dataUser.username.toString())
}
}
private fun showUserFollowers(id: String) {
progressBarFollowers.visibility = View.VISIBLE
val client = AsyncHttpClient()
client.addHeader("User-Agent", "request")
client.addHeader("Authorization", "token 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")
val url = "https://api.github.com/users/$id/followers"
client.get(url, object : AsyncHttpResponseHandler(){
override fun onSuccess(
statusCode: Int,
headers: Array<Header>,
responseBody: ByteArray
) {
progressBarFollowers.visibility = View.INVISIBLE
val result = String(responseBody)
Log.d(TAG, result)
try {
val jsonArray = JSONArray(result)
for (i in 0 until jsonArray.length()) {
val jsonObject = jsonArray.getJSONObject(i)
val username: String = jsonObject.getString("login")
showUserDetail(username)
}
} catch (e: Exception) {
Toast.makeText(activity, e.message, Toast.LENGTH_SHORT)
.show()
e.printStackTrace()
}
}
override fun onFailure(
statusCode: Int,
headers: Array<Header>,
responseBody: ByteArray,
error: Throwable
) {
progressBarFollowers.visibility = View.INVISIBLE
val errorMessage = when (statusCode) {
401 -> "$statusCode : Bad Request"
403 -> "$statusCode : Forbidden"
404 -> "$statusCode : Not Found"
else -> "$statusCode : ${error.message}"
}
Toast.makeText(activity, errorMessage, Toast.LENGTH_LONG)
.show()
}
})
}
private fun showUserDetail(id: String){
progressBarFollowers.visibility = View.VISIBLE
val client = AsyncHttpClient()
client.addHeader("User-Agent", "request")
client.addHeader("Authorization", "token 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")
val url = "https://api.github.com/users/$id"
client.get(url, object : AsyncHttpResponseHandler(){
override fun onSuccess(statusCode: Int, headers: Array<Header>, responseBody: ByteArray) {
progressBarFollowers.visibility = View.INVISIBLE
val result = String(responseBody)
Log.d(TAG, result)
try {
val jsonObject = JSONObject(result)
val username: String = jsonObject.getString("login").toString()
val name: String = jsonObject.getString("name").toString()
val avatar: String = jsonObject.getString("avatar_url").toString()
val company: String = jsonObject.getString("company").toString()
val location: String = jsonObject.getString("location").toString()
val repository: String? = jsonObject.getString("public_repos")
val followers: String? = jsonObject.getString("followers")
val following: String? = jsonObject.getString("following")
listUser.add(
UserData(
username,
name,
avatar,
company,
location,
repository,
followers,
following
)
)
showRecyclerList()
} catch (e: Exception) {
Toast.makeText(activity, e.message, Toast.LENGTH_SHORT)
.show()
e.printStackTrace()
}
}
override fun onFailure(statusCode: Int, headers: Array<Header>, responseBody: ByteArray, error: Throwable) {
progressBarFollowers.visibility = View.INVISIBLE
val errorMessage = when (statusCode) {
401 -> "$statusCode : Bad Request"
403 -> "$statusCode : Forbidden"
404 -> "$statusCode : Not Found"
else -> "$statusCode : ${error.message}"
}
Toast.makeText(activity, errorMessage, Toast.LENGTH_LONG)
.show()
}
})
}
private fun showRecyclerList() {
recyclerViewFollowers.layoutManager = LinearLayoutManager(activity)
val listAdapter = FollowersAdapter(followerFilter)
recyclerViewFollowers.adapter = adapter
listAdapter.setOnItemClickCallback(object : FollowersAdapter.OnItemClickCallback{
override fun onItemClicked(UserData: UserData) {
}
})
}
}
我不知道如何解决这个问题,感谢您的关注:)
我只是从你的问题中举出一个例子:
您已声明:
private lateinit var dataFavorite: FavoriteData
这意味着 FavoriteData
不能被赋予空值。
因此,当您从 parcelable 中获取数据时,由于某种原因它可能为 null,因此它为您提供了一个类型 FavoriteData?
,该类型可为 null,无法直接分配。
有两种方法可以解决这个问题
1.) 添加 Non-Null 断言 (!!) 如果数据为 NULL
将抛出 NullPointterdataFavorite = (intent.getParcelableExtra(YOUR_KEY) as FavoriteData?)!!
2.) 使您的变量可空
private var dataFavorite: FavoriteData? = null
指定为
dataFavorite = intent.getParcelableExtra("") as FavoriteData?
根据您的用例进行选择,其他人也可以这样做