convertView.findViewById返回null,即使convertView不为null

时间:2013-01-20 19:04:45

标签: java android

我正在尝试显示包含不同类型行的ListView。 我有一个由ResultArtistLabel等继承的Release抽象类。 我从JSON响应中获得结果。解析没问题,我的工厂设法正确创建了一些Result个对象。

使用这些指南12,我最终扩展了BaseAdapter

public class SearchResultsActivity extends ListActivity {

    private static final String SEARCH_API_ENDPOINT = "http://xxxx.com/database/search?q=";

    SearchResultAdapter searchAdapter;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.result_list);
        searchAdapter = new SearchResultAdapter();
        // handleIntent is needed because android:launchMode="singleTop" mode uses onNewIntent
        handleIntent(getIntent());
    }

    @Override
    protected void onNewIntent(Intent intent) {
        handleIntent(intent);
    }

    private void handleIntent(Intent intent) {

        if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
            String query = intent.getStringExtra(SearchManager.QUERY); // get user input from search widget 
            String[][] params = new String[][]{{"q", query}}; // prepare GET parameters
            HttpRequestHandler requestHandler = new HttpRequestHandler("GET");
            String result;

            requestHandler.setURL(HttpRequestHandler.API_URL, HttpRequestHandler.SEARCH_QUERY_ENDPOINT);
            requestHandler.addParameters(params);
            result = requestHandler.sendRequest();
            if (result != null && !result.isEmpty()) {
                try {
                    ArrayList<Result> resultList = new ResultFactory(new JSONObject(result)).getResults(); // JSON to Result objects
                    for (Result res: resultList) {
                        searchAdapter.addItem(res);
                    }
                    setListAdapter(searchAdapter);
                } catch (JSONException e) {
                    System.out.println("xxjsonexception");
                }
            }
        }
    }

    public class SearchResultAdapter extends BaseAdapter {

        private List<Result> searchResults = new ArrayList<Result>();
        private LayoutInflater mInflater;

        public SearchResultAdapter() {
            mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }

        public void addItem(Result result) {
            searchResults.add(result);
            notifyDataSetChanged();
        }

        @Override
        public Object getItem(int position) {
            return searchResults.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public int getCount() {
            return searchResults.size();
        }

        @Override
        public int getViewTypeCount() {
            return Result.Type.values().length; // enum length
        }

        @Override
        public int getItemViewType(int position) {
            return searchResults.get(position).getType().ordinal();
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            Result tmp = searchResults.get(position); // only for testing
            System.out.println("xxItem type " + tmp.getType());
            View v = searchResults.get(position).getView(mInflater, convertView);
            if (v == null) {
                System.out.println("xxgetviewnull");
            } else {
                System.out.println("xxgetviewok");
            }
            return v;
        }
    }
}

Result.java:

public abstract class Result {
    // general search result class

    public enum Type {
        ARTIST,
        RELEASE,
        MASTER,
        LABEL,
        ERROR,
    }

    public static final String NODE_RESULTS = "results";
    public static final String NODE_TITLE = "title";
    public static final String NODE_THUMB = "thumb";
    public static final String NODE_RESSOURCE = "resource_url";
    public static final String NODE_TYPE = "type";
    public static final String NODE_URI = "uri";
    public static final String NODE_ID = "id";

    public static final String TYPE_ARTIST = "artist";
    public static final String TYPE_RELEASE = "release";
    public static final String TYPE_MASTER = "master";
    public static final String TYPE_LABEL = "label";


    protected String thumb;
    protected String title;
    protected String ressource_url;
    protected static Type type;
    protected String uri;
    protected int id;


    public void setData(JSONObject jsonResult) {
        try {
            setId(jsonResult.getInt(Result.NODE_ID));
            setUri(jsonResult.getString(Result.NODE_URI));
            setRessource_url(jsonResult.getString(Result.NODE_RESSOURCE));
            setThumb(jsonResult.getString(Result.NODE_THUMB));
            setTitle(jsonResult.getString(Result.NODE_TITLE));
        } catch (JSONException e) {
            type = Type.ERROR;
        }
    }

    // getters and setters ..

    public abstract View getView(LayoutInflater inflater, View convertView);
}

Artist.java:

public class Artist extends Result{

    public Artist(){
        type = Type.ARTIST;
    }

    @Override
    public View getView(LayoutInflater inflater, View convertView) {
        if (convertView == null) {
            convertView = inflater.inflate(R.layout.list_item_artist, null);
        }
        TextView textTitle = (TextView) convertView.findViewById(R.id.title_artist);
        if (textTitle == null) {
            System.out.println("xxtexttitle null");
        } else {
            System.out.println("xxtexttitleok " + title);
        }
        textTitle.setText(title);
        return convertView;
    }

}

Label.java

public class Label extends Result {

    public Label() {
        type = Type.LABEL;
    }

    @Override
    public View getView(LayoutInflater inflater, View convertView) {
        if (convertView == null) {
            convertView = inflater.inflate(R.layout.list_item_label, null);
        }
        if (convertView == null) {
            System.out.println("xxconvertviewisnull");
        } else {
            System.out.println("xxconvertviewok");
        }
        TextView titleText = (TextView) convertView.findViewById(R.id.title_label);
        titleText.setText(title);
        return convertView;
    }

}

正如您所看到的,我的ArtistLabel类非常相似,但只有我的Label类在TextView titleText = (TextView) convertView.findViewById(R.id.title_label)处抛出NPE。

这不是我在setContentView()中所做的onCreate 我的Result个对象永远不会null,也不会有null个字段 我确实在我的convertView方法中查看null是否为getView,如果nullRelease,则会对视图进行充气。 我没有使用ViewHolder,因为Master<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:id="@+id/title_label" android:layout_width="fill_parent" android:layout_height="wrap_content"/> </LinearLayout> 将显示额外的字段。

编辑:

list_item_label.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="match_parent"
              android:layout_height="match_parent">

    <TextView android:id="@+id/title_artist"
              android:layout_width="fill_parent"
              android:layout_height="wrap_content"
              android:textColor="#FFAAAA"
              android:textSize="14pt"/>

</LinearLayout>

list_item_artist.xml

{{1}}

2 个答案:

答案 0 :(得分:3)

这是因为当您到达列表中的Label对象时,您的convertView是一个“list_item_artist”视图。然后convertview不是null,但错误的类型的视图找不到title_label。

反转列表顺序,您将获得一个带有艺术家视图的空指针。

答案 1 :(得分:0)

我的猜测是list_item_layout没有id为title_label的元素,这会导致convertView.findViewById(R.id.title_label)返回null,然后在titleText.setText(title)处抛出NullPointerException。如果有另一个包含id为title_lable的布局,那么它将构建得很好,但是然后在运行时抛出NPE。