android.widget.ListView.setAdapter(android.widget.ListAdapter)' 在空对象引用上



错误在setAdapter行上。我找不到错误在哪里。它与空异常无关。有些事情不顺理

java.lang.RuntimeException: 无法启动活动 ComponentInfo{com.example.myapplication/com.example.myapplication.Namelist}: java.lang.NullPointerException: 尝试调用虚拟方法 'void android.widget.ListView.setAdapter(android.widget.ListAdapter(' on a 空对象引用 at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2913( at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048( at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78( 在

主类:

public class Namelist extends AppCompatActivity {
String[] mobileArray = {"Android","IPhone","WindowsMobile","Blackberry",
"WebOS","Ubuntu","Windows7","Max OS X"};
ListView l1;
ArrayAdapter<String> arrayAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
l1 = (ListView) findViewById(R.id.list);
arrayAdapter = new ArrayAdapter<String>(Namelist.this,R.layout.activity_namelist,mobileArray);
l1.setAdapter(arrayAdapter);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_namelist);
}
}

活动 XML:

<?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=".Namelist">
<ListView
android:id="@+id/list"
android:layout_width="409dp"
android:layout_height="729dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

提前致谢

不能在setContentView(R.layout.activity_namelist)
之前引用l1

正确的代码在这里:

public class Namelist extends AppCompatActivity {
String[] mobileArray = {"Android","IPhone","WindowsMobile","Blackberry","WebOS","Ubuntu","Windows7","Max OS X"};
ListView l1;
ArrayAdapter<String> arrayAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_namelist);
l1 = findViewById(R.id.list);
arrayAdapter = new ArrayAdapter<String>(Namelist.this,android.R.layout.simple_list_item_1,mobileArray);
l1.setAdapter(arrayAdapter);
}
}

而且您还将错误的layoutR.layout.activity_namelist传递给了ArrayAdapter的第二个参数.您没有activity_namelist声明布局名称。因此,您可以使用默认的内置布局android.R.layout.simple_list_item_1询问上面的代码。

相关内容

  • 没有找到相关文章

最新更新