1

I have this code, does anybody know why I get an error when I compile this on my Phone?

public void onSectionAttached(int number) {
            TextView textView = (TextView) findViewById(R.id.textView1);
            textView.setVisibility(View.VISIBLE);
            switch (number) {
                case 1:
                    mTitle = getString(R.string.title_section1);
                    break;
                case 2:
                    mTitle = getString(R.string.title_section2);
                    textView.setVisibility(View.GONE);
                    break;
                case 3:
                    mTitle = getString(R.string.title_section3);
                    textView.setVisibility(View.GONE);
                    break;
            }
    }

EDIT : This is the error I get, it goes wrong on the setVisibitily lines.

meesg
  • 13
  • 3
  • 1
    How about displaying the actual error? – James Oct 08 '14 at 19:50
  • what is the error? post your `getString` method – Rod_Algonquin Oct 08 '14 at 19:52
  • If that is what is causing the error the only thing it could be is that there is no textView1 in your layout, everything else is valid or wouldn't compile if it wasn't. Again, that is only if this is what is causing the error for certain. – zgc7009 Oct 08 '14 at 19:53
  • I think that you want to mean runtime error when you say "compile on my phone". Maybe you have declared a view with the ID tetView1, but **in other layout** and not in the layout of this activity. This is why you don't have compiled a compile error, but yes runtime one. – Juan Aguilar Guisado Oct 08 '14 at 20:09

1 Answers1

2

Next time please attach the relevant logs to your question. It makes things so much simpler..

Anyway the only causes for error I can see in your code are:

A. textView.setVisibility() is called from a thread other than the UI thread. If that is the case, do something like to solve your problem:

 myActivity.runOnUiThread(new Runnable() {
        public void run() {
            onSectionAttached(num);
        }
  });

B. You have not called setContentView() to your layout prior to activating this code.

C. Your layout does not contain a TextView element called textView1. In which case findViewById() wil return null and textView.setVisibility() will result in NPE.

Gilad Haimov
  • 5,767
  • 2
  • 26
  • 30