Я взглянул на другие вопросы, рассказывающие об этой проблеме, и я узнал, что моя проблема заключается в том, что я пытаюсь найти представление, которое не находится в реальном отображаемом представлении (я полагаю).
Но я не могу понять, как решить эту проблему.
Вот мой MainActivity.java
, где появляется ошибка с 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());
}
});
}
Тогда у меня есть 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>
Ошибка:
java .lang.RuntimeException: невозможно запустить действие ComponentInfo {com.example.lapero / com.example.lapero. MainActivity}: java .lang.NullPointerException: попытка вызвать виртуальный метод 'void android .widget.ListView.setAdapter (android .widget.ListAdapter)' для ссылки на пустой объект