Android beginner

Johnatan56

Honorary Master
Joined
Aug 23, 2013
Messages
24,551
#1
Hi,

My class exercise is to make a basic android app that takes a name and salary on the first screen, multiplies that by 1.15 and prints it out (after clicking a button). Then it has two buttons going to other screens (screen 2 and 3). On screen 2 there are just two buttons, one going home, the other to screen 3. Screen 3 has 3 buttons, one to generate random numbers, output them and the sum of them and print a message depending on the number; the other two buttons link back home and screen 2.

The exception:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.Window.findViewById(int)' on a null object reference
at android.app.Activity.findViewById(Activity.java:2072)
at marco.classexercisesexteenthsep.ScreenOne.<init>(ScreenOne.java:15)
at java.lang.reflect.Constructor.newInstance(Native Method)


The line in question is when I start this:
EditText userName = (EditText)findViewById(R.id.name);
Could you tell me what I am doing wrong? Still new to programming/android.

The code:

Screen1 (main)
Code:
package marco.classexercisesexteenthsep;

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

public class ScreenOne extends AppCompatActivity {

    EditText userName = (EditText)findViewById(R.id.name);
    EditText salary = (EditText)findViewById(R.id.salary);
    Double oldSalary = Double.parseDouble(salary.getText().toString());
    TextView output = (TextView)findViewById(R.id.output);


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

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

        calcSalary.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Double newSalary = oldSalary * 1.15;
                output.setText("The new salary for " + userName + " is: " + newSalary);
            }
        });
    }

    public void sendScreen2(){
        Intent toScreen2 = new Intent(this, ScreenTwo.class);
        startActivity(toScreen2);
    }

    public void sendScreen3(){
        Intent toScreen3 = new Intent(this, ScreenThree.class);
        startActivity(toScreen3);
    }


    @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_screen_one, 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);
    }
}
XML of screen1
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:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".ScreenOne">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Welcome to the Home Screen"
        android:id="@+id/welcomeScreen"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="35dp"
        android:textSize="25dp" />

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:inputType="textPersonName"
        android:text="Enter name"
        android:ems="10"
        android:id="@+id/name"
        android:layout_marginTop="34dp"
        android:layout_below="@+id/welcomeScreen"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:inputType="numberDecimal"
        android:ems="10"
        android:id="@+id/salary"
        android:text="Enter Salary"
        android:layout_alignTop="@+id/name"
        android:layout_toRightOf="@+id/toScreen3"
        android:layout_toEndOf="@+id/toScreen3" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Screen 2"
        android:id="@+id/toScreen2"
        android:layout_centerVertical="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:onClick="sendScreen2"/>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Screen 3"
        android:id="@+id/toScreen3"
        android:layout_alignBottom="@+id/toScreen2"
        android:layout_centerHorizontal="true"
        android:onClick="sendScreen3"/>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="new Salary"
        android:id="@+id/calcSalary"
        android:layout_alignBottom="@+id/toScreen3"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"
        android:onClick="calcSalary"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/output"
        android:layout_below="@+id/toScreen3"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="74dp"
        android:text="Output" />
</RelativeLayout>
Screen 2
Code:
package marco.classexercisesexteenthsep;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;

/**
 * Created by Temporary on 9/15/2015.
 */
public class ScreenTwo extends Activity{
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_screen_one);
    }

    public void sendScreen3(){
        Intent toScreen3 = new Intent(this, ScreenThree.class);
        startActivity(toScreen3);
    }

    public void sendHome(){
        Intent toHome = new Intent(this, ScreenOne.class);
        startActivity(toHome);
    }
}
XML of screen 2
Code:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="match_parent">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Welcome to Screen 2"
        android:id="@+id/welcome2"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="30dp"
        android:textSize="25dp" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Screen 3"
        android:id="@+id/toScreen3"
        android:layout_above="@+id/toHome"
        android:layout_alignLeft="@+id/toHome"
        android:layout_alignStart="@+id/toHome"
        android:layout_marginBottom="35dp"
        android:onClick="sendScreen3"/>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Home"
        android:id="@+id/toHome"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true"
        android:onClick="sendHome"/>
</RelativeLayout>
Screen 3
Code:
package marco.classexercisesexteenthsep;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;

import java.util.Random;

/**
 * Created by Temporary on 9/15/2015.
 */
public class ScreenThree extends Activity {

    final TextView output = (TextView) findViewById(R.id.output);
    Random rand = new Random();

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

    public void sendScreen2(){
        Intent toScreen2 = new Intent(this, ScreenTwo.class);
        startActivity(toScreen2);
    }

    public void sendHome(){
        Intent toHome = new Intent(this, ScreenOne.class);
        startActivity(toHome);
    }

