单击按钮时应用程序停止工作

时间:2015-03-03 17:48:08

标签: android android-studio

我是Android开发的新手,我的主要活动上有按钮,应该让用户进行新的活动,我只有其中一个按钮的代码到目前为止已经工作(添加按钮),但是已经开始导致点击时崩溃的应用程序,任何帮助将不胜感激,谢谢

主要活动

public class MainActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    TextView calories = (TextView)findViewById(R.id.calorie_display);


    Button add = (Button)findViewById(R.id.add_meal);
    Button reset = (Button)findViewById(R.id.reset);
    Button about = (Button)findViewById(R.id.about);

    add.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {

            Intent intent = new Intent(getApplicationContext(),MainActivity2.class);
                    startActivity(intent);
        }
    });
}
}

主要活动2

    public class MainActivity2 extends ActionBarActivity {


int sub_weight = 0;

EditText weight = (EditText)findViewById(R.id.edit_weight);
TextView calories = (TextView)findViewById(R.id.cal_total);
Button display = (Button)findViewById(R.id.display);



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

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


            Intent intent = new Intent(getApplicationContext(), MainActivity.class);
            startActivity(intent);
        }
    });
}
public void onRadioButtonClicked(View v){

    boolean checked = ((RadioButton) v).isChecked();

    switch (v.getId()) {
        case R.id.radiopork:
            if (checked)
                sub_weight = sub_weight + 2;
            break;
        case R.id.radiochicken:
            if (checked)
                sub_weight = sub_weight + 7;
            break;
        case R.id.radiobeef:
            if (checked)
                sub_weight = sub_weight + 9;
            break;
        case R.id.radiosalmon:
            if (checked)
                sub_weight = sub_weight + 13;
            break;
        case R.id.radiocod:
            if (checked)
                sub_weight = sub_weight + 17;
            break;
        case R.id.radiocereal:
            if (checked)
                sub_weight = sub_weight + 18;
            break;
        case R.id.radioporridge:
            if (checked)
                sub_weight = sub_weight + 23;
            break;
        case R.id.radiotoast:
            if (checked)
                sub_weight = sub_weight + 26;
            break;
        case R.id.radiocrisps:
            if (checked)
                sub_weight = sub_weight + 29;
            break;
        case R.id.radionoodle:
            if (checked)
                sub_weight = sub_weight + 33;
            break;


    }

    }
public void display(View v){

    String m = weight.getText().toString();
    int x =  Integer.parseInt(m);
    int y = x * sub_weight;
    calories.setText(y);
}
}

清单文件

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.michael.foodapp" >

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name="com.example.michael.foodapp.MainActivity"
        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="com.example.michael.foodapp.MainActivity2"
        android:label="@string/app_name" >
        </activity>
</application>

主要活动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" 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=".MainActivity">

<TextView android:text="@string/calorie_counter" android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:id="@+id/textView"
    android:textSize="20sp" />

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/meal_add"
    android:id="@+id/add_meal"
    android:layout_marginTop="80dp"
    android:layout_below="@+id/textView"
    android:layout_alignRight="@+id/reset"
    android:layout_alignEnd="@+id/reset" />

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/reset"
    android:id="@+id/reset"
    android:layout_below="@+id/add_meal"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="60dp" />

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/about"
    android:id="@+id/about"
    android:layout_below="@+id/reset"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="60dp" />

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/cal_display"
    android:id="@+id/calorie_display"
    android:layout_alignParentBottom="true"
    android:layout_centerHorizontal="true"
    android:layout_marginBottom="67dp"
    android:textSize="20sp" />

<EditText
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:inputType="number"
    android:ems="10"
    android:id="@+id/editText"
    android:layout_alignParentBottom="true"
    android:layout_alignLeft="@+id/calorie_display"
    android:layout_alignStart="@+id/calorie_display" />

主要活动2 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" 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=".MainActivity2">

