Я пытаюсь преобразовать этот Java код в Kotlin. У меня есть представление переработчика, элементы которого загружаются через вызов внешней базы данных. В Java первое, что я обычно делаю, это инициализирую представление рециркулятора в OnCreateView (после представления), а затем создаю адаптер с новыми элементами, как показано ниже:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.popular_fragment, container, false);
recyclerView = view.findViewById(R.id.popular_rc_view);
loadMovie();
return view;
}
private void loadMovie() {
ApiService apiService = ApiBuilder.getClient(getContext()).create(ApiService.class);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext(),LinearLayoutManager.VERTICAL, false));
Call<MovieResponse> call = ....
//HERE I LOAD THE DATA INTO "MOVIES"
recyclerView.setAdapter(new PopularAdapter(movies, R.layout.content_main, getContext()));
recyclerView.addOnItemTouchListener(.....)
}
Теперь, в Kotlin я попытался сделать то же самое, выполнив инициализацию следующим образом:
@JvmField
@BindView(R.id.rc_view)
var recyclerView: RecyclerView? = null
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val view = inflater.inflate(R.layout.popular_fragment, container, false)
recyclerView = view.findViewById(R.id.popular_rc_view)
loadMovie()
return view
}
private fun loadMovie() {
val apiService = getClient(context)!!.create(ApiService::class.java)
recyclerView!!.layoutManager = LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false)
val call = ....
//HERE I LOAD THE DATA INTO "MOVIES"
recyclerView!!.adapter = PopularAdapter(movies as List<MovieModel>, R.layout.content_main, context!!)
recyclerView!!.addOnItemTouchListener(....)
}
Проблема в том, что в Kotlin я получаю ошибку в PopularAdapter, в частности KotlinNullPointerException в onBindViewHolder . Это мой метод в адаптере, я получаю сообщение об ошибке в первой строке, поэтому я думаю, что это проблема макета, поскольку он не может найти, где установить текст (если я пытаюсь напечатать заголовок mov ie, он работает, так что это не проблема списка):
class MoviesAdapter(private val movies: List<MovieModel>, private val rowLayout: Int, private val context: Context) : RecyclerView.Adapter<MoviesAdapter.MovieViewHolder>() {
class MovieViewHolder(v: View?) : RecyclerView.ViewHolder(v!!) {
@JvmField
@BindView(R.id.movieTitle)
var movieTitle: TextView? = null
@JvmField
@BindView(R.id.date)
var date: TextView? = null
@JvmField
@BindView(R.id.popularityTextView)
var popularity: TextView? = null
@JvmField
@BindView(R.id.gambar)
var backbg: ImageView? = null
init {
ButterKnife.bind(this, v!!)
}
}
override fun onCreateViewHolder(viewGroup: ViewGroup, viewType: Int): MovieViewHolder {
val view = LayoutInflater.from(viewGroup.context).inflate(R.layout.row, viewGroup, false)
return MovieViewHolder(view)
}
override fun onBindViewHolder(holder: MovieViewHolder, position: Int) {
holder.movieTitle!!.text = movies[position].title
val time = movies[position].releaseDate
val parser = SimpleDateFormat("yyyy-MM-dd")
var date: Date? = null
try {
date = parser.parse(time)
val formatter = SimpleDateFormat("EEEE, dd MMM yyyy")
val formattedDate = formatter.format(date)
holder.date!!.text = formattedDate
} catch (e: ParseException) {
e.printStackTrace()
}
holder.popularity!!.text = movies[position].getVoteAverage().toString()
Glide.with(context).load(BuildConfig.URL_BACKBG + movies[position].backdropPath)
.into(holder.backbg)
}
override fun getItemCount(): Int {
return movies.size
}
}
Я также публикую два xml, которые я использовал в Java / Kotlin, возможно, мне нужно изменить способ их объявления в программе утилизации:
content_main. xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="match_parent"
android:layout_width="match_parent"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:background="@color/grey"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/ll1"
android:orientation="vertical">
<ImageView
android:layout_width="@dimen/_80sdp"
android:layout_height="@dimen/_30sdp"
android:layout_marginTop="@dimen/_10sdp"
android:background="@drawable/logoss"
android:layout_gravity="center"/>
</LinearLayout>
<FrameLayout
android:layout_below="@+id/ll1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/fragment_container"
android:layout_above="@id/bottombar"
app:layout_behavior="@string/appbar_scrolling_view_behavior">
</FrameLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:id="@+id/bottombar"
android:background="@color/dark"
android:orientation="vertical">
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="@+id/BottomNavigation"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="@dimen/_5sdp"
android:layout_gravity="bottom"
app:itemBackground="@color/dark"
android:foreground="?attr/selectableItemBackground"
app:itemTextColor="@animator/bottom_nav_color"
app:itemIconTint="@animator/bottom_nav_color"
app:menu="@menu/bottombar_menu_4items"/>
</LinearLayout>
</RelativeLayout>
Popular_fragment. xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:minHeight="@dimen/_150sdp"
android:layout_marginTop="@dimen/_10sdp"
android:orientation="vertical">
<androidx.recyclerview.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:id="@+id/popular_rc_view">
</androidx.recyclerview.widget.RecyclerView>
</LinearLayout>
</LinearLayout>
Это декомпилированный байт-код: ссылка Это после преобразования декомпилированного байт-кода в Java: java