    public void generateNum(){
        float num1, num2, num3, num4, numTotal;
        String numProp;
        num1 = rand.nextFloat();
        num2 = rand.nextFloat();
        num3 = rand.nextFloat();
        num4 = rand.nextFloat();
        numTotal = num1 + num2 + num3 + num4;
        if(numTotal < 5){
            numProp = "lower number";
        }
        else numProp = "higher number";
        output.setText(num1 + "\n" + num2 + "\n" + num3 + "\n" + num4 + "\n" + numTotal + "\n" + numProp);
    }
}
 

Johnatan56

Honorary Master
Joined
Aug 23, 2013
Messages
24,551
#2
Continuation

XML of screen 3
Code:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="match_parent">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Welcome to Screen 3"
        android:id="@+id/welcome3"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="34dp"
        android:textSize="25dp" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Generate Random Num"
        android:id="@+id/generateRandom"
        android:layout_centerVertical="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:onClick="generateNum"/>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Home"
        android:id="@+id/toHome"
        android:layout_alignTop="@+id/generateRandom"
        android:layout_toLeftOf="@+id/toScreen2"
        android:layout_toStartOf="@+id/toScreen2"
        android:onClick="sendHome"/>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Screen 2"
        android:id="@+id/toScreen2"
        android:layout_alignTop="@+id/toHome"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"
        android:onClick="sendScreen2"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Random Numbes \n Total"
        android:id="@+id/output"
        android:layout_below="@+id/generateRandom"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="45dp" />
</RelativeLayout>
Android manifest
Code:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="marco.classexercisesexteenthsep" >

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".ScreenOne"
            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=".ScreenTwo"></activity>
        <activity android:name=".ScreenThree"></activity>
    </application>

</manifest>
Thanks

EDIT:
uploaded to zippyshare, about 4MB.
http://www1.zippyshare.com/v/s6DsC3Og/file.html
 
Last edited:

henry1103

Senior Member
Joined
Dec 1, 2009
Messages
583
#3
You're trying to call findViewById when the view has not been created yet.
Set these:
Code:
    EditText userName = null;
    EditText salary = null;
    Double oldSalary = null;
    TextView output = null;
Then in your onCreate, you call the findViewById and should work :)
Code:
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_screen_one);

[B]    EditText userName = (EditText)findViewById(R.id.name);
    EditText salary = (EditText)findViewById(R.id.salary);
    Double oldSalary = Double.parseDouble(salary.getText().toString());
    TextView output = (TextView)findViewById(R.id.output);[/B]

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

        calcSalary.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Double newSalary = oldSalary * 1.15;
                output.setText("The new salary for " + userName + " is: " + newSalary);
            }
        });
    }
 

Johnatan56

Honorary Master
Joined
Aug 23, 2013
Messages
24,551
#4
You're trying to call findViewById when the view has not been created yet.
Set these:
Code:
    EditText userName = null;
    EditText salary = null;
    Double oldSalary = null;
    TextView output = null;
Then in your onCreate, you call the findViewById and should work :)
Thanks, going to try it out. So the onCreate actually creates it but I am calling it before onCreate happens?
And by setting null, the value will get updated once the onCreate happens, so it won't mess with the onClickListener?

Thanks.

EDIT:
And working. Changed the first one to:
Code:
package marco.classexercisesexteenthsep;

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

public class ScreenOne extends AppCompatActivity {

    EditText userName = null;
    EditText salary = null;
    TextView output = null;

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

        userName = (EditText)findViewById(R.id.name);
        salary = (EditText)findViewById(R.id.salary);
        output = (TextView)findViewById(R.id.output);

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

        calcSalary.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final double oldSalary = Double.parseDouble(salary.getText().toString());
                final String name = String.valueOf(userName.getText());
                Double newSalary = oldSalary * 1.15;
                output.setText("The new salary for " + name + " is: " + newSalary);
            }
        });
    }

    public void sendScreen2(){
        Intent toScreen2 = new Intent(this, ScreenTwo.class);
        startActivity(toScreen2);
    }

    public void sendScreen3(){
        Intent toScreen3 = new Intent(this, ScreenThree.class);
        startActivity(toScreen3);
    }


    @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_screen_one, 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);
    }
}
 
Last edited:

henry1103

Senior Member
Joined
Dec 1, 2009
Messages
583
#5
Yes, the view needs to be created first, then you can access the gui (EditText, TextView, etc) items by findViewById.

I would also modify the calcSalary button's onClickListener to fetch the oldSalary from EditText first, so it always fetches the latest salary that the user has entered.
Code:
   [B]oldSalary = Double.parseDouble(salary.getText().toString());[/B]
   Double newSalary = oldSalary * 1.15;
   output.setText("The new salary for " + userName + " is: " + newSalary);
Same thing with userName too :)
 

Johnatan56

Honorary Master
Joined
Aug 23, 2013
Messages
24,551
#7
Yeah. Was seeing the error as well, changed it first thing when I saw it say android widget+random gibberish (running the app in an emulator).
Thanks for the help.


EDIT:
Screen One
Code:
package marco.classexercisesexteenthsep;

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

