Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to start activity ComponentInfo{...}: java.lang.NullPointerException

As I just started my first Android application, I've been granted with my first issues.

The code below is quite simple and the only goal is to navigate from MainActivity.java to IMC.java However, I've been looking for a solution to this on a lot of tutorial and I really don't get what I'm doing wrong...

package com.example.firstapp;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Button;
import android.view.View;
import android.view.View.OnClickListener;

public class MainActivity extends Activity {

    Button IMC;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        IMC = (Button) findViewById(R.id.buttonIMC);
        IMC.setOnClickListener(IMCListener);
    }

    // Listener du bouton IMC
    private OnClickListener IMCListener = new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i = new Intent(MainActivity.this,IMC.class);
                startActivity(i); 
           }
    };
}

In the activity_main.xml, I got the following code:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".IMC" >


    <Button
        android:id="@+id/buttonIMC"
        style="?android:attr/buttonStyleSmall"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentRight="true"
        android:text="IMC" />

</RelativeLayout>

The stack trace is

11-03 16:30:04.877: E/AndroidRuntime(619): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.firstapp/com.example.firstapp.IMC}: java.lang.NullPointerException
11-03 16:30:04.877: E/AndroidRuntime(619):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
11-03 16:30:04.877: E/AndroidRuntime(619):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
11-03 16:30:04.877: E/AndroidRuntime(619):  at android.app.ActivityThread.access$2300(ActivityThread.java:125)
11-03 16:30:04.877: E/AndroidRuntime(619):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
11-03 16:30:04.877: E/AndroidRuntime(619):  at android.os.Handler.dispatchMessage(Handler.java:99)
11-03 16:30:04.877: E/AndroidRuntime(619):  at android.os.Looper.loop(Looper.java:123)
11-03 16:30:04.877: E/AndroidRuntime(619):  at android.app.ActivityThread.main(ActivityThread.java:4627)
11-03 16:30:04.877: E/AndroidRuntime(619):  at java.lang.reflect.Method.invokeNative(Native Method)
11-03 16:30:04.877: E/AndroidRuntime(619):  at java.lang.reflect.Method.invoke(Method.java:521)
11-03 16:30:04.877: E/AndroidRuntime(619):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
11-03 16:30:04.877: E/AndroidRuntime(619):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
11-03 16:30:04.877: E/AndroidRuntime(619):  at dalvik.system.NativeStart.main(Native Method)
11-03 16:30:04.877: E/AndroidRuntime(619): Caused by: java.lang.NullPointerException
11-03 16:30:04.877: E/AndroidRuntime(619):  at com.example.firstapp.IMC.onCreate(IMC.java:57)
11-03 16:30:04.877: E/AndroidRuntime(619):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
11-03 16:30:04.877: E/AndroidRuntime(619):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)

And the manifest is here below

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.firstapp"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="18" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.firstapp.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name="com.example.firstapp.MainActivity2"
            android:label="@string/title_activity_main_activity2" >
        </activity>
        <activity
            android:name="com.example.firstapp.IMCActivity"
            android:label="@string/title_activity_imc" >
        </activity>
        <activity
            android:name="com.example.firstapp.Interest"
            android:label="@string/title_activity_interest" >
        </activity>
        <activity
            android:name="com.example.firstapp.IMC"
            android:label="@string/title_activity_imc" >
        </activity>
    </application>

</manifest>

The activity IMC is already set and is working properly (basically, it is only a simple computation) And to be totally exhaustive here it is:

package com.example.firstapp;


import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
import android.text.TextWatcher;
import android.text.Editable;

public class IMC extends Activity {
  // La chaîne de caractères par défaut
  private final String defaut = "Vous devez cliquer sur le bouton « Calculer l'IMC » pour obtenir un résultat.";
  // La chaîne de caractères de la megafonction
  private final String megaString = "Vous faites un poids parfait ! Wahou ! Trop fort ! On dirait Brad Pitt (si vous êtes un homme)/Angelina Jolie (si vous êtes une femme)/Willy (si vous êtes un orque) !";

  Button envoyer = null;
  Button raz = null;

  EditText poids = null;
  EditText taille = null;

  RadioGroup group = null;

  TextView result = null;

  CheckBox mega = null;


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

    // On récupère toutes les vues dont on a besoin
    envoyer = (Button)findViewById(R.id.calcul);

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

    taille = (EditText)findViewById(R.id.taille);
    poids = (EditText)findViewById(R.id.poids);

    mega = (CheckBox)findViewById(R.id.mega);

    group = (RadioGroup)findViewById(R.id.group);

    result = (TextView)findViewById(R.id.result);

