简体   繁体   English

应用程式在启动其他活动时当机

[英]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: 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);
}
}

Calculator Java class: 计算器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;
    }
}

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. mItemNamemItemCostmSellPercentmSellAmountnull ,您无法访问它们的方法。 Just access them after you initialize them by using findViewById method. 使用findViewById方法初始化它们后,只需访问它们即可。 In your StartCalc activity, put this code: 在您的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;

after mItemName , mItemCost , mSellPercent , and mSellAmount are itialized: mItemNamemItemCostmSellPercentmSellAmount之后:

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). 问题出在您的StartCalc活动中,当它首次实例化时,它将变量itemitcostcostsellperc为依赖于mItemNamemItemCostmSellPercentmSellAmount的值,此时它们为空(直到onCreate()为称为)。

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). 在为mItemNamemItemCostmSellPercentmSellAmount分配值之后,可以尝试将这些分配操作移至onCreate() ,以克服异常(取决于您要执行的操作)。 But bear in mind that the value of item (and your other variables) won't change when the mItemName EditText gets changed. 但是请记住,当mItemName EditText更改时, item (和其他变量)的值不会更改。 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. StartCalc活动中,以下声明默认情况下初始化为null

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 . android抛出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. 请注意, 只有通过findViewById()方法将它们链接 ,活动代码中的View组件和布局之间的连接才会建立

Write the above code after the calls to the findviewById() as shown below. 如下所示,在调用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); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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