开发者

setting an array of text into an array of textview

i faced this problem when trying to assign a character into an array of text view

counter is a count wh开发者_如何学JAVAich i got from reading the number of characters i have in a text file

            TextView[] tv = new TextView[counter];

        for (int i = 0; i < counter; i++)
        {
            tv[i].setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); 
            tv[i].setText(singleText[i]); 
            setContentView(tv[i]); 
        }

after this, when i try to run the application i the application just force closes.. i have no idea on how to debug it

my application would need to set 1 character into 1 text view


You haven't initialized the TextViews properly. That's why you are getting nullpointerexception. You have to initialize the TextView as follows:

tv[i] = new TextView(this);

Here this is the your Activity instance.

And there is a problem in your

setContentView(tv[i]);

If you use this code then in the screen you will see only the last textview.

To see all the TextView you have to add all the TextView in a container like LinearLayout. Then you have set the container as content View.

Here is the code you can use:

LinearLayout linearLayout = new LinearLayout(this);
linearLayout.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,              
        LayoutParams.WRAP_CONTENT));
TextView[] tv = new TextView[counter];

for (int i = 0; i < counter; i++)
{
        tv[i] = new TextView(this);
        tv[i].setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,              
            LayoutParams.WRAP_CONTENT)); 
        tv[i].setText(singleText[i]); 
        linearLayout.addView(tv[i]); 
}
setContentView(linearLayout);

Hope it will help you.


TextView[] tv = new TextView[counter]; Here you creating array filled with null references. Of course it will crash here tv[i].setLayoutParams() with null pointer exception

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