Error in ListActivity, probably related to OnItemClickListener

1

I'm having a problem understanding what's going wrong in this code, I feel the problem may be related to the OnItemClickListener. When I try to emulate it it responds with a message like this: "Unfortunately, MyAplication has stopped.".

    public class MainActivity extends ListActivity {

private ArrayList<ViewListing> arrayList;
private ListView list = (ListView) findViewById(R.id.listview);

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    arrayList = new ArrayList<ViewListing>();
        arrayList.add(new ViewListing(0, R.drawable.anjelly, "Item 1"));
        arrayList.add(new ViewListing(1, R.drawable.construct, "Item 2"));
        arrayList.add(new ViewListing(2, R.drawable.darkdestroyer, "Item 3"));

        ListViewAdapter adp = new ListViewAdapter(getApplicationContext(), arrayList);

    setListAdapter(adp);
    list.setOnItemClickListener(new OnItemClickListener() {

        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            switch(position) {
                case 1:
                    Toast.makeText(getApplicationContext(), "1 Selected", Toast.LENGTH_SHORT).show();
                case 2:
                    Toast.makeText(getApplicationContext(), "2 Selected", Toast.LENGTH_SHORT).show();
                case 3:
                    Toast.makeText(getApplicationContext(), "3 Selected", Toast.LENGTH_SHORT).show();
            }

        }
    });
   }
}
    
asked by anonymous 13.08.2016 / 01:01

1 answer

1

I see at least 3 problems in the code:

1 - The ListView list is being initialized outside the onCreate() method.

2 - You must call the setContentView() method if your layout is not just a ListView .

3 - In order to use the setAdapter() method of ListActivity, the id of the listView must be @android:id/list .

The findViewById() method looks at view within the layout passed to the setContentView() method, so it must be used later.

Change this part of the code like this:

public class MainActivity extends ListActivity {

    private ArrayList<ViewListing> arrayList;
    private ListView list;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);//Altere se o nome do layout for outro.

        list = getListView();//O id da listView tem de ser @android:id/list.

        ......
        //restante do código
}

For more information, see ListActivity in the documentation.

    
13.08.2016 / 01:15