Listactivity error, probably related to Onitemclicklistener

Asked

Viewed 57 times

1

I am having a problem understanding what is going wrong in this code, I feel that the problem may be related to Onitemclicklistener. When I try to emulate 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();
            }

        }
    });
   }
}

1 answer

1


I see at least 3 problems in the code:

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

2 - It is necessary to call the method setContentView(), should your layout not just a Listview.

3 - To use the method setAdapter() of Listactivity, the id of listview must be @android:id/list.

The method findViewById() looking for the view within the layout passed to the method setContentView(), has therefore to 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.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.