Nullpointerexception when creating a View on Android

Asked

Viewed 160 times

0

I’m creating a Activity on Android, whose code is here, and I’m getting a NullPointerException near the line

final TextView txtResult = new TextView(this);

I got the following dump from the stack:

05-07 09:12:57.180: E/AndroidRuntime(887): FATAL EXCEPTION: main
05-07 09:12:57.180: E/AndroidRuntime(887): Process: br.com.colorcalc, PID: 887
05-07 09:12:57.180: E/AndroidRuntime(887): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{br.com.colorcalc/br.com.colorcalc.Calculator}: java.lang.NullPointerException
05-07 09:12:57.180: E/AndroidRuntime(887):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2102)
05-07 09:12:57.180: E/AndroidRuntime(887):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2226)
05-07 09:12:57.180: E/AndroidRuntime(887):  at android.app.ActivityThread.access$700(ActivityThread.java:135)
05-07 09:12:57.180: E/AndroidRuntime(887):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1397)
05-07 09:12:57.180: E/AndroidRuntime(887):  at android.os.Handler.dispatchMessage(Handler.java:102)
05-07 09:12:57.180: E/AndroidRuntime(887):  at android.os.Looper.loop(Looper.java:137)
05-07 09:12:57.180: E/AndroidRuntime(887):  at android.app.ActivityThread.main(ActivityThread.java:4998)
05-07 09:12:57.180: E/AndroidRuntime(887):  at java.lang.reflect.Method.invokeNative(Native Method)
05-07 09:12:57.180: E/AndroidRuntime(887):  at java.lang.reflect.Method.invoke(Method.java:515)
05-07 09:12:57.180: E/AndroidRuntime(887):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:777)
05-07 09:12:57.180: E/AndroidRuntime(887):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:593)
05-07 09:12:57.180: E/AndroidRuntime(887):  at dalvik.system.NativeStart.main(Native Method)
05-07 09:12:57.180: E/AndroidRuntime(887): Caused by: java.lang.NullPointerException
05-07 09:12:57.180: E/AndroidRuntime(887):  at android.content.ContextWrapper.getResources(ContextWrapper.java:89)
05-07 09:12:57.180: E/AndroidRuntime(887):  at android.view.ContextThemeWrapper.getResources(ContextThemeWrapper.java:78)
05-07 09:12:57.180: E/AndroidRuntime(887):  at android.view.View.<init>(View.java:3429)
05-07 09:12:57.180: E/AndroidRuntime(887):  at android.view.View.<init>(View.java:3496)
05-07 09:12:57.180: E/AndroidRuntime(887):  at android.widget.TextView.<init>(TextView.java:622)
05-07 09:12:57.180: E/AndroidRuntime(887):  at android.widget.TextView.<init>(TextView.java:617)
05-07 09:12:57.180: E/AndroidRuntime(887):  at android.widget.TextView.<init>(TextView.java:613)
05-07 09:12:57.180: E/AndroidRuntime(887):  at br.com.colorcalc.Calculator.<init>(Calculator.java:26)
05-07 09:12:57.180: E/AndroidRuntime(887):  at java.lang.Class.newInstanceImpl(Native Method)
05-07 09:12:57.180: E/AndroidRuntime(887):  at java.lang.Class.newInstance(Class.java:1208)
05-07 09:12:57.180: E/AndroidRuntime(887):  at android.app.Instrumentation.newActivity(Instrumentation.java:1061)
05-07 09:12:57.180: E/AndroidRuntime(887):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2093)
05-07 09:12:57.180: E/AndroidRuntime(887):  ... 11 more

