Android: How to put ListView in XML?
- by FloIancu
I want to make a simple app that shows a list of contacts (name, surname). My code:
package lista.android;
import java.util.*;
import android.app.ListActivity;
import android.os.Bundle;
import android.widget.*;
class Contact{
String nume;
String prenume;
Contact(String nume, String prenume){
this.nume=nume;
this.prenume=prenume;
}
public String toString(){
return prenume +" "+ nume;
}
}
public class Lista1Activity extends ListActivity {
/** Called when the activity is first created. */
ArrayList <Contact> lista;
ArrayAdapter <Contact> adaptor;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
setListAdapter(adaptor);
lista=new ArrayList<Contact>();
adaptor=new ArrayAdapter<Contact>(this, R.id.element, lista);
adaugaContact("Florian", "Iancu");
adaugaContact("Ioana", "Constantina");
}
public void adaugaContact(String nume, String prenume){
lista.add(new Contact(nume, prenume));
adaptor.notifyDataSetChanged();
}
}
In the XML I have the LinearLayout and a TextView that is the list element. When I run it, the simulator says "Sorry, the application [...] has stopped unexpectedly. Please try again." The LogCat tells me I have to have a ListView whose id is android.R.id.lista. If I create a random ListView field in the XML file and give it the "lista" id, it still doesn't work. How to I call that ListView from XML to match something in my Java code? In other words, I know I'm wrong, but where and how do I fix it?