困住,需要帮助程序在尝试访问SharedPreferences时崩溃

时间:2014-07-18 17:30:46

标签: java android sharedpreferences

程序一直运行,直到它尝试访问updateUserSettings()方法中的SharedPreferences。我花了最近2个小时搜索互联网,没有任何解释。请帮忙!

我有一条混乱的线路在我的onCreate()的底部评论;

这是 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;
        }
    }

这是我的 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();

    }

}

这是我的 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

我是Android的新手,所以我不擅长调试,所以有人可以帮助我解决困境吗?

活动已包含在我的清单中,所以我知道这不是问题。

任何帮助都很有帮助。

1 个答案:

答案 0 :(得分:0)

您收到NullPointerException,因为null

的默认值为SharedPreference.getString()

因为getString()获取一个空字符串作为默认值...

所以试试这个......

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

而不是

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