创建新的SharedPreferences文件时出现NullPointerException

时间:2013-10-09 00:34:34

标签: java android nullpointerexception

除非我错了,调用getSharedPreferences(“someName”,0)应该只是创建一个新文件,如果手机的内存中不存在,对吧?

对我来说不幸的是,这只是给了我一个NPE。代码和LogCat在下面。

NewCity类:

public class NewCity extends Activity implements OnClickListener, OnCheckedChangeListener {
    public static City city;
    private Generator gen;
    RadioGroup popGroup;
    RadioButton random, specific;
    Spinner cityType, supplies;
    EditText cityName, customPop;
    CheckBox fishing, mining, forestry;
    Button next;
    TextView errorList;

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

    private void initializeRefs() {
        popGroup = (RadioGroup) findViewById(R.id.popGroup);
        random = (RadioButton) findViewById(R.id.radioRandomCity);
        specific = (RadioButton) findViewById(R.id.radioSpecificCity);
        cityType = (Spinner) findViewById(R.id.spinCityType);
        supplies = (Spinner) findViewById(R.id.spinSupplies);
        cityName = (EditText) findViewById(R.id.textCityName);
        customPop = (EditText) findViewById(R.id.textCustomPop);
        fishing = (CheckBox) findViewById(R.id.checkFishing);
        mining = (CheckBox) findViewById(R.id.checkMining);
        forestry = (CheckBox) findViewById(R.id.checkForestry);
        next = (Button) findViewById(R.id.bNewNext);
        errorList = (TextView) findViewById(R.id.errorList);

        popGroup.setOnCheckedChangeListener(this);
        next.setOnClickListener(this);      
        customPop.setEnabled(false);
    }

    @Override
    public void onClick(View view) {
        boolean canGenerate = true;
        ArrayList<String> errors = new ArrayList<String>();

        switch(view.getId()) {
        case R.id.bNewNext:
            if(cityName.getText().toString().matches("")) {
                errors.add("! Settlement must have a name.\n");
                canGenerate = false;
            }

            if(specific.isChecked() && customPop.getText().toString().matches("")) {
                errors.add("! Enter a population figure.\n");
                canGenerate = false;
            }           
            break;
        }

        if(canGenerate) {
            gen = new Generator(getBaseContext());
            errors.clear();
            sendCityData(cityName.getText().toString());
                    gen.createCity();
        } else {
            StringBuilder builder = new StringBuilder();
            for(String value : errors) {
                builder.append(value);
            }           
            errorList.setText(builder.toString());
            errors.clear();
        }
    }
    .... Unrelated code ....
}

生成器类:

public class Generator {
    private Context context;
    private City city;
    private SharedPreferences storage;

    public Generator(Context context) {
        this.context = context;
        city = NewCity.city;
        storage = context.getSharedPreferences(city.getName(), Context.MODE_PRIVATE);
    }

    public float random(float low, float high) {
        Random random = new Random();
        return ((low + (high - low)) * random.nextFloat());
    }

    public void createCity() {
        Editor edit = storage.edit();
        edit.putString("NAME", city.getName()).apply();
    }
}

logcat的:

10-08 20:22:28.598: E/AndroidRuntime(21336): FATAL EXCEPTION: main
10-08 20:22:28.598: E/AndroidRuntime(21336): java.lang.NullPointerException
10-08 20:22:28.598: E/AndroidRuntime(21336):    at com.flawedspirit.android.citygen.Generator.<init>(Generator.java:17)
10-08 20:22:28.598: E/AndroidRuntime(21336):    at com.flawedspirit.android.citygen.NewCity.onClick(NewCity.java:77)
10-08 20:22:28.598: E/AndroidRuntime(21336):    at android.view.View.performClick(View.java:4203)
10-08 20:22:28.598: E/AndroidRuntime(21336):    at android.view.View$PerformClick.run(View.java:17189)
10-08 20:22:28.598: E/AndroidRuntime(21336):    at android.os.Handler.handleCallback(Handler.java:615)
10-08 20:22:28.598: E/AndroidRuntime(21336):    at android.os.Handler.dispatchMessage(Handler.java:92)
10-08 20:22:28.598: E/AndroidRuntime(21336):    at android.os.Looper.loop(Looper.java:137)
10-08 20:22:28.598: E/AndroidRuntime(21336):    at android.app.ActivityThread.main(ActivityThread.java:4961)
10-08 20:22:28.598: E/AndroidRuntime(21336):    at java.lang.reflect.Method.invokeNative(Native Method)
10-08 20:22:28.598: E/AndroidRuntime(21336):    at java.lang.reflect.Method.invoke(Method.java:511)
10-08 20:22:28.598: E/AndroidRuntime(21336):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1004)
10-08 20:22:28.598: E/AndroidRuntime(21336):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:771)
10-08 20:22:28.598: E/AndroidRuntime(21336):    at dalvik.system.NativeStart.main(Native Method)

违规声明位于Generate类的第17行。我不明白为什么它不起作用。它正在传递一个Context和一个String(“city.getName()”),它在传递之前被初始化,所以我知道那不是null。 Generator类的构造函数是否放在错误的位置?我知道它必须在activity的super.onCreate()语句之后。

编辑:我的城市类'构造函数;这样做真的有效吗?

public class City {
    private static final int PEOPLE_PER_SQACRE = 61;
    private static final int PEOPLE_PER_SQMILE = 38850;

    private String name;
    private String type;
    private int population;
    private float sizeMi;
    private float sizeAc;
    private int gpLimit;
    private long wealth;
    private float lowPop;
    private float highPop;
    private boolean fishing;
    private boolean mining;
    private boolean forestry;

    public City(String name) {
        this.name = name;
    }
    .... Unrelated code ....
}

1 个答案:

答案 0 :(得分:0)

编辑:好的,所以现在知道问题是:您在创建它之前访问city。请参阅下面的代码

@Override
    public void onClick(View view) {
        boolean canGenerate = true;
        ArrayList<String> errors = new ArrayList<String>();

        switch(view.getId()) {
        case R.id.bNewNext:
            if(cityName.getText().toString().matches("")) {
                errors.add("! Settlement must have a name.\n");
                canGenerate = false;
            }

            if(specific.isChecked() && customPop.getText().toString().matches("")) {
                errors.add("! Enter a population figure.\n");
                canGenerate = false;
            }           
            break;
        }

        if(canGenerate) {
            // Here, you should run this method first
            sendCityData(cityName.getText().toString());
            gen = new Generator(getBaseContext());
            errors.clear();
            gen.createCity();
        } else {
            StringBuilder builder = new StringBuilder();
            for(String value : errors) {
                builder.append(value);
            }           
            errorList.setText(builder.toString());
            errors.clear();
        }
    }