简体   繁体   中英

App crashes on launching other Activity

So I created an app to calculate food costs, but when I press the button to take me to the activity that calculates the app crashes. The App would change fine until I added the methods to do the actual calculation. I'm new to this so I realize the code might be kind of messy.

Launcher Activity:

    package com.example.foodcostcalculator;

import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.app.Activity;

public class ActivityHome extends Activity {

private TextView mMainHeader;
private Button mStartCalc;

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


    mStartCalc = (Button)findViewById(R.id.calc_button);
    mStartCalc.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            final Intent intent1 = new Intent(ActivityHome.this, StartCalc.class);
            if (intent1 != null) {
                startActivity(intent1);
            }
        }
    });

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.activity_home, 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();
    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}
}

StartCalc Activity:

    package com.example.foodcostcalculator;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class StartCalc extends Activity {

private Button mBackButton;
private EditText mItemName;
private EditText mItemCost;
private EditText mSellPercent;
private EditText mSellAmount;
private Button mCalculate;

String item = mItemName.getText().toString();                                    
String itcost = mItemCost.getText().toString();                                      
int cost = Integer.parseInt(itcost);   
String sellperc = mSellPercent.getText().toString();                                     
int no2 = Integer.parseInt(sellperc);   
String sellamou = mSellAmount.getText().toString();                            
int no3 = Integer.parseInt(sellamou); 

private String name1 = "Menu Item: $" + item;
private String cost1 = "Item Cost: $" + cost;
private String perc1 = "Sell Percent: %" + no2;
private String amount1 = "Sell Price: $" + no3;



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

    final AlertDialog.Builder builder2 = new AlertDialog.Builder(this);
    builder2.setMessage("Required Fields aren't filled!");
    builder2.setCancelable(true);




    mBackButton = (Button)findViewById(R.id.back_button1);
    mBackButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            final Intent intent1 = new Intent(StartCalc.this, ActivityHome.class);
            if (intent1 != null) {
                startActivity(intent1);
            }
        }
    });

    mItemName = (EditText)findViewById(R.id.edit_item_name);
    mItemCost = (EditText)findViewById(R.id.item_cost);
    mSellPercent = (EditText)findViewById(R.id.profit_percent);
    mSellAmount = (EditText)findViewById(R.id.profit_amount);

    mCalculate = (Button)findViewById(R.id.calculate_button);
    mCalculate.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            if (mSellPercent.getText().toString().trim().length() == 0) {
                int no5 = Calculator.getPerc(cost, no3);
                String percstring = "Item Percent: %" + no5;
                final AlertDialog.Builder builder1 = new AlertDialog.Builder(StartCalc.this);
                builder1.setMessage(name1 + "\n" + cost + "\n" + percstring + "\n" + amount1);
                builder1.setCancelable(true);
                AlertDialog alert11 = builder1.create();
                alert11.show();
            } 
            else if (mSellAmount.getText().toString().trim().length() == 0) {
                int no6 = Calculator.getPerc(cost, no3);
                String amountstring = "Item Amount: $" + no6;
                final AlertDialog.Builder builder1 = new AlertDialog.Builder(StartCalc.this);
                builder1.setMessage(name1 + "\n" + cost1 + "\n" + perc1 + "\n" + amountstring);
                builder1.setCancelable(true);
                AlertDialog alert11 = builder1.create();
                alert11.show();
            }

            else {
                AlertDialog alert2 = builder2.create();
                alert2.show();
            }
        }
    }); 


}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.start_calc, 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();
    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}
}

Calculator Java class:

    package com.example.foodcostcalculator;

public class Calculator {
    private static int cost3;
    private static int percent;
    private static int amountsell;

    public static void setCost(int cd) {
        cost3 = cd;
    }

    public static int getCost() {
        return cost3;
    }

    public static void setPerc(int p) {
        percent = p;
    }

    public static void setAmount(int am) {
        amountsell = am;
    }

    public static int getPerc(int a, int b) {

        percent = (b / a) * 100;
        return percent;
    }

    public static int getAmount(int c, int e) {
        amountsell = c * e;
        return amountsell;
    }
}

Log:

    04-09 01:34:37.812: E/AndroidRuntime(14908): FATAL EXCEPTION: main
04-09 01:34:37.812: E/AndroidRuntime(14908): Process: com.example.foodcostcalculator, PID: 14908
04-09 01:34:37.812: E/AndroidRuntime(14908): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.foodcostcalculator/com.example.foodcostcalculator.StartCalc}: java.lang.NullPointerException
04-09 01:34:37.812: E/AndroidRuntime(14908):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2124)
04-09 01:34:37.812: E/AndroidRuntime(14908):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2257)
04-09 01:34:37.812: E/AndroidRuntime(14908):    at android.app.ActivityThread.access$800(ActivityThread.java:139)
04-09 01:34:37.812: E/AndroidRuntime(14908):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1210)
04-09 01:34:37.812: E/AndroidRuntime(14908):    at android.os.Handler.dispatchMessage(Handler.java:102)
04-09 01:34:37.812: E/AndroidRuntime(14908):    at android.os.Looper.loop(Looper.java:136)
04-09 01:34:37.812: E/AndroidRuntime(14908):    at android.app.ActivityThread.main(ActivityThread.java:5097)
04-09 01:34:37.812: E/AndroidRuntime(14908):    at java.lang.reflect.Method.invokeNative(Native Method)
04-09 01:34:37.812: E/AndroidRuntime(14908):    at java.lang.reflect.Method.invoke(Method.java:515)
04-09 01:34:37.812: E/AndroidRuntime(14908):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
04-09 01:34:37.812: E/AndroidRuntime(14908):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
04-09 01:34:37.812: E/AndroidRuntime(14908):    at dalvik.system.NativeStart.main(Native Method)
04-09 01:34:37.812: E/AndroidRuntime(14908): Caused by: java.lang.NullPointerException
04-09 01:34:37.812: E/AndroidRuntime(14908):    at com.example.foodcostcalculator.StartCalc.<init>(StartCalc.java:22)
04-09 01:34:37.812: E/AndroidRuntime(14908):    at java.lang.Class.newInstanceImpl(Native Method)
04-09 01:34:37.812: E/AndroidRuntime(14908):    at java.lang.Class.newInstance(Class.java:1208)
04-09 01:34:37.812: E/AndroidRuntime(14908):    at android.app.Instrumentation.newActivity(Instrumentation.java:1084)
04-09 01:34:37.812: E/AndroidRuntime(14908):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2115)
04-09 01:34:37.812: E/AndroidRuntime(14908):    ... 11 more
String item = mItemName.getText().toString();                                    
String itcost = mItemCost.getText().toString(); 
String sellperc = mSellPercent.getText().toString();
String sellamou = mSellAmount.getText().toString();

