2017-02-12 74 views
-2

傢伙,我想創建Android上點擊列表視圖,但我不斷收到此錯誤顯示java.lang.NullPointerException:在一個ListView

顯示java.lang.NullPointerException:試圖調用虛擬方法無效android.widget .ListView.setAdapter(android.widget.ListAdapter)'在一個空對象引用

我不確定這是什麼意思我很新的Android開發 你能幫我嗎?...謝謝你Advance

My ** CitySelection.java **文件

package com.sourcey.materiallogindemo; 

import android.content.Intent; 
import android.support.v7.app.AppCompatActivity; 
import android.os.Bundle; 
import android.view.View; 
import android.widget.AdapterView; 
import android.widget.ArrayAdapter; 
import android.widget.ListView; 

public class CitySelection extends AppCompatActivity { 
ListView listView; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_city_selection); 
    listView = (ListView)findViewById(android.R.id.list); 
    String[] values = new String[] {"Chennai" , "Madurai" , "Delhi" , "Trichy"}; 
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.activity_list_item, android.R.id.text1, values); 
    listView.setAdapter(adapter); 
    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { 
     @Override 
     public void onItemClick(AdapterView<?> parent, View view, int position, long id) { 
      if(position==0){ 
       Intent myintent = new Intent(view.getContext() , MaduraiCityMain.class); 
       startActivityForResult(myintent,0); 
      } 
      if(position==1){ 
       Intent myintent = new Intent(view.getContext() , ChennaiCityMain.class); 
       startActivityForResult(myintent,1); 
      } 
     } 
    }); 

} 

} 
+0

'的ListView =(ListView中)findViewById(android.R.id.list);'應'的ListView =(ListView中)findViewById(R.id.list);' – rafsanahmad007

回答

0

看起來你已經忘記了在調用它之前初始化listView。

嘗試listView = (new ListView)findViewById(android.R.id.list);

相關問題