在自定义视图中获取值时,Android SharedPreferences会崩溃

时间:2011-08-10 00:52:42

标签: android crash sharedpreferences android-custom-view

我一直在寻找一段时间,但似乎没有人真的遇到同样的问题,所以可能只是一个简单的编程错误。

从平板电脑上全新安装程序加载,然后如果您转到首选项菜单并选择nPref文本框并输入一个值,程序就可以了。但是当你重新启动程序时,它会在输入一个值后最初崩溃。

我的程序的大致轮廓如下:

    <import statments>
    public class Galaxy extends Activity{
            public void onCreate(Bundle savedInstanceState) {
                 requestWindowFeature(Window.FEATURE_NO_TITLE);                                    
                 requestWindowFeature(Window.FEATURE_NO_TITLE);
                 getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, 
                    WindowManager.LayoutParams.FLAG_FULLSCREEN); //request fullscreen
                 super.onCreate(savedInstanceState);
                 setContentView(new Simulation(this)); //set contentview to my class
            }
            public boolean onCreateOptionsMenu(Menu menu) { //create ("inflate") the menu
                 MenuInflater inflater = getMenuInflater();
                 inflater.inflate(R.layout.options_menu, menu);
                 return true;
            }
            public boolean onOptionsItemSelected(MenuItem item) { //check if a menu item is pressed
                switch (item.getItemId()) {
                case R.id.m_SETTINGS:
                   Toast.makeText(Galaxy_test2Activity.this, "Preference Launched!",Toast.LENGTH_SHORT);
                   Intent i = new Intent(Galaxy_test2Activity.this, Preferences.class);
                   startActivity(i);

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

            }   

            class Simulation extends View {
                  //I declare my program variables here
                  public Simulation(Context context) {
                       super(context);
                       SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context); //get the preferences
                       int storedPreference = preferences.getInt("nPref", 0); //attempt to get a value from the preferences
                       Log.i(TAG, "storedPref nPref = " + storedPreference); //log it to see if it is working
                       //rest of my program
                       //I also have onDraw and onTouchEvent
                  }
             }
             }

如果您还需要其他任何东西我可以发布

谢谢!

0 个答案:

没有答案