<TextView android:text="@string/calorie_counter" android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:id="@+id/textView"
    android:textSize="20dp" />

<EditText
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:hint="@string/weight"
    android:id="@+id/edit_weight"
    android:textSize="20dp"
    android:inputType="number"
    android:layout_centerVertical="true"
    android:layout_centerHorizontal="true" />

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/save"
    android:id="@+id/save"
    android:layout_alignParentBottom="true"
    android:layout_centerHorizontal="true" />

<RadioButton
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Pork"
    android:id="@+id/radiopork"
    android:layout_below="@+id/textView"
    android:layout_marginTop="25dp"
    android:onClick="onRadioButtonClicked" />

<RadioButton
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Chicken"
    android:id="@+id/radiochicken"
    android:layout_below="@+id/radiopork"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:onClick="onRadioButtonClicked"/>

<RadioButton
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Beef"
    android:id="@+id/radiobeef"
    android:layout_below="@+id/radiochicken"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:onClick="onRadioButtonClicked"/>

<RadioButton
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Salmon"
    android:id="@+id/radiosalmon"
    android:layout_below="@+id/radiobeef"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:onClick="onRadioButtonClicked"/>

<RadioButton
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Cod"
    android:id="@+id/radiocod"
    android:layout_below="@+id/radiosalmon"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:onClick="onRadioButtonClicked"/>

<RadioButton
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Cereal"
    android:id="@+id/radiocereal"
    android:layout_alignTop="@+id/radiopork"
    android:layout_alignParentRight="true"
    android:layout_alignParentEnd="true"
    android:onClick="onRadioButtonClicked"/>

<RadioButton
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Porridge"
    android:id="@+id/radioporridge"
    android:layout_alignTop="@+id/radiochicken"
    android:layout_alignRight="@+id/radiocereal"
    android:layout_alignEnd="@+id/radiocereal"
    android:onClick="onRadioButtonClicked"/>

<RadioButton
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Toast"
    android:id="@+id/radiotoast"
    android:layout_below="@+id/radioporridge"
    android:layout_alignRight="@+id/radioporridge"
    android:layout_alignEnd="@+id/radioporridge"
    android:onClick="onRadioButtonClicked"/>

<RadioButton
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Crisps"
    android:id="@+id/radiocrisps"
    android:layout_below="@+id/radiotoast"
    android:layout_alignParentRight="true"
    android:layout_alignParentEnd="true"
    android:onClick="onRadioButtonClicked"/>

<RadioButton
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Pot Noodle"
    android:id="@+id/radionoodle"
    android:layout_below="@+id/radiocrisps"
    android:layout_alignRight="@+id/radiocrisps"
    android:layout_alignEnd="@+id/radiocrisps"
    android:onClick="onRadioButtonClicked"/>

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Display Meal Calories"
    android:id="@+id/display"
    android:onClick="display"
    android:layout_below="@+id/edit_weight"
    android:layout_toRightOf="@+id/radiochicken"
    android:layout_toEndOf="@+id/radiochicken"
    android:layout_marginTop="44dp"
    />

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Meal Calorie Total:"
    android:id="@+id/cal_total"
    android:layout_above="@+id/save"
    android:layout_centerHorizontal="true"
    android:layout_marginBottom="34dp" />

    03-03 17:53:41.432    1922-1922/com.example.michael.foodapp E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.example.michael.foodapp, PID: 1922
    java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.michael.foodapp/com.example.michael.foodapp.MainActivity2}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.Window.findViewById(int)' on a null object reference
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2209)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
            at android.app.ActivityThread.access$800(ActivityThread.java:144)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5221)
            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:899)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
     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:2071)
            at com.example.michael.foodapp.MainActivity2.<init>(MainActivity2.java:23)
            at java.lang.reflect.Constructor.newInstance(Native Method)
            at java.lang.Class.newInstance(Class.java:1572)
            at android.app.Instrumentation.newActivity(Instrumentation.java:1065)
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2199)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
            at android.app.ActivityThread.access$800(ActivityThread.java:144)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5221)
            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:899)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
