-2

Program runs until it tries to access the SharedPreferences in my updateUserSettings() method. I have spent the last 2 hours searching the internet with no explanations. Please help!

I have the line that messes everything up Commented at the bottom of my onCreate();

Here is FuelEconomyCalculatorActivity.java

    package com.example.fuelcalculator;

    import android.content.Intent;
    import android.content.SharedPreferences;
    import android.os.Bundle;
    import android.preference.PreferenceManager;
    import android.support.v7.app.ActionBarActivity;
    import android.view.Menu;
    import android.view.MenuItem;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.Button;
    import android.widget.EditText;
    import android.widget.RadioButton;
    import android.widget.TextView;
    import android.widget.Toast;

    public class FuelEconomyCalculatorActivity extends ActionBarActivity implements
            OnClickListener {

        private EditText fuelEditText;
        private EditText distanceEditText;
        private TextView mpgTextView;
        private TextView litresTextView;
        private Button calculateButton;
        private Button clearButton;
        private RadioButton gallonsRadio;
        private RadioButton litresRadio;
        private RadioButton milesRadio;
        private RadioButton kmRadio;
        private String mpg = " ";
        private String kp100 = " ";
        private boolean metricChecked;
        private boolean imperialChecked;
        private boolean usGallonChecked;
        private boolean ukGallonChecked;


        private static final int RESULT_SETTINGS = 1;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_fuel_economy_calculator);
            fuelEditText = (EditText) findViewById(R.id.fuelEditText);
            distanceEditText = (EditText) findViewById(R.id.distanceEditText);
            mpgTextView = (TextView) findViewById(R.id.mpgTextView);
            litresTextView = (TextView) findViewById(R.id.litresTextView);
            calculateButton = (Button) findViewById(R.id.calculateButton);
            clearButton = (Button) findViewById(R.id.clearButton);
            gallonsRadio = (RadioButton) findViewById(R.id.gallonsRadio);
            litresRadio = (RadioButton) findViewById(R.id.litresRadio);
            milesRadio = (RadioButton) findViewById(R.id.milesRadio);
            kmRadio = (RadioButton) findViewById(R.id.kmRadio);
            calculateButton.setOnClickListener(this);
            clearButton.setOnClickListener(this);

            if (savedInstanceState != null) {
                mpg = savedInstanceState.getString("mpg");
                kp100 = savedInstanceState.getString("kp100");
                initializeViews();
            }
        //  updateUserSettings();
        }

        protected void onSaveInstanceState(Bundle savedInstanceState) {
            super.onSaveInstanceState(savedInstanceState);
            savedInstanceState.putString("mpg", (String) mpgTextView.getText());
            savedInstanceState.putString("kp100", (String) litresTextView.getText());
            litresRadio.setChecked(true);
            kmRadio.setChecked(true);
        }

        private void initializeViews() {
            mpgTextView.setText(mpg);
            litresTextView.setText(kp100);
        }

        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            // Inflate the menu; this adds items to the action bar if it is present.
            getMenuInflater().inflate(R.menu.fuel_economy_calculator, 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.
            switch (item.getItemId()) {
            case R.id.action_settings: {
                Intent intent = new Intent(FuelEconomyCalculatorActivity.this,
                        FuelEconomySettingsActivity.class);
                startActivityForResult(intent, RESULT_SETTINGS);
                return true;
            }

            case R.id.action_about: {
                Intent intent = new Intent(getApplicationContext(),   FuelEconomyAboutPageActivity.class);
                startActivity(intent);
                return true;
            }

            default:
                return super.onOptionsItemSelected(item);
            }
        }

        @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
            super.onActivityResult(requestCode, resultCode, data);

            switch (requestCode) {
            case RESULT_SETTINGS:
                updateUserSettings();
                break;

            }

        }

        private void updateUserSettings() {
            SharedPreferences sharedPrefs = PreferenceManager
                    .getDefaultSharedPreferences(this);

            if(sharedPrefs.getString("measuringUnits", null).equalsIgnoreCase("metric"))
            {
                metricChecked = true;
                imperialChecked = false;
            }
            else if(sharedPrefs.getString("measuringUnits", null).equalsIgnoreCase("imperial"))
            {
                imperialChecked = true;
                metricChecked = false;
            }
            if(sharedPrefs.getString("gallons", null).equalsIgnoreCase("uk"))
            {
                ukGallonChecked = true;
                usGallonChecked = false;
            }
            else if(sharedPrefs.getString("gallons", null).equalsIgnoreCase("us"))
            {
                usGallonChecked = true;
                ukGallonChecked = false;
            }

            if(metricChecked)
            {
                litresRadio.setChecked(true);
                kmRadio.setChecked(true);
            }
            else if(imperialChecked)
            {
                milesRadio.setChecked(true);
                gallonsRadio.setChecked(true);
            }
        }

        @Override
        public void onClick(View v) {
            if (v.getId() == R.id.calculateButton) {
                float mpg = 0;
                float kmLitres = 0;
                // it doesn't matter which you use here, as long
                // as you use a fuel and a distance method
                if (ukGallonChecked && !usGallonChecked) {
                    if (getKM() > 0 && getLitres() > 0) {
                        mpg = getMiles() / getGallons();
                        kmLitres = getLitres() / (getKM() / 100);
                        mpgTextView.setText(String.format("%.2f", mpg));
                        litresTextView.setText(String.format("%.2f", kmLitres));
                    }
                } else if (usGallonChecked && !ukGallonChecked) {
                    if (getKM() > 0 && getLitres() > 0) {
                        mpg = getMiles() / getGallonsUS();
                        kmLitres = getLitresUS() / (getKM() / 100);
                        mpgTextView.setText(String.format("%.2f", mpg));
                        litresTextView.setText(String.format("%.2f", kmLitres));
                    }
                }
            } else if (v.getId() == R.id.clearButton) {
                resetValues();
            }

        }

        public float CheckValues(EditText input) {
            float value = 0;
            try {
                value = Float.parseFloat(input.getText().toString());
                if (value < 1) {
                    Toast toast = Toast.makeText(this,
                            "Please enter a number that is larger than 0",
                            Toast.LENGTH_SHORT);
                    toast.show();
                }
            } catch (Exception ex) {
                Toast toast = Toast.makeText(this, "Please enter a number",
                        Toast.LENGTH_SHORT);
                toast.show();
            }
            return value;
        }

        public void resetValues() {
            mpg = " ";
            kp100 = " ";
            fuelEditText.setText("");
            distanceEditText.setText("");
            mpgTextView.setText("");
            litresTextView.setText("");
        }

        public float getKM() {
            float distance = CheckValues(distanceEditText);
            if (milesRadio.isChecked()) {
                distance = (float) (distance * 1.60934);
            }
            return distance;
        }

        public float getMiles() {
            float distance = CheckValues(distanceEditText);
            if (kmRadio.isChecked()) {
                distance = (float) (distance * 0.62137);
            }
            return distance;
        }

        public float getLitres() {
            float fuel = CheckValues(fuelEditText);
            if (gallonsRadio.isChecked()) {
                fuel = (float) (fuel * 4.54609);
            }
            return fuel;
        }

        public float getLitresUS() {
            float fuel = CheckValues(fuelEditText);
            if (gallonsRadio.isChecked()) {
                fuel = (float) (fuel * 3.785411784);
            }
            return fuel;
        }

        public float getGallons() {
            float fuel = CheckValues(fuelEditText);
            if (litresRadio.isChecked()) {
                fuel = (float) (fuel * 0.219969);
            }
            return fuel;
        }

        public float getGallonsUS() {
            float fuel = CheckValues(fuelEditText);
            if (litresRadio.isChecked()) {
                fuel = (float) (fuel * 0.264172);
            }
            return fuel;
        }
    }

