嗨我想在android中做我的第一个应用程序。我想用Contextmenu制作列表视图但是当我尝试编译时我有错误。这是我的代码:
instancias(); 中的错误
错误:lista.setAdapter(a);
paiseslista(); 中的错误
这是日志:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
at sergio.dialogosprueba.mainactivity.paisesLista(mainactivity.java:66)
at sergio.dialogosprueba.mainactivity.instancias(mainactivity.java:58)
at sergio.dialogosprueba.mainactivity.onCreate(mainactivity.java:30)
活动:
public class MainActivity extends AppCompatActivity {
Button vuelos,fecha;
ListView lista;
ArrayList<String> array;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
instancias();
vuelos.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(mainactivity.this, secondactivity.class);
startActivity(intent);
}
});
fecha.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(mainactivity.this, secondactivity.class);
startActivity(intent);
}
});
}
private void instancias() {
vuelos = (Button) findViewById(R.id.vuelos);
fecha = (Button) findViewById(R.id.fecha);
lista =(ListView) findViewById(R.id.lista);
array = new ArrayList<String>();
array.add("Roma");
array.add("Madrid");
array.add("Paris");
paisesLista();
registerForContextMenu(lista);
}
private void paisesLista() {
ArrayAdapter a = new ArrayAdapter(mainactivity.this,android.R.layout.list_content,array);
lista.setAdapter(a);
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
getMenuInflater().inflate(R.menu.menu_main, menu);
super.onCreateContextMenu(menu, v, menuInfo);
}
@Override
public boolean onContextItemSelected(MenuItem item) {
return super.onContextItemSelected(item);
}
}
答案 0 :(得分:1)
lista在paisesLista中为null。尝试调试,看看行后的lista的值是什么:
lista =(ListView) findViewById(R.id.lista);
您的布局可能存在问题。检查它是否具有ID&#34; lista&#34;
根据您的评论,您想使用second_layout.xml,因此您需要更改以下行:
setContentView(R.layout.activity_main);
为:
setContentView(R.layout. second_layout);