Search code examples
javaandroidnullpointerexceptionnumberformatexception

NullPointerException/NumberFormatException ("unable to instantiate activity ComponentInfo")


I am new with Android, and I am doing a little game for Android 2.3.3 But when I run on AVD, it closes automatically

The code is like this

package dam.moviles.adivinaminumero;

import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.*;
import android.widget.*;
import java.util.*;

public class MainActivity extends ActionBarActivity 
{
    int intentos;
    Random dado=new Random();
    int numAdivinar=dado.nextInt(100)+1;
    Button boton=(Button) findViewById(R.id.button1);
    EditText et=(EditText)findViewById(R.id.cajaNumero);
    TextView tv=(TextView)findViewById(R.id.textView1);
    int numero=Integer.parseInt(et.getText().toString());

    @Override
    protected void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        et.setOnKeyListener(new android.view.View.OnKeyListener()
        { 
            public boolean onKey(View v, int keyCode, android.view.KeyEvent event)
            {
                if ((event.getAction() == android.view.KeyEvent.ACTION_DOWN) && (keyCode == android.view.KeyEvent.KEYCODE_ENTER)) 
                {
                    if(numero<numAdivinar)
                    {
                        String format=getResources().getString(R.string.mensajeMayor);
                        String cadFinal=String.format(format, numero);
                        tv.setText(cadFinal);
                    }
                    else if(numero>numAdivinar)
                    {
                        String format=getResources().getString(R.string.mensajeMenor);
                        String cadFinal=String.format(format, numero);
                        tv.setText(cadFinal);
                    }
                    else
                    {
                        tv.setText(R.string.acierto);
                    }
                    return true;
                }
                else
                {
                    return false;
                }
            }
        });
    }
}

And throws a NullPointerException

If I put the code inside OnCreate, like this

package dam.moviles.adivinaminumero;

import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.*;
import android.widget.*;
import java.util.*;

public class MainActivity extends ActionBarActivity 
{
    int intentos;
    Random dado=new Random();
    int numAdivinar=dado.nextInt(100)+1;
    Button boton;
    EditText et;
    TextView tv;
    int numero;

    @Override
    protected void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        boton=(Button) findViewById(R.id.button1);
        et=(EditText)findViewById(R.id.cajaNumero);
        tv=(TextView)findViewById(R.id.textView1);
        numero=Integer.parseInt(et.getText().toString());

        et.setOnKeyListener(new android.view.View.OnKeyListener()
        { 
            public boolean onKey(View v, int keyCode, android.view.KeyEvent event)
            {
                if ((event.getAction() == android.view.KeyEvent.ACTION_DOWN) && (keyCode == android.view.KeyEvent.KEYCODE_ENTER)) 
                {
                    if(numero<numAdivinar)
                    {
                        String format=getResources().getString(R.string.mensajeMayor);
                        String cadFinal=String.format(format, numero);
                        tv.setText(cadFinal);
                    }
                    else if(numero>numAdivinar)
                    {
                        String format=getResources().getString(R.string.mensajeMenor);
                        String cadFinal=String.format(format, numero);
                        tv.setText(cadFinal);
                    }
                    else
                    {
                        tv.setText(R.string.acierto);
                    }
                    return true;
                }
                else
                {
                    return false;
                }
            }
        });
    }

throws a NumberFormatException, with this LogCat

11-18 17:00:22.621: D/AndroidRuntime(595): Shutting down VM
11-18 17:00:22.621: W/dalvikvm(595): threadid=1: thread exiting with uncaught exception (group=0x40015560)
11-18 17:00:22.641: E/AndroidRuntime(595): FATAL EXCEPTION: main
11-18 17:00:22.641: E/AndroidRuntime(595): java.lang.RuntimeException: Unable to start activity ComponentInfo{dam.moviles.adivinaminumero/dam.moviles.adivinaminumero.MainActivity}: java.lang.NumberFormatException: unable to parse '' as integer
11-18 17:00:22.641: E/AndroidRuntime(595):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647)
11-18 17:00:22.641: E/AndroidRuntime(595):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
11-18 17:00:22.641: E/AndroidRuntime(595):  at android.app.ActivityThread.access$1500(ActivityThread.java:117)
11-18 17:00:22.641: E/AndroidRuntime(595):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
11-18 17:00:22.641: E/AndroidRuntime(595):  at android.os.Handler.dispatchMessage(Handler.java:99)
11-18 17:00:22.641: E/AndroidRuntime(595):  at android.os.Looper.loop(Looper.java:123)
11-18 17:00:22.641: E/AndroidRuntime(595):  at android.app.ActivityThread.main(ActivityThread.java:3683)
11-18 17:00:22.641: E/AndroidRuntime(595):  at java.lang.reflect.Method.invokeNative(Native Method)
11-18 17:00:22.641: E/AndroidRuntime(595):  at java.lang.reflect.Method.invoke(Method.java:507)
11-18 17:00:22.641: E/AndroidRuntime(595):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
11-18 17:00:22.641: E/AndroidRuntime(595):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
11-18 17:00:22.641: E/AndroidRuntime(595):  at dalvik.system.NativeStart.main(Native Method)
11-18 17:00:22.641: E/AndroidRuntime(595): Caused by: java.lang.NumberFormatException: unable to parse '' as integer
11-18 17:00:22.641: E/AndroidRuntime(595):  at java.lang.Integer.parseInt(Integer.java:362)
11-18 17:00:22.641: E/AndroidRuntime(595):  at java.lang.Integer.parseInt(Integer.java:332)
11-18 17:00:22.641: E/AndroidRuntime(595):  at dam.moviles.adivinaminumero.MainActivity.onCreate(MainActivity.java:28)
11-18 17:00:22.641: E/AndroidRuntime(595):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
11-18 17:00:22.641: E/AndroidRuntime(595):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
11-18 17:00:22.641: E/AndroidRuntime(595):  ... 11 more
11-18 17:00:25.701: I/Process(595): Sending signal. PID: 595 SIG: 9

Thanks a bunch


Solution

  • The second way (the one that throws the NumberFormatException is the one that I am referring to in this answer, as this is the more-correct one).

    Declare et as final and move numero=Integer.parseInt(et.getText().toString()); to within your onKey method. The reason that you are getting an error is that your EditText is empty when your app is first created, and since you are also trying to assign numero when the app is first started, there is nothing to parse.

    By moving numero=Integer.parseInt(et.getText().toString()); to within onKey, you are telling it to only parse when something has been entered.

    This will still give you an error if a user enters something into the EditText that cannot have a number parsed from it, so you can either specify that only numbers may be entered into the EditText, or you can surround the parsing method with a try/catch block.

    In your XML, use android:inputType="number" to enforce that only numbers may be entered.