Android ListView问题加载应用程序

时间:2015-07-05 22:25:48

标签: java listview android-listview

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_home_screen);

    String[] myHouses = new String[8];
    myHouses[0] = "Hello0";
    myHouses[1] = "Hello1";
    myHouses[2] = "Hello2";
    myHouses[3] = "Hello3";
    myHouses[4] = "Hello4";
    myHouses[5] = "Hello5";
    myHouses[6] = "Hello6";
    myHouses[7] = "Hello7";
    ArrayList<String> myHousesList =new ArrayList<>(Arrays.asList(myHouses));

    ListAdapter grumpyAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, myHousesList);
    ListView grumpyListView = (ListView) findViewById(R.id.grumpyListView);
    grumpyListView.setAdapter(grumpyAdapter);

    grumpyListView.setOnItemClickListener(
            new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    String myHouse = String.valueOf(parent.getItemAtPosition(position));
                    Toast.makeText(HomeScreen.this, myHouse, Toast.LENGTH_LONG).show();
                }
            }
    );

}

}

将我的错误移到此行:再次出现空指针异常: ListView grumpyListView =(ListView)findViewById(R.id.grumpyListView);

2 个答案:

答案 0 :(得分:0)

正如错误消息所示,您的布局有问题,无法充气,请检查相应的xml布局文件。

答案 1 :(得分:0)

而不是ListAdapter尝试使用ArrayAdapter

ArrayList<String> myHousesList=new ArrayList<>(Arrays.asList(myHouses));
ArrayAdapter<String> grumpyAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, myHousesList);
 ListView grumpyListView = (ListView) findViewById(R.id.grumpyListView);  
   grumpyListView.setAdapter(grumpyAdapter);

试试这个