mItemName , mItemCost , mSellPercent , and mSellAmount are null , you can't access to their's methods. Just access them after you initialize them by using findViewById method. In your StartCalc activity, put this code:

String item = mItemName.getText().toString();                                    
String itcost = mItemCost.getText().toString();                                      
int cost = Integer.parseInt(itcost);   
String sellperc = mSellPercent.getText().toString();                                     
int no2 = Integer.parseInt(sellperc);   
String sellamou = mSellAmount.getText().toString();                            
int no3 = Integer.parseInt(sellamou); 

private String name1 = "Menu Item: $" + item;
private String cost1 = "Item Cost: $" + cost;
private String perc1 = "Sell Percent: %" + no2;
private String amount1 = "Sell Price: $" + no3;

after mItemName , mItemCost , mSellPercent , and mSellAmount are itialized:

mItemName = (EditText)findViewById(R.id.edit_item_name);
mItemCost = (EditText)findViewById(R.id.item_cost);
mSellPercent = (EditText)findViewById(R.id.profit_percent);
mSellAmount = (EditText)findViewById(R.id.profit_amount);

like this:

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

    final AlertDialog.Builder builder2 = new AlertDialog.Builder(this);
    builder2.setMessage("Required Fields aren't filled!");
    builder2.setCancelable(true);

    mBackButton = (Button)findViewById(R.id.back_button1);
    mBackButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            final Intent intent1 = new Intent(StartCalc.this, ActivityHome.class);
            if (intent1 != null) {
                startActivity(intent1);
            }
        }
    });

    mItemName = (EditText)findViewById(R.id.edit_item_name);
    mItemCost = (EditText)findViewById(R.id.item_cost);
    mSellPercent = (EditText)findViewById(R.id.profit_percent);
    mSellAmount = (EditText)findViewById(R.id.profit_amount);

    String item = mItemName.getText().toString();                                    
    String itcost = mItemCost.getText().toString();                                      
    int cost = Integer.parseInt(itcost);   
    String sellperc = mSellPercent.getText().toString();                                     
    int no2 = Integer.parseInt(sellperc);   
    String sellamou = mSellAmount.getText().toString();                            
    int no3 = Integer.parseInt(sellamou); 

    String name1 = "Menu Item: $" + item;
    String cost1 = "Item Cost: $" + cost;
    String perc1 = "Sell Percent: %" + no2;
    String amount1 = "Sell Price: $" + no3;
    mCalculate = (Button)findViewById(R.id.calculate_button);

The problem is in your StartCalc activity, when it is first instantiated, it initializes the variable item , itcost , cost , sellperc to values that depend on mItemName , mItemCost , mSellPercent , mSellAmount , which are null at this point (until onCreate() is called).

You can try moving these assign operations to onCreate() , after you assign values to mItemName , mItemCost , mSellPercent , mSellAmount to get over the exception (depending on what you are trying to do). But bear in mind that the value of item (and your other variables) won't change when the mItemName EditText gets changed. So, I think you are better assigning these values just before using them.

In StartCalc activity, the following declarations are initialised to null by default.

private Button mBackButton;
private EditText mItemName;
private EditText mItemCost;
private EditText mSellPercent;
private EditText mSellAmount;
private Button mCalculate;

So when you try to do :

String item = mItemName.getText().toString();                                    
String itcost = mItemCost.getText().toString();                                      
int cost = Integer.parseInt(itcost);   
String sellperc = mSellPercent.getText().toString();                                     
int no2 = Integer.parseInt(sellperc);   
String sellamou = mSellAmount.getText().toString();                            
int no3 = Integer.parseInt(sellamou); 

android throws a java.lang.NullPointerException . Please note that the connection between the View components in the activity code and the layout are established only after you link them via the findViewById() method.

Write the above code after the calls to the findviewById() as shown below.

...
mItemName = (EditText)findViewById(R.id.edit_item_name);
mItemCost = (EditText)findViewById(R.id.item_cost);
mSellPercent = (EditText)findViewById(R.id.profit_percent);
mSellAmount = (EditText)findViewById(R.id.profit_amount);

mCalculate = (Button)findViewById(R.id.calculate_button);
item = mItemName.getText().toString();                                    
itcost = mItemCost.getText().toString();                                      
cost = Integer.parseInt(itcost);   
sellperc = mSellPercent.getText().toString();                                     
no2 = Integer.parseInt(sellperc);   
sellamou = mSellAmount.getText().toString();                            
no3 = Integer.parseInt(sellamou); 

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