'LayoutInflater returns null view Android
I have a RecyclerView with a custom view being used as the holder. Whenever the ViewHolder class is constructed, it calls the findViewById method on the view being passed through, but I get a NullPointerException. I'm figuring it's a problem with the inflater.
Here's my code:
public RecyclerAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.boxview_layout, parent, true);
view.setLayoutParams(new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT));
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
try {
JSONObject pos = jsonList.getJSONObject(position);
holder.setText(pos.getString("text"));
holder.setTitle(pos.getString("title"));
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
public int getItemCount() {
return jsonList.length();
}
public class ViewHolder extends RecyclerView.ViewHolder {
private TextView title;
private TextView text;
private View view;
public ViewHolder(View v) {
super(v);
this.title = view.findViewById(R.id.titleBox);
this.text = view.findViewById(R.id.textBox);
this.view = v;
}
public View getCustomView() {
return view;
}
public void setTitle(String title) {
this.title.setText(title);
}
public void setText(String text) {
this.text.setText(text);
}
}
And here's the view being inflated:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:custom="http://schemas.android.com/apk/res-auto"
android:layout_height="match_parent"
android:layout_width="match_parent">
<TextView
android:id="@+id/titleBox"
android:textSize="40sp"
android:layout_width="256dp"
android:layout_height="69dp"
android:text="Filler title"
custom:layout_constraintStart_toStartOf="parent"
custom:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="@+id/textBox"
android:layout_width="256dp"
android:layout_height="69dp"
android:layout_marginTop="8dp"
android:text="Filler text"
android:textSize="25sp"
custom:layout_constraintStart_toStartOf="parent"
custom:layout_constraintTop_toBottomOf="@+id/titleBox" />
</androidx.constraintlayout.widget.ConstraintLayout>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