Does it have something to do with my method onCreate?

        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            txtResult = (TextView) findViewById(R.id.txtResult);
            btnCalc.setOnClickListener (new View.OnClickListener() {
                    public void onClick(View v) {      
                            result = "#" + rst1 + remainderR + rst2 + remainderG + rst3 + remainderB;
                            txtResult.setText(result);
                    }
                });
        }
  • 1

    final means that you are declaring a constant instead of a variable, so you can only assign the value to the txtResult in your creation. About NPE, you have Textview called txtResult in your xml?

  • Try it like this: final TextView txtResult = new TextView(ATuaActivity.this);

  • I do have Math. I even used it to show the result of an equation. I will include the line in the main post.

  • Jorge, even with the change the problem continued.

  • 1

    If I understand your dump, br.com.colorcalc.Calculator is your Activity, correct? The <init> means the code is running in the constructor. You’re actually doing all of this inside the constructor Activity or did I get something wrong? If you are creating the views inside the constructor, the concept is wrong, you should create the views (manually, or through the method setContentView) within the onCreate of Activity, or another similar place.

  • Yes, Calculator is my Activity. At the beginning of the project, I was creating my code inside onCreate, but I had a double "" error that according to what I found in the English OS, can happen when a very large code is inserted inside it. Therefore, I chose to create the code within another method, object or void.

  • So, @leo.Mind you, I don’t know a limit for lines of code within a method. Maybe your error was from a String very long? The correct is to even leave the creation of the views inside the onCreate. If you can, send a larger example of the code, even if by link.

  • Do you know any site to upload code so I can give you the link?

  • How many lines do you have? If you don’t have many (<= 200), you can ask the question. Otherwise, I know the http://pastebin.com/ where you can paste codes to share. But put the link in the question, too.

  • You are here: http://pastebin.com/sjT80S2P

  • 2

    Just remember to format the question at the end of the discussion to avoid external links. And try to ask a succinct question that is useful to future visitors and does not escape from the original question. @leo.Saddle, I recommend reading two links: How to ask a good question? and How to create a Minimum, Complete and Verifiable example

Show 6 more comments

2 answers

2


In line 40 of the code posted

btnCalc.setOnClickListener (new View.Onclicklistener()

You are using btnCalc, but it was not assigned before. Before using btnCalc lacks something like

btnCalc = (Button)findViewById(R.id.btnCalc);

One more detail, to convert an integer number x for its hexadecimal notation, it is possible to simply do this:

Integer.toHexString(x)
  • The fact of creating the event in the XML button and adding this code to the class disturbs something?

  • If you have already put in XML then you do not need to put the setOnClickListener in the middle, by the way, nor should ;) Now, if you take it out of the XML, there you can put in the code, without problems.

  • It worked, thank you!

  • 1

    Then try to optimize those hexadecimal conversions, like I told you ;)

1

Ending - For the declaration of constants.

Now on to good practice, that line of code of yours.
final TextView txtResult = new TextView(this);
In my case I maintain good practice and do the following:

- I declare all interface objects that I will use, in a global way (just below the public class). -
- Thus: private TextView txtResult; - Within the onCreate() method I refer to the variable txtResult as follows:

txtResult = (TextView) findViewById(R.id.ID_DO_OBJETO);

So this way you can use txtResult in various parts of the code.

Another good practice I use is the following: XML of the layout, in the button code, I add :

android:onClick="METODO"

Obs: within the onClick="" the method must be written without the ().
That way it’s not necessary to do what you did, which in the case was:

btnCalc.setOnClickListener (new View.OnClickListener()  {   
    public void onClick(View v){
        result = "#" + rst1 + remainderR + rst2 + remainderG + rst3 + remainderB;
        txtResult.setText(result);  
    }
});
  • Take a look at his dump... Apparently this is all happening inside the br.com.colorcalc.Calculator.<init>, i.e., the class constructor (which would not be the best place to instantiate the views). What about the final TextView txtResult ..., no problem declaring a view as final to be used within the method. It would only put as a class field if it really needed to use the view in more than one of the Activity

  • But this way I said how good practice is advisable right? than putting views on onCreate.

  • About formatting your code, you can learn a little by reading this topic: How we should format questions and answers?

  • I do not understand the question of your comment, @Enzotiezzi... If you want, then come and talk to me in the first hour, I’m a little quiet! :)

  • ok @carlosrafaelgn, after a look at the face, I left you a question, Thanks!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.