03-03 17:53:45.055    1922-1922/com.example.michael.foodapp I/Process﹕ Sending signal. PID: 1922 SIG: 9

3 个答案:

答案 0 :(得分:1)

在MainActivity2中:

EditText weight = (EditText)findViewById(R.id.edit_weight);
TextView calories = (TextView)findViewById(R.id.cal_total);
Button display = (Button)findViewById(R.id.display);

这些语句不应该在oncreate方法中吗?在setcontentview之后?

我认为这是你的问题。

答案 1 :(得分:0)

请对您的活动进行一些更改,如下所示:

public class MainActivity2 extends ActionBarActivity {


int sub_weight = 0;

EditText weight;
TextView calories;
Button display;

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

weight = (EditText)findViewById(R.id.edit_weight);
calories = (TextView)findViewById(R.id.cal_total);
display = (Button)findViewById(R.id.display);

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


        Intent intent = new Intent(getApplicationContext(), MainActivity.class);
        startActivity(intent);
    }
});
}
}

我所做的改变是,我在课堂上创建了对控件的引用:

...
EditText weight;
TextView calories;
Button display;
...

然后,这些引用在onCreate()内初始化为:

...
weight = (EditText)findViewById(R.id.edit_weight);
calories = (TextView)findViewById(R.id.cal_total);
display = (Button)findViewById(R.id.display);
...

我猜你是Android App开发的新手。所以,mike ..您希望在布局中找到的任何视图,只需在findViewById之后执行setContentView()内容,因为布局的所有组件都可以仅在setContentView()之后引用

答案 2 :(得分:0)

更正确地理解 - 错误是由

引起的
 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:2071)
        at com.example.michael.foodapp.MainActivity2.<init>(MainActivity2.java:23)

所以看看第23行以及关于findviewbyId的内容。通过查看logcat,您可以找到错误所在的位置。我希望你能在下次登陆logcat时修复空指针:)

在MainActivity2中,在调用setContentView()之后,必须将视图链接到 OnCreate方法中的xml对应项。

public class MainActivity2 extends ActionBarActivity {


int sub_weight = 0;

EditText weight;
TextView calories;
Button display;



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

    weight = (EditText)findViewById(R.id.edit_weight);
    calories = (TextView)findViewById(R.id.cal_total);
    display = (Button)findViewById(R.id.display);

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


            Intent intent = new Intent(getApplicationContext(), MainActivity.class);
            startActivity(intent);
        }
    });
}
public void onRadioButtonClicked(View v){

    boolean checked = ((RadioButton) v).isChecked();

    switch (v.getId()) {
        case R.id.radiopork:
            if (checked)
                sub_weight = sub_weight + 2;
            break;
        case R.id.radiochicken:
            if (checked)
                sub_weight = sub_weight + 7;
            break;
        case R.id.radiobeef:
            if (checked)
                sub_weight = sub_weight + 9;
            break;
        case R.id.radiosalmon:
            if (checked)
                sub_weight = sub_weight + 13;
            break;
        case R.id.radiocod:
            if (checked)
                sub_weight = sub_weight + 17;
            break;
        case R.id.radiocereal:
            if (checked)
                sub_weight = sub_weight + 18;
            break;
        case R.id.radioporridge:
            if (checked)
                sub_weight = sub_weight + 23;
            break;
        case R.id.radiotoast:
            if (checked)
                sub_weight = sub_weight + 26;
            break;
        case R.id.radiocrisps:
            if (checked)
                sub_weight = sub_weight + 29;
            break;
        case R.id.radionoodle:
            if (checked)
                sub_weight = sub_weight + 33;
            break;


    }

    }
public void display(View v){

    String m = weight.getText().toString();
    int x =  Integer.parseInt(m);
    int y = x * sub_weight;
    calories.setText(y);
}
}