简体   繁体   中英

Can't get simple android calculator app to run

I have been spending a little time going over some of Google's android tutorials, and decided to throw together my own simple calculator application. I know a good bit of JAVA, and have messed around a little bit of Android back a few SDKs ago. I think the code is fine, but I just can't get the bastard to run. I have been trying to find an answer based on my LogCat stuff, but have had no luck. First, here is my MainActivity.java:

package com.AppliedArgonautics.calculator;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends Activity {
    EditText editText1 = (EditText)findViewById(R.id.editText1);
    EditText editText2 = (EditText)findViewById(R.id.editText2);
    TextView textView1 = (TextView)findViewById(R.id.textView1);

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

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.activity_main, menu);
    return true;
}
public void Add(){
    float num1 = Float.parseFloat(editText1.getText().toString());
    float num2 = Float.parseFloat(editText2.getText().toString());
    float result = num1 + num2;
    textView1.setText(Float.toString(result));
}
public void Subtract(){
    float num1 = Float.parseFloat(editText1.getText().toString());
    float num2 = Float.parseFloat(editText2.getText().toString());
    float result = num1 - num2;
    textView1.setText(Float.toString(result));
}
public void Multiply(){
    float num1 = Float.parseFloat(editText1.getText().toString());
    float num2 = Float.parseFloat(editText2.getText().toString());
    float result = num1 * num2;
    textView1.setText(Float.toString(result));
}
public void Divide(){
    float num1 = Float.parseFloat(editText1.getText().toString());
    float num2 = Float.parseFloat(editText2.getText().toString());
    float result = num1 / num2;
    textView1.setText(Float.toString(result));
}
public void Clear(){
    editText1.setText("");
    editText2.setText("");
    textView1.setText("");
}
}

My manifest file:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.AppliedArgonautics.calculator"
    android:versionCode="1"
    android:versionName="1.0" >

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

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

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

then, the activity_main.xml

<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" >

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_centerVertical="true"
        android:layout_marginLeft="32dp"
        android:onClick="Add"
        android:text="Add" />

    <Button
        android:id="@+id/button3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/button1"
        android:layout_below="@+id/button1"
        android:layout_marginTop="45dp"
        android:onClick="Multiply"
        android:text="Multiply" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/button3"
        android:layout_alignParentRight="true"
        android:layout_marginRight="28dp"
        android:onClick="Subtract"
        android:text="Subtract" />

    <Button
        android:id="@+id/button4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/button3"
        android:layout_alignBottom="@+id/button3"
        android:layout_alignLeft="@+id/button2"
        android:onClick="Divide"
        android:text="Divide" />

     <Button
         android:id="@+id/button5"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:layout_below="@+id/button1"
         android:layout_centerHorizontal="true"
         android:onClick="Clear"
         android:text="Clear" />

     <EditText
        android:id="@+id/editText1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_alignRight="@+id/button1"
        android:layout_marginTop="37dp"
        android:ems="10"
        android:inputType="phone" >

        <requestFocus />
    </EditText>

    <EditText
        android:id="@+id/editText2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/editText1"
        android:layout_alignLeft="@+id/button2"
        android:layout_alignParentRight="true"
        android:layout_alignTop="@+id/editText1"
        android:ems="10"
        android:inputType="phone" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/button5"
        android:layout_below="@+id/editText1"
        android:layout_marginTop="56dp"
        android:text="TextView" />

</RelativeLayout>

This is what LogCat shows when I try to run it:

