在意图之间传递值,app在启动时停止

时间:2015-03-05 11:39:29

标签: android android-intent android-studio

我正在尝试制作一个由2个活动组成的卡路里计数器应用程序,主要活动显示我的第二个活动累积的卡路里量(计算卡路里并将其值传递给主要活动意图时点击“保存” ),当试图添加代码以在意图之间传递值时,它现在在加载时崩溃应用程序,我怀疑它是因为启动时没有传递值但我只能推测,我将如何克服这个?任何帮助将不胜感激,解释更多!感谢,

主要活动

    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.overall);
            String calvalue = getIntent().getStringExtra("passedvalue");
            int f = Integer.parseInt(calvalue);
            calories.setText(""+f);





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


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

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





        }

主要活动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" />

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

</RelativeLayout>

主要活动2

    public class MainActivity2 extends ActionBarActivity {


    int sub_weight = 0;

    EditText weight;
    TextView calories;
    Button display, save;



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

                TextView calories = (TextView)findViewById(R.id.cal_total);
                String g = calories.getText().toString();

                Intent intent = new Intent(getApplicationContext(), MainActivity.class);
                intent.putExtra("passedvalue", g );
                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_calories(View v){

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

    }


}

主要活动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_calories"
        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" />


</RelativeLayout>

logcat

03-05 11:47:04.092    1955-1955/com.example.michael.foodapp E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.example.michael.foodapp, PID: 1955
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.michael.foodapp/com.example.michael.foodapp.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.os.Bundle.getString(java.lang.String)' on a null object reference
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298)
            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 'java.lang.String android.os.Bundle.getString(java.lang.String)' on a null object reference
            at com.example.michael.foodapp.MainActivity.onCreate(MainActivity.java:24)
            at android.app.Activity.performCreate(Activity.java:5933)
            at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251)
            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-05 11:47:06.864    1955-1955/com.example.michael.foodapp I/Process﹕ Sending signal. PID: 1955 SIG: 9

2 个答案:

答案 0 :(得分:-1)

在您的主要活动中检查您是否有额外或意图,然后从中获取价值!像这样:

if (getIntent() != null){
    Intent intent = getIntent();
    if(intent.hasExtra("passedvalue")){
       // get your value here 
    }
}

我还建议您使用StartActivityForResult()来完成此用例!看到这个链接:
How to manage `startActivityForResult` on Android?

答案 1 :(得分:-1)

Yuo必须查看意图是否有额外内容,或者在这种情况下是额外的。

所以试着这样做:

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

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

            //NEW STUFF
            Intent intent = getIntent();
             String calvalue = "";

            if( intent ! = null) {
                if (i.hasExtra("passedvalue"))
                {
                      calvalue = i.getExtras().getString("passedvalue");

                } else {
                      calvalue = "0";  // I put 0 in String, because you parse it later. SO the logic is that is the first time you open the App, you have no Calories
                }
            }
            // Your Stuff
            int f = Integer.parseInt(calvalue);
            calories.setText(""+f);