    // On attribue un listener adapté aux vues qui en ont besoin
    envoyer.setOnClickListener(envoyerListener);
    raz.setOnClickListener(razListener);
    taille.addTextChangedListener(textWatcher);
    poids.addTextChangedListener(textWatcher);

    // Solution avec des onKey
    //taille.setOnKeyListener(modificationListener);
    //poids.setOnKeyListener(modificationListener);
    mega.setOnClickListener(checkedListener);
  }

  /*
  // Se lance à chaque fois qu'on appuie sur une touche en étant sur un EditText
  private OnKeyListener modificationListener = new OnKeyListener() {
    @Override
    public boolean onKey(View v, int keyCode, KeyEvent event) {
      // On remet le texte à sa valeur par défaut pour ne pas avoir de résultat incohérent
      result.setText(defaut);
      return false;
    }
  };*/

  private TextWatcher textWatcher = new TextWatcher() {

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
      result.setText(defaut);
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count,
      int after) {

    }

    @Override
    public void afterTextChanged(Editable s) {

    }
  };

  // Uniquement pour le bouton "envoyer"
  private OnClickListener envoyerListener = new OnClickListener() {
    @Override
    public void onClick(View v) {
      if(!mega.isChecked()) {
        // Si la megafonction n'est pas activée
        // On récupère la taille
        String t = taille.getText().toString();
        // On récupère le poids
        String p = poids.getText().toString();

        float tValue = Float.valueOf(t);

        // Puis on vérifie que la taille est cohérente
        if(tValue == 0)
          Toast.makeText(IMC.this, "Hého, tu es un Minipouce ou quoi ?", Toast.LENGTH_SHORT).show();
        else {
          float pValue = Float.valueOf(p);
          // Si l'utilisateur a indiqué que la taille était en centimètres
          // On vérifie que la Checkbox sélectionnée est la deuxième à l'aide de son identifiant
          if(group.getCheckedRadioButtonId() == R.id.radio2)
            tValue = tValue / 100;

          tValue = (float)Math.pow(tValue, 2);
          float imc = pValue / tValue;
          result.setText("Votre IMC est " + String.valueOf(imc));
        }
      } else
        result.setText(megaString);
    }
  };

  // Listener du bouton de remise à zéro
  private OnClickListener razListener = new OnClickListener() {
    @Override
    public void onClick(View v) {
      poids.getText().clear();
      taille.getText().clear();
      result.setText(defaut);
    }
  };

  // Listener du bouton de la megafonction.
  private OnClickListener checkedListener = new OnClickListener() {
    @Override
    public void onClick(View v) {
      // On remet le texte par défaut si c'était le texte de la megafonction qui était écrit
      if(!((CheckBox)v).isChecked() && result.getText().equals(megaString))
        result.setText(defaut);
    }
  };
}

(this code above is not from me, it comes from a tutorial found on openclassroom)

Would you have any idea, it would be much appreciated :)

Thanks!

like image 284
ChrisH127 Avatar asked Nov 03 '13 16:11

ChrisH127


People also ask

How do I fix Java Lang NullPointerException in Java?

In Java, the java. lang. NullPointerException is thrown when a reference variable is accessed (or de-referenced) and is not pointing to any object. This error can be resolved by using a try-catch block or an if-else condition to check if a reference variable is null before dereferencing it.

What causes Java Lang NullPointerException?

What Causes NullPointerException. The NullPointerException occurs due to a situation in application code where an uninitialized object is attempted to be accessed or modified. Essentially, this means the object reference does not point anywhere and has a null value.

How do I ignore Java Lang NullPointerException?

Answer: Some of the best practices to avoid NullPointerException are: Use equals() and equalsIgnoreCase() method with String literal instead of using it on the unknown object that can be null. Use valueOf() instead of toString() ; and both return the same result. Use Java annotation @NotNull and @Nullable.

What does this mean Error 500 Java Lang NullPointerException?

You may encounter the 'error 500:Java. lang. nullpointerexception' on a Java-based game (like Minecraft) if the game's installation is corrupt as the game's modules are not able to perform the designated role. In this scenario, reinstalling the problematic game may clear the error at hand.


1 Answers

Line 57 of IMC.java envoyer.setOnClickListener(envoyerListener)

Looks like envoyer is null.

You have

   setContentView(R.layout.activity_main);

Your activity_main.xml does not have a button with that id R.id.calcul.

You need to change this

  setContentView(R.layout.imc); // layout xml for IMC Activity

Make sure it has a button with the id R.id.calcul and it will work.

like image 138
Raghunandan Avatar answered Oct 14 '22 14:10

Raghunandan