public class ScreenOne extends AppCompatActivity {

    EditText userName = null;
    EditText salary = null;
    TextView output = null;

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

        userName = (EditText)findViewById(R.id.name);
        salary = (EditText)findViewById(R.id.salary);
        output = (TextView)findViewById(R.id.output);

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

        calcSalary.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final double oldSalary = Double.parseDouble(salary.getText().toString());
                final String name = String.valueOf(userName.getText());
                Double newSalary = oldSalary * 1.15;
                output.setText("The new salary for " + name + " is: " + newSalary);
            }
        });
    }

    public void sendScreen2(View v){
        Intent toScreen2 = new Intent(this, ScreenTwo.class);
        startActivity(toScreen2);
    }

    public void sendScreen3(View v){
        Intent toScreen3 = new Intent(this, ScreenThree.class);
        startActivity(toScreen3);
    }


    @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_screen_one, 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);
    }
}

Log
Code:
09-15 17:18:39.380  13294-13294/marco.classexercisesexteenthsep D/Atlas﹕ Validating map...
09-15 17:18:39.430  13294-13309/marco.classexercisesexteenthsep D/﹕ HostConnection::get() New Host Connection established 0x7f46ddcea7c0, tid 13309
09-15 17:18:39.460  13294-13309/marco.classexercisesexteenthsep I/OpenGLRenderer﹕ Initialized EGL, version 1.4
09-15 17:18:39.590  13294-13309/marco.classexercisesexteenthsep D/OpenGLRenderer﹕ Enabling debug mode 0
09-15 17:18:39.610  13294-13309/marco.classexercisesexteenthsep W/EGL_emulation﹕ eglSurfaceAttrib not implemented
09-15 17:18:39.610  13294-13309/marco.classexercisesexteenthsep W/OpenGLRenderer﹕ Failed to set EGL_SWAP_BEHAVIOR on surface 0x7f46ddc8fe40, error=EGL_SUCCESS
09-15 17:18:42.730  13294-13309/marco.classexercisesexteenthsep W/EGL_emulation﹕ eglSurfaceAttrib not implemented
09-15 17:18:42.730  13294-13309/marco.classexercisesexteenthsep W/OpenGLRenderer﹕ Failed to set EGL_SWAP_BEHAVIOR on surface 0x7f46dde74ac0, error=EGL_SUCCESS
09-15 17:18:42.920  13294-13309/marco.classexercisesexteenthsep D/OpenGLRenderer﹕ endAllStagingAnimators on 0x7f46ddcdc800 (RippleDrawable) with handle 0x7f46ddd5bae0
09-15 17:18:46.530  13294-13294/marco.classexercisesexteenthsep D/AndroidRuntime﹕ Shutting down VM
09-15 17:18:46.530  13294-13294/marco.classexercisesexteenthsep E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: marco.classexercisesexteenthsep, PID: 13294
    java.lang.IllegalStateException: Could not find a method sendScreen2(View) in the activity class marco.classexercisesexteenthsep.ScreenTwo for onClick handler on view class android.widget.Button with id 'toScreen2'
            at android.view.View$1.onClick(View.java:4007)
            at android.view.View.performClick(View.java:4780)
            at android.view.View$PerformClick.run(View.java:19866)
            at android.os.Handler.handleCallback(Handler.java:739)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5257)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
     Caused by: java.lang.NoSuchMethodException: sendScreen2 [class android.view.View]
I am assuming it is this section that is wrong:
Code:
    public void sendScreen2(View v){
        Intent toScreen2 = new Intent(this, ScreenTwo.class);
        startActivity(toScreen2);
    }
I click once (time-log: 17:18:42), nothing happens, click again (time-log: 17:18:46) and it crashes.

EDIT2: Sorry, was an idiot. Set the content view in the second class wrongly.
 
Last edited:

CamiKaze

Honorary Master
Joined
May 19, 2010
Messages
13,153
#8
I don't get it. I am trying to install Android Studio and it seems the install is looking for the string "JDK" where I installed a JRE for Eclipse.
What if I want to point to jre1.8 instead of having to download and install the JDK?

1.jpg
 

Johnatan56

Honorary Master
Joined
Aug 23, 2013
Messages
24,551
#9
I don't get it. I am trying to install Android Studio and it seems the install is looking for the string "JDK" where I installed a JRE for Eclipse.
What if I want to point to jre1.8 instead of having to download and install the JDK?

View attachment 322679
I installed the JDK first, needed it for Visual Studio. Do you have the 64bit version of the jdk installed?
 

Johnatan56

Honorary Master
Joined
Aug 23, 2013
Messages
24,551
#11
Aah, I have the 32-bit JRE installed. Thanks for pointing that out, let me proceed with this download then. :mad:
Have fun. Do install Intel HAXM, speeds up the emulator quite a bit. If you have a problem installing it, just shout, I figured it out.
 
Top