0

I'm trying to make a calorie counter app consisting of 2 activities, the main activity shows the amount of calories accumulated by my second activity (which calculates the calories and passes its value to the main activity intent when clicking "save"), when attempting to add code to pass the values between intents it now crashes the app on load up, I suspect its because there are no values passed on start up but I can only speculate, how would I overcome this? any help would be greatly appreciated, explanations more so! thanks,

Main Activity

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





        }

Main Activity 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>

Main activity 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+"");

    }


}

Main Activity 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
Mike12345
  • 15
  • 3

2 Answers2

-1

In your main activity check if you have extra or intent and then get the value from it ! like this way :

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

And also i suggest you to use StartActivityForResult() for this use case ! see this link :
How to manage `startActivityForResult` on Android?

Community
  • 1
  • 1
YFeizi
  • 1,498
  • 3
  • 28
  • 50
-1

Yuo have to see if the intent has or not extras, or the extra in this case.

SO try to do this:

@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);
Shudy
  • 7,806
  • 19
  • 63
  • 98