-1

我正在尝试在我的代码中实现 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)

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

提前致谢。

4

1 回答 1

1

PREFS_NAME 是否正确初始化?

于 2013-09-27T15:50:28.430 回答