ListView无法解析

时间:2012-08-02 16:55:30

标签: android android-listview

大家。我在这段代码的摘录中遇到了麻烦:

cocktailListView.setAdapter(adapter);

cocktailListView无法解析

我的整个代码是:

public class SearchCustomListViewActivity extends ListActivity {
    //ArrayList thats going to hold the search results
    ArrayList<HashMap<String, Object>> searchResults;

    //ArrayList that will hold the original Data
    ArrayList<HashMap<String, Object>> originalValues;
    LayoutInflater inflater;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.main);
        final EditText searchBox=(EditText) findViewById(R.id.searchBox);
        ListView playerListView=(ListView) findViewById(android.R.id.list);

        //get the LayoutInflater for inflating the customomView
        //this will be used in the custom adapter
        inflater=(LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        //these arrays are just the data that
        //I'll be using to populate the ArrayList
        //You can use our own methods to get the data
        String names[]={"Ronaldo","Messi","Torres","Iniesta",
                "Drogba","Gerrard","Rooney","Xavi"};

        String teams[]={"Real Madrid","Barcelona","Chelsea",
                "Barcelona","Chelsea","Liverpool",
                "ManU","Barcelona"};
        Integer[] photos={R.drawable.amazonas,R.drawable.amazonas,
                R.drawable.amazonas,R.drawable.amazonas,
                R.drawable.amazonas,R.drawable.amazonas,
                R.drawable.amazonas,R.drawable.amazonas};

        originalValues=new ArrayList<HashMap<String,Object>>();

        //temporary HashMap for populating the
        //Items in the ListView
        HashMap<String , Object> temp;

        //total number of rows in the ListView
        int noOfPlayers=names.length;

        //now populate the ArrayList players
        for(int i=0;i<noOfPlayers;i++)
        {
            temp=new HashMap<String, Object>();

            temp.put("name", names[i]);
            temp.put("team", teams[i]);   
            temp.put("photo", photos[i]);

            //add the row to the ArrayList
            originalValues.add(temp);       
        }
        //searchResults=OriginalValues initially
        searchResults=new ArrayList<HashMap<String,Object>>(originalValues);

        //create the adapter
        //first param-the context
        //second param-the id of the layout file
        //you will be using to fill a row
        //third param-the set of values that
        //will populate the ListView
        final CustomAdapter adapter=new CustomAdapter(this, R.layout.players_layout,searchResults);

        //finally,set the adapter to the default ListView
        cocktailListView.setAdapter(adapter);
        searchBox.addTextChangedListener(new TextWatcher() {
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                //get the text in the EditText
                String searchString=searchBox.getText().toString();
                int textLength=searchString.length();
                searchResults.clear();

                for(int i=0;i<originalValues.size();i++)
                {
                    String playerName=originalValues.get(i).get("name").toString();
                    if(textLength<=playerName.length()){
                        //compare the String in EditText with Names in the ArrayList
                        if(searchString.equalsIgnoreCase(playerName.substring(0,textLength)))
                            searchResults.add(originalValues.get(i));
                    }
                }

                adapter.notifyDataSetChanged();
            }

            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

            public void afterTextChanged(Editable s) {}
        });
    }

    //define your custom adapter
    private class CustomAdapter extends ArrayAdapter<HashMap<String, Object>>
    {
        public CustomAdapter(Context context, int textViewResourceId,
                ArrayList<HashMap<String, Object>> Strings) {
            //let android do the initializing :)
            super(context, textViewResourceId, Strings);
        }

        //class for caching the views in a row 
        private class ViewHolder
        {
            ImageView photo;
            TextView name,team;
        }
        ViewHolder viewHolder;

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if(convertView==null)
            {
                convertView=inflater.inflate(R.layout.players_layout, null);
                viewHolder=new ViewHolder();

                //cache the views
                viewHolder.photo=(ImageView) convertView.findViewById(R.id.photo);
                viewHolder.name=(TextView) convertView.findViewById(R.id.name);
                viewHolder.team=(TextView) convertView.findViewById(R.id.team);

                //link the cached views to the convertview
                convertView.setTag(viewHolder);
            }
            else
                viewHolder=(ViewHolder) convertView.getTag();

            int photoId=(Integer) searchResults.get(position).get("photo");

            //set the data to be displayed
            viewHolder.photo.setImageDrawable(getResources().getDrawable(photoId));
            viewHolder.name.setText(searchResults.get(position).get("name").toString());
            viewHolder.team.setText(searchResults.get(position).get("team").toString());

            //return the view to be displayed
            return convertView;
        }
    }
}

2 个答案:

答案 0 :(得分:1)

您还没有实例化cocktailListView

您需要在onCreate(...)中执行以下操作。您可以在实例化playerListView

的地方执行此操作
  

来自Espiandev

     

ListView cocktailListView = getListView();

OR

ListView cocktailListView = 
    (ListView) this.findViewById(/* id of your list view*/);

答案 1 :(得分:0)

使用ListActivity时,布局中的ListView应具有精确的ID:

  android:id="@id/android:list"

仅在这种情况下,您实际上可以使用getListView而无需获得npe。

来自doc:

  

ListActivity的默认布局由单个布局组成,   屏幕中央的全屏列表。但是,如果你愿意,   您可以通过设置自己的视图布局来自定义屏幕布局   在onCreate()中使用setContentView()。要做到这一点,你自己的观点必须   包含一个ID为“@android:id / list”的ListView对象(或列出if   它在代码中)