And here is my FuelEconomySettingsActivity.java

package com.example.fuelcalculator;

import android.app.Activity;
import android.os.Bundle;

public class FuelEconomySettingsActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        getFragmentManager().beginTransaction().replace(android.R.id.content,
                new FuelEconomySettingsFragment()).commit();

    }

}

Here is my LogCat

07-18 14:35:37.014: E/AndroidRuntime(3084): FATAL EXCEPTION: main
07-18 14:35:37.014: E/AndroidRuntime(3084): Process: com.example.fuelcalculator, PID: 3084
07-18 14:35:37.014: E/AndroidRuntime(3084): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.fuelcalculator/com.example.fuelcalculator.FuelEconomyCalculatorActivity}: java.lang.NullPointerException
07-18 14:35:37.014: E/AndroidRuntime(3084):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2305)
07-18 14:35:37.014: E/AndroidRuntime(3084):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2363)
07-18 14:35:37.014: E/AndroidRuntime(3084):     at android.app.ActivityThread.access$900(ActivityThread.java:161)
07-18 14:35:37.014: E/AndroidRuntime(3084):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1265)
07-18 14:35:37.014: E/AndroidRuntime(3084):     at android.os.Handler.dispatchMessage(Handler.java:102)
07-18 14:35:37.014: E/AndroidRuntime(3084):     at android.os.Looper.loop(Looper.java:157)
07-18 14:35:37.014: E/AndroidRuntime(3084):     at android.app.ActivityThread.main(ActivityThread.java:5356)
07-18 14:35:37.014: E/AndroidRuntime(3084):     at java.lang.reflect.Method.invokeNative(Native Method)
07-18 14:35:37.014: E/AndroidRuntime(3084):     at java.lang.reflect.Method.invoke(Method.java:515)
07-18 14:35:37.014: E/AndroidRuntime(3084):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1265)
07-18 14:35:37.014: E/AndroidRuntime(3084):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
07-18 14:35:37.014: E/AndroidRuntime(3084):     at dalvik.system.NativeStart.main(Native Method)
07-18 14:35:37.014: E/AndroidRuntime(3084): Caused by: java.lang.NullPointerException
07-18 14:35:37.014: E/AndroidRuntime(3084):     at com.example.fuelcalculator.FuelEconomyCalculatorActivity.updateUserSettings(FuelEconomyCalculatorActivity.java:128)
07-18 14:35:37.014: E/AndroidRuntime(3084):     at com.example.fuelcalculator.FuelEconomyCalculatorActivity.onCreate(FuelEconomyCalculatorActivity.java:63)
07-18 14:35:37.014: E/AndroidRuntime(3084):     at android.app.Activity.performCreate(Activity.java:5426)
07-18 14:35:37.014: E/AndroidRuntime(3084):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
07-18 14:35:37.014: E/AndroidRuntime(3084):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2269)
07-18 14:35:37.014: E/AndroidRuntime(3084):     ... 11 more

