在膨胀PopupWindow时出现NullPointerException

时间:2013-09-04 02:19:22

标签: android nullpointerexception popupwindow

我正在尝试从位于列表项中的按钮(来自自定义列表适配器)中膨胀PopupWindow,但是我在多个位置获得了NullPointerExceptions。

这是按钮的onClick,我试图让PopupWindow发生:

public void onClick(View v) {
    LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    PopupWindow pw = null;
if (scores[0] == null) {
    pw = new PopupWindow(inflater.inflate(R.layout.tag_table_row, null, false), 100, 100, true);
    TextView tag = (TextView) v.findViewById(R.id.tag);
    tag.setText("error!");
} else {
    int x = tags.length;
    int y = 5; 
    int z = Math.min(x, y); 

    for (int i = 0; i < z; i++) {
        pw = new PopupWindow(inflater.inflate(R.layout.tag_table_row, null, false), 100, 100, true);                        
            TextView tag = (TextView) v.findViewById(R.id.tag);
            tag.setText(tags[i]);
            int tag1score = Double.parseDouble(scores[i]);
            TextView score = (TextView) v.findViewById(R.id.tagscore);
            score.setText(Integer.toString(tag1score));
    }
}
pw.showAtLocation(v.findViewById(R.id.fragment_content), Gravity.CENTER, 0, 0);
}

我在tag.setText(tags[i]);得到NullPointerException。如果我评论并尝试做分数,我会在score.setText(Integer.toString(tag1score));得到一个NullPointerException。标签[]和得分[]都在onClick之前被初始化和填充,我已经测试过以确保两者中的结果都是字符串而非空。

有关NPE为何发生的任何想法?

1 个答案:

答案 0 :(得分:1)

你需要使用正确的东西来寻找视图。你正在膨胀到pw,但你正在寻找你的观点。我认为这可能会更好;

public void onClick(View v) {
    LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View popupView = null;
    PopupWindow pw = null;
    if (scores[0] == null) {
        popupView = layoutInflater.inflate(R.layout.tag_table_row, null, false);  
        pw = new PopupWindow(popupView, 100, 100, true);                      

        TextView tag = (TextView) v.findViewById(R.id.tag);
        tag.setText("error!");
    } else {
        int x = tags.length;
        int y = 5; 
        int z = Math.min(x, y); 

        for (int i = 0; i < z; i++) {
            popupView = layoutInflater.inflate(R.layout.tag_table_row, null, false);  
            pw = new PopupWindow(popupView, 100, 100, true);                      
            TextView tag = (TextView) popupView.findViewById(R.id.tag);
            tag.setText(tags[i]);
            int tag1score = Double.parseDouble(scores[i]);
            TextView score = (TextView) popupView.findViewById(R.id.tagscore);
            score.setText(Integer.toString(tag1score));
        }
    }
    pw.showAtLocation(popupView, Gravity.CENTER, 0, 0);
}

它会跟踪您已膨胀的视图,因此您可以搜索其中的元素。

相关问题