0

I'm having a few issues resolving a null point exception on an onClick function - I'll put the code in here in the hope someone can spot something I can't.

Main class:

package org.matthewdann.mathsapp;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        //insert buttons to get different activities
        //SUVAT
        Button buttonSUVAT = (Button) findViewById(R.id.buttonSUVAT);
        buttonSUVAT.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(MainActivity.this, suvatSolver.class));
            }
        });
        //Temp Converter
        Button tempConvertButton = (Button) findViewById(R.id.temp_convert_button);
        tempConvertButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(MainActivity.this, TempConverter.class));
            }

        });
    }
        @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

Manifest:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="org.matthewdann.mathsapp">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity
            android:name="org.matthewdann.mathsapp.MainActivity"
            android:label="@string/app_name"
            android:theme="@style/AppTheme.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name="org.matthewdann.mathsapp.suvatSolver"
            android:label="@string/title_activity_suvat_solver"
            android:theme="@style/AppTheme.NoActionBar" />
        <activity
            android:name="org.matthewdann.mathsapp.TempConverter"
            android:label="@string/title_activity_temp_converter"
            android:theme="@style/AppTheme.NoActionBar">

        </activity>
    </application>

</manifest>

Logcat:

03-10 21:32:27.061 11535-11535/org.matthewdann.mathsapp D/AndroidRuntime: Shutting down VM
03-10 21:32:27.062 11535-11535/org.matthewdann.mathsapp E/AndroidRuntime: FATAL EXCEPTION: main
                                                                          Process: org.matthewdann.mathsapp, PID: 11535
                                                                          java.lang.RuntimeException: Unable to start activity ComponentInfo{org.matthewdann.mathsapp/org.matthewdann.mathsapp.TempConverter}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
                                                                              at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
                                                                              at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
                                                                              at android.app.ActivityThread.-wrap11(ActivityThread.java)
                                                                              at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
                                                                              at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                              at android.os.Looper.loop(Looper.java:148)
                                                                              at android.app.ActivityThread.main(ActivityThread.java:5417)
                                                                              at java.lang.reflect.Method.invoke(Native Method)
                                                                              at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
                                                                              at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
                                                                           Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
                                                                              at org.matthewdann.mathsapp.TempConverter.onCreate(TempConverter.java:42)
                                                                              at android.app.Activity.performCreate(Activity.java:6251)
                                                                              at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
                                                                              at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
                                                                              at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) 
                                                                              at android.app.ActivityThread.-wrap11(ActivityThread.java) 
                                                                              at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) 
                                                                              at android.os.Handler.dispatchMessage(Handler.java:102) 
                                                                              at android.os.Looper.loop(Looper.java:148) 
                                                                              at android.app.ActivityThread.main(ActivityThread.java:5417) 
                                                                              at java.lang.reflect.Method.invoke(Native Method) 
                                                                              at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
                                                                              at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 

EDIT: content_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    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"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="org.matthewdann.mathsapp.MainActivity"
    tools:showIn="@layout/activity_main">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="@string/app_name"
        android:id="@+id/mainPageHeader"
        android:layout_below="@+id/adView1"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/buttonSUVAT"
        android:id="@+id/buttonSUVAT"
        android:layout_below="@+id/mainPageHeader"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/temp_convert_button"
        android:id="@+id/temp_convert_button"
        android:layout_below="@+id/buttonSUVAT"
        android:layout_alignRight="@+id/buttonSUVAT"
        android:layout_alignEnd="@+id/buttonSUVAT"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />
</RelativeLayout>

EDIT 2 - tempConverter:

package org.matthewdann.mathsapp;

import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.text.DecimalFormat;

public class TempConverter extends AppCompatActivity {
    private EditText tempEditText;
    private TextView showTempTextView;
    DecimalFormat round = new DecimalFormat("0.0");
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        //define Text and button variables
        tempEditText = (EditText) findViewById(R.id.TempInput);
        Button cButton = (Button) findViewById(R.id.buttonC);
        Button fButton = (Button) findViewById(R.id.buttonF);
        showTempTextView = (TextView) findViewById(R.id.Output);

        //button event listeners

        fButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //hide keyboard
                InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                inputManager.hideSoftInputFromWindow((null == getCurrentFocus()) ? null : getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                //error if empty
                String editTextVal = tempEditText.getText().toString();
                if (editTextVal.isEmpty()) {
                    Toast.makeText(getApplicationContext(), "Enter a value", Toast.LENGTH_LONG).show();
                } else {
                    //something has been entered - parse into decimal
                    double doubleEditText = Double.parseDouble(editTextVal);
                    //convert
                    double convertedVal1 = convertToCelsius(doubleEditText);
                    double convertedVal2 = (273.15 + convertedVal1);
                    if (0 < convertedVal2) {
                        //parse into string for output
                        String stringResult = String.valueOf(round.format(convertedVal1) + " C ; " + round.format(convertedVal2) + " K ");
                        showTempTextView.setText(stringResult);
                    } else {
                        String stringResult = String.valueOf("Error!");
                        showTempTextView.setText(stringResult);
                        Toast.makeText(getApplicationContext(), "Value is too small!", Toast.LENGTH_LONG).show();
                    }
                }
            }
        });
        cButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //convert to f
                InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                inputManager.hideSoftInputFromWindow((null == getCurrentFocus()) ? null : getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                String editTextVal = tempEditText.getText().toString();
                if (editTextVal.isEmpty()) {
                    Toast.makeText(getApplicationContext(), "Edit a value", Toast.LENGTH_LONG).show();
                } else {
                    //something entered
                    double doubleEditText = Double.parseDouble(editTextVal);
                    double convertedVal = convertToF(doubleEditText);
                    double convertedVal2 = (273.15 + doubleEditText);

                    if (0 < convertedVal2) {
                        String stringResult = String.valueOf(round.format(convertedVal) + " F ; " + round.format(convertedVal2) + " K ");
                        showTempTextView.setText(stringResult);
                    } else {
                        Toast.makeText(getApplicationContext(), "Value is too small!", Toast.LENGTH_LONG).show();
                        String stringResult = String.valueOf("Error!");
                        showTempTextView.setText(stringResult);
                    }
                }
            }
        });
    }

    public double convertToCelsius (double farVal) {
        double resultCel;
        resultCel = (farVal - 32) * 5/9;
        return resultCel;
    }
    public double convertToF (double celVar) {
        double resultF;
        resultF = (celVar * 9/5) + 32;
        return resultF;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}
  • Possible duplicate of [What is a Null Pointer Exception, and how do I fix it?](http://stackoverflow.com/questions/218384/what-is-a-null-pointer-exception-and-how-do-i-fix-it) – NoChinDeluxe Mar 10 '16 at 21:44
  • Did you declare buttons id in XML with `@+id/temp_convert_button` ? – Ozgur Mar 10 '16 at 21:45
  • You are trying to set an onClick listener on a button that doesn't exist. Make sure it exists in your layout file and is inflated correctly before trying to access it. – NoChinDeluxe Mar 10 '16 at 21:45
  • I believe I have declared it - I've posted the xml just in case I've missed something! I'd note the button above it is declared in the same way (I think), so I'm not sure what I've done! – Matthew Dann Mar 10 '16 at 21:48
  • Also read this [What is a stack trace, and how can I use it to debug my application errors?](http://stackoverflow.com/questions/3988788/what-is-a-stack-trace-and-how-can-i-use-it-to-debug-my-application-errors) – headsvk Mar 10 '16 at 21:49
  • 2
    The crash doesn't even happen in MainActivity but in TempConverter `org.matthewdann.mathsapp.TempConverter.onCreate(TempConverter.java:42)` – headsvk Mar 10 '16 at 21:50
  • Your code is trying to load a layout called "activity_main" but your question details refer to it as "content_main". Is that a typo in your question above or have you mixed up two layout files? – Robert Nekic Mar 10 '16 at 21:52
  • @RobertNekic - this is correct (activity_main then loads content_main) - this appears to be the way Android does it – Matthew Dann Mar 10 '16 at 21:56
  • 1
    Can you post your code for TempConverter? That's where the crash is happening. – Submersed Mar 10 '16 at 22:01
  • Got it - I didn't change a reference there when I merged the two together, thanks all! – Matthew Dann Mar 10 '16 at 22:03

4 Answers4

0

firstly Check to see if

R.id.temp_convert_button 

is in the same XML as

R.layout.activity_main.

you may well find that findViewById() is returning null. try

Button tempConvertButton = (Button) findViewById(R.id.temp_convert_button)
Log.i("test"," is null " +(null == tempConvertButton));
Mark Gilchrist
  • 1,972
  • 3
  • 24
  • 44
0

The issue isn't with the onClick-method, it's where you register the listener! The button object is null, and such things happen most likely if you try to use findViewById() when the required XML file isn't loaded yet. Try moving the Listener registration to onCreateView()

Namnodorel
  • 385
  • 5
  • 17
0

I think you are calling the wrong layout. In your code you are asking for activity_main layout, but your layout file seems to be content_main.xml.

Try to change setContentView(R.layout.activity_main); to setContentView(R.layout.content_main);

Or just rename content_main.xml file to activity_main.xml

Edit:

Following your second edit, it seems that you are using the same layout for two activities. You might refer to a wrong layout in some cases.

0

So I had a rogue instance of setContentView(R.layout.activity_main); in the app - fixing that seems to resolve the issue!

Jonas Czech
  • 12,018
  • 6
  • 44
  • 65