I am new to Android so I am not very good at debugging so could someone please assist me with my predicament?

The activity is already included in my Manifest so I know that is not the issue.

Any help is much obliged.

Darrell
  • 638
  • 4
  • 17
  • http://stackoverflow.com/questions/218384/what-is-a-null-pointer-exception-and-how-do-i-fix-it/218510#218510 – nhaarman Jul 18 '14 at 17:32
  • According to your Stack Trace, you have a NullPointerException on line 127 in FuelEconomyCalculatorActivity.java Look at the "Caused by: java.lang.NullPointerException" line and the following line after that will show you the line it crashed on. – Cruceo Jul 18 '14 at 17:36
  • I put the line `if(sharedPrefs!=null)` and I am still getting the same thing, I will update the logcat – Darrell Jul 18 '14 at 17:39
  • you just uninstall the app once and rerun it again..the error will be solved... – Lal Jul 18 '14 at 17:40
  • What does the second argument of `SharedPreferences.getString()` do? What will happen if you don't have the key "measuringUnits"? – kdgregory Jul 18 '14 at 17:44
  • try `if(sharedPrefs.getString("measuringUnits", "").equalsIgnoreCase("metric"))` instead of `if(sharedPrefs.getString("measuringUnits", null).equalsIgnoreCase("metric"))`..try replacing `null` with `""` in all others too.. – Lal Jul 18 '14 at 17:46
  • same thing happens if I take it out. measuring units is the name of a string-array – Darrell Jul 18 '14 at 17:47
  • try my comment..@Darrell Replace `null` with `""`.. – Lal Jul 18 '14 at 17:49
  • I just did that and now it doesn't crash, but now some other stuff doesn't work right... I keep plugging away at it for now. Thanks – Darrell Jul 18 '14 at 17:50
  • Can you mark my answer as accepted if i add it as my answer.. @Darrell – Lal Jul 18 '14 at 17:51
  • Yes, because you did in fact answer my question. Thanks – Darrell Jul 18 '14 at 17:53
  • Thankyou @Darell..Ive added that as my answer.. – Lal Jul 18 '14 at 17:54

1 Answers1

0

You are getting a NullPointerException because you are getting null as the default value for SharedPreference.getString()

Since it is getString() get an empty string as the default value...

So try this..

if(sharedPrefs.getString("measuringUnits", "").equalsIgnoreCase("metric")) 

instead of

if(sharedPrefs.getString("measuringUnits", null).equalsIgnoreCase("metric"))
Lal
  • 14,726
  • 4
  • 45
  • 70