/Trace   ( 3186): error opening trace file: No such file or directory (2)
D/AndroidRuntime( 3186): Shutting down VM
W/dalvikvm( 3186): threadid=1: thread exiting with uncaught exception (group=0x40a13300)
E/AndroidRuntime( 3186): FATAL EXCEPTION: main
E/AndroidRuntime( 3186): java.lang.RuntimeException: Unable to instantiate activity           ComponentInfo{com.AppliedArgonautics.calculator/com.AppliedArgonautics.calculator.MainActivi    ty}: java.lang.NullPointerException
E/AndroidRuntime( 3186):    at     android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1983)
E/AndroidRuntime( 3186):    at     android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
E/AndroidRuntime( 3186):    at     android.app.ActivityThread.access$600(ActivityThread.java:130)
E/AndroidRuntime( 3186):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
E/AndroidRuntime( 3186):    at android.os.Handler.dispatchMessage(Handler.java:99)
E/AndroidRuntime( 3186):    at android.os.Looper.loop(Looper.java:137)
E/AndroidRuntime( 3186):    at android.app.ActivityThread.main(ActivityThread.java:4745)
E/AndroidRuntime( 3186):    at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime( 3186):    at java.lang.reflect.Method.invoke(Method.java:511)
E/AndroidRuntime( 3186):    at  com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
E/AndroidRuntime( 3186):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
E/AndroidRuntime( 3186):    at dalvik.system.NativeStart.main(Native Method)
E/AndroidRuntime( 3186): Caused by: java.lang.NullPointerException
E/AndroidRuntime( 3186):    at android.app.Activity.findViewById(Activity.java:1825)
E/AndroidRuntime( 3186):    at com.AppliedArgonautics.calculator.MainActivity.<init>(MainActivity.java:10)
E/AndroidRuntime( 3186):    at java.lang.Class.newInstanceImpl(Native Method)
E/AndroidRuntime( 3186):    at java.lang.Class.newInstance(Class.java:1319)
E/AndroidRuntime( 3186):    at  android.app.Instrumentation.newActivity(Instrumentation.java:1053)
E/AndroidRuntime( 3186):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1974)
E/AndroidRuntime( 3186):    ... 11 more
W/ActivityManager(  160):   Force finishing activity com.AppliedArgonautics.calculator/.MainActivity

I would really appreciate it if someone could have a look at this. I thought it would be cool to learn android, but am getting very frustrated with my inability to get even a simple program like this to launch. Thank you.

There may be lot of issues in your code, but first to get you started:

Create EditText and TextView as instance variables. Assign views to those variables in onCreate .

public class MainActivity extends Activity {
        EditText editText1;
        EditText editText2;
        TextView textView1;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
     editText1 = (EditText)findViewById(R.id.editText1);
     editText2 = (EditText)findViewById(R.id.editText2);
     textView1 = (TextView)findViewById(R.id.textView1);
    }
.........
}

I loaded up your application, and ran the application in debug mode. It broke on the line

EditText editText1 = (EditText)findViewById(R.id.editText1);

It was throwing a null pointer exception because you have not yet loaded your layout. This happens in your OnCreate function. The solution is to shift the findViewById command into your onCreate function after the SetContentView command. Ie:

public class MainActivity extends Activity {
    EditText editText1;
    EditText editText2;
    TextView textView1;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    editText1 = (EditText)findViewById(R.id.editText1);
    editText2 = (EditText)findViewById(R.id.editText2);
    textView1 = (TextView)findViewById(R.id.textView1);
}

Your next issues are that the functions that your Add, Subtract, etc functions all need to take a parameter of type View. This is the reference back to the button that was clicked. (Otherwise you get an IllegalStateException when it can't find the function to call)

Then it's going to fail on Float.parseFloat(editText1.getText().toString()) because the the editText contains blank, not a number. You'll want to either force the edit texts to always have a valid number, or modify your functions to cater for empty strings.

Good luck from here! :)

I did here for adding the values.. Your created the button in xml but, not using in java code.. we need to do our stuff under button click listener...

public class MainActivity extends Activity {
    EditText editText1 ;
    EditText editText2 ;
    TextView textView1 ;
    float num1, num2,result;
    Button add;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    editText1 = (EditText)findViewById(R.id.editText1);
    editText2 = (EditText)findViewById(R.id.editText2);
    textView1 = (TextView)findViewById(R.id.textView1);
    add = (Button)findViewById(R.id.button1);
    add.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
             num1 = Float.parseFloat(editText1.getText().toString());
             num2 = Float.parseFloat(editText2.getText().toString());
             result = num1 + num2;
            textView1.setText(Float.toString(result));
        }
    });
}


}

Apply the same thing for all methods...

Hope, this will helps you..

write these

EditText editText1; 
EditText editText2;
TextView textView1 ;

instead of these

EditText editText1 = (EditText)findViewById(R.id.editText1);
EditText editText2 = (EditText)findViewById(R.id.editText2);
TextView textView1 = (TextView)findViewById(R.id.textView1);

and change this

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

to

@Override
public void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);
 editText1 = (EditText)findViewById(R.id.editText1);
 editText2 = (EditText)findViewById(R.id.editText2);
 textView1 = (TextView)findViewById(R.id.textView1);

}

You are getting error because you are trying to access the views without specifying which layout you are considering.

 setContentView(R.layout.activity_main);

specifies the layout you are considering

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM