I took a look at the other questions talking about this problem and what I learnt is that my problem is there because I try to find a view that isn't in the actual displayed view (I guess).
But I can't figure out how to fix this problem.
Here is my MainActivity.java
where the error appears with final ListView list...
public class MainActivity extends AppCompatActivity {
private AppBarConfiguration mAppBarConfiguration;
private Context context = this;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//-------------------------------------- Apero list ---------------------------
ArrayList<AperoVersion> aperoList = new ArrayList<AperoVersion>();
initList(aperoList);
AperoAdapter adapter = new AperoAdapter(this, R.layout.apero_list_layout, aperoList);
final ListView list = (ListView)findViewById(R.id.list_apero);
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapter, View v, int position, long id) {
AperoVersion selectedItem = (AperoVersion) adapter.getItemAtPosition(position);
Log.v("CustomAdapterExemple", "Selected apero: " + selectedItem.getName());
}
});
}
Then I have the fragment_home
:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ui.home.HomeFragment">
<ListView
android:id="@+id/list_apero"
android:layout_width="407dp"
android:layout_height="598dp"
android:layout_marginTop="136dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="@+id/text_home"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:textAlignment="center"
android:textSize="20sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.043" />
</androidx.constraintlayout.widget.ConstraintLayout>
The error is:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.lapero/com.example.lapero.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
list_apero
is in fragment_home
and not in activity_main
.
findViewById(R.id.list_apero)
in the activity is returning null.
You should set the adapter in the Fragment, not in the Activity.