开发者

Android TextView and null pointer exception

Why is

TextView test = (TextView) findViewById(R.id.testTextView);
test.getText();

generating a null pointer exce开发者_如何学编程ption? The id is correct, testTextView is correctly declared in my XML layout file.


The only reason for findViewById to return null if you are passing a valid id is that you are either setting the wrong content view (with setContentView) or not setting a content view at all.


I think you might have written setContentView(..) after defining the TextView. Reverse these, and it should work.

Change:

TextView test = (TextView) findViewById(R.id.testTextView);
.
.
setContetView(..)

To:

setContetView(..)
.
.
TextView test = (TextView) findViewById(R.id.testTextView);


You probably haven't called setContentView. You can only use findViewById to get elements of views that have already been inflated.

You could also use a layoutinflater to inflate the view, but that's probably not what you want.


Are you sure the TextView is set on the right XML? For example if you're creating a Dialog that loads a custom XML, to get an element from that xml you have to mention it in dialog.findViewById(R.id.testTextView);

Like Falmarri said, the view has to be inflated. I understand you solved it by creating a new project, but still thought to mention it for future users.


It can also be that you defined the activity in two files. For example layout and layout-v21 and some information like id is missing on one of them. So check all the activity's layouts


In my case, the layout was not finished inflating. Solved by adding a small delay before trying to access the TextView.

new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
    @Override
    public void run() {
        TextView test = (TextView) findViewById(R.id.testTextView);
        test.getText();
    }
}, 100);


I struggled with this for a while and what I realized was, that, if you have more than one layout file version like:

"activity_one.xml" in "layout" folder and one in "layout - small" folder

Which I used for multiple phone layout support, the problem was that one of the TextViews was in both, with the exact same ID and everything, however the difference was that one was higher up in the hierarchy of views in the layout.

When I changed them to be in the same spot it worked.

(I know this is already answered, but maybe this helps someone out there. Very rare though.)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