应用程序在启动其他Activity时崩溃

时间:2016-04-09 08:36:18

标签: java android

所以我创建了一个应用来计算食物费用,但是当我按下按钮带我去计算应用程序崩溃的活动时。应用程序将改变正常,直到我添加方法来进行实际计算。我是新手,所以我意识到代码可能有点混乱。

启动器活动:

    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活动:

    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);
}
}

计算器Java类:

    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;
    }
}

记录:

    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

3 个答案:

答案 0 :(得分:0)

String item = mItemName.getText().toString();                                    
String itcost = mItemCost.getText().toString(); 
String sellperc = mSellPercent.getText().toString();
String sellamou = mSellAmount.getText().toString();

mItemNamemItemCostmSellPercentmSellAmountnull,您无法访问其方法。只需使用findViewById方法初始化它们即可访问它们。 在您的StartCalc活动中,输入以下代码:

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;

mItemName之后,mItemCostmSellPercentmSellAmount被赎回:

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);
像这样:

@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);

答案 1 :(得分:0)

问题出在您的StartCalc活动中,首次实例化时,它会将变量itemitcostcostsellperc初始化为值这取决于mItemNamemItemCostmSellPercentmSellAmount,此时为空(直到调用onCreate())。

在为onCreate()mItemNamemItemCostmSellPercent分配值后,您可以尝试将这些分配操作移至mSellAmount以克服异常(取决于你想要做什么)。但请记住,当item EditText发生更改时,mItemName(和您的其他变量)的值不会改变。所以,我认为你最好在使用它们之前分配这些值。

答案 2 :(得分:0)

StartCalc活动中,默认情况下,以下声明初始化为null

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); 

android抛出一个java.lang.NullPointerException。请注意,活动代码中的View组件与布局之间的连接只有在通过findViewById()方法链接后才能建立。

在调用findviewById()后编写上述代码,如下所示。

...
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);