getPreferences引发NullPointerException

时间:2013-09-27 15:00:44

标签: java android

我正在尝试在我的代码中实现SharedPreferences,它存储图像文件名。

这是我用来实现SharedPreferences的代码 -

private void setpath(String path2) {
    // TODO Auto-generated method stub
System.out.println("sharedpreferences "+path2);
try{
SharedPreferences settings = getSharedPreferences(PREFS_NAME,0); //I am getting NullPointerException here.
SharedPreferences.Editor editor = settings.edit();
editor.putString("name",path2);
Log.v("path in setpath of MyFileOberver : ",path2);
editor.commit();
Intent i=new Intent(getApplicationContext(),ArrAdapter.class);
i.putExtra("path", path);
    startActivity(i);       
}
catch(Exception e)
{
    Log.v("Exception in SharedPreferences : ",e.toString());
}
}

ArrAdapter.java:

@Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
setContentView(R.layout.fileeventlist);
info = new adapter(this);
listView = (ListView) findViewById(android.R.id.list);
setContentView(R.layout.fileeventlist);
    SharedPreferences settings = getSharedPreferences (PREFS_NAME,0);
    String newpath = "newpath";
    this.path = settings.getString("name",newpath);
    Log.v("New path in FileEvent : ",newpath);


    }

logcat显示以下消息 -

09-27 11:07:14.141: A/FileObserver(14481): Unhandled exception in FileObserver com.example.sample_fileobserver.MyFileObserver@b1178718
09-27 11:07:14.141: A/FileObserver(14481): java.lang.NullPointerException
09-27 11:07:14.141: A/FileObserver(14481):  at android.content.ContextWrapper.getSharedPreferences(ContextWrapper.java:167)
09-27 11:07:14.141: A/FileObserver(14481):  at com.example.sample_fileobserver.FileEvent.setpath(FileEvent.java:135)

我无法理解,我的代码出错了。

提前致谢。

1 个答案:

答案 0 :(得分:1)

PREFS_NAME是否已正确初始化?