Search code examples
javaandroidnullpointerexceptionandroid-linearlayoutviewgroup

Android - LinearLayout not adding custom view


NOTICE: THIS QUESTION HAS BEEN RESOLVED DUE TO ME CATCHING MY OWN STUPIDITY

I want to add a custom class to a LinearLayout, but for some reason I keep getting a NullPointerException.

Here is the method that deals with the addition:

protected void onPostExecute(String results) {
        System.out.println("ON POST EXECUTE : " + results);
        try {
            if(!results.equals(((MessageBlurb)container.getChildAt(0)).getMessage())){
                try {
                    container.removeViewAt(30);
                    for (int i = 29; i > 0; i--) {
                        container.addView(container.getChildAt(i-1), i);
                        container.removeViewAt(i-1);
                    }
                    container.addView(new MessageBlurb(getApplicationContext(), results, Color.BLACK), 0);
                } catch (NullPointerException e) {
                    // TODO: handle exception
                }
            }
        }
        catch (Exception e) {
            MessageBlurb mb = new MessageBlurb(getApplicationContext(), results, Color.BLACK);
            mb.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
            System.out.println(mb);
            container.addView(mb, 0);
        }


    }

where MessageBlurb extends ViewGroup, because I have a TextView inside the MessageBlurb.

The MessageBlurb class looks like this:

public MessageBlurb(Context context, String message, int color){
    super(context);
    myTV = new TextView(context);
    this.addView(myTV);
    myTV.setText(message);
    System.out.println("THE BLURB IS CREATED");
    this.setOnClickListener(new OnClickListener() {

        public void onClick(View v) {
            System.out.println("YOU CLIKED THE BLURB");

        }
    });

}

I printed out the description of mb, and it gives me a memory location. As well as that, the logcat error points to this line:

container.addView(mb, 0);

The container itself is a LinearLayout defined in the activity_main.xml file. It is initialized through the line of code:

container = (LinearLayout)findViewById(R.id.container);

The id of the Layout in the xml file is also called container

Can someone see what I'm doing wrong? Thanks!


Solution

  • It turns out that I was being a complete idiot. I looked through my onCreate() and found that I had commented out the line: setContentView(...)

    Even so, I want to thank everyone who replied to this thread. Sorry for all the trouble! :)