尝试在空对象引用上调用虚拟方法 'void android.view.View.setVisibility(int)'



我试图在一个片段中实现进度条,但它给了我这个错误。我正在调用一个api,它给我数据,直到数据被获取,我想运行进度条。

. lang。NullPointerException:尝试在空对象引用上调用虚拟方法'void android.view.View.setVisibility(int)'

代码

class GeneralFragment : Fragment() {
private lateinit var mAdapter: NewsListAdapter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
fetchdata("https://news-api-don.herokuapp.com/api/v1?apiKey=20d14506791144cc8b424549c42068c0")
}

override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_general, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val recyclerView = view.findViewById<RecyclerView>(R.id.recyclerView)
mAdapter = NewsListAdapter(this)
recyclerView.adapter = mAdapter
}

private fun fetchdata(url: String) {
generalBar.visibility = View.VISIBLE
val jsonObjectRequest = JsonObjectRequest(
Request.Method.GET, url, null,
{
val newsJsonArray = it.getJSONArray("articles")
val newsArray = ArrayList<News>()
for (i in 0 until newsJsonArray.length()) {
val newsJsonObject = newsJsonArray.getJSONObject(i)
val news = News(
newsJsonObject.getString("title"),
newsJsonObject.getString("author"),
newsJsonObject.getString("url"),
newsJsonObject.getString("urlToImage")
)
newsArray.add(news)
}
mAdapter.updateNews(newsArray)
generalBar.visibility = View.GONE
},
{
Toast.makeText(activity, "Something went wrong", Toast.LENGTH_LONG).show()
generalBar.visibility = View.GONE
}
)

MySingleton.getInstance(this).addToRequestQueue(jsonObjectRequest)
}
fun onItemClicked(item: News) {
val builder = CustomTabsIntent.Builder()
val customTabsIntent = builder.build()
activity?.let { customTabsIntent.launchUrl(it, Uri.parse(item.url)) }
}
}

这是xml文件

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context=".fragments.GeneralFragment">
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"/>
<ProgressBar
android:id="@+id/generalBar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"/>

</androidx.constraintlayout.widget.ConstraintLayout>

似乎generalBarfetchdata调用之前没有初始化。你需要初始化它

val generalBar = view.findViewById<ProgressBar>(R.id.generalBar)

相关内容

  • 没有找到相关文章

最新更新