當我嘗試從片段中初始化我的SharedPreference
init時,我在上下文中不斷收到NullPointerException
。從片段調用sharedPref時上下文的NullPointerException錯誤
以下是錯誤:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.SharedPreferences android.content.Context.getSharedPreferences(java.lang.String, int)' on a null object reference
at c.c.modular.SessionManager.<init>(SessionManager.java:68)
at c.c.ProfileCompletedFragment.setupData(ProfileCompletedFragment.java:75)
at c.c.ProfileCompletedFragment.passDataToFragment(ProfileCompletedFragment.java:210)
at c.c.ProfileActivity.onCreate(ProfileActivity.java:287)
這裏是初始化:
// init
public SessionManager(Context context) {
this._context = context;
pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
editor = pref.edit();
}
這裏是片段中的呼叫:
private void setupData() {
//sessions manager
session = new SessionManager(getActivity());
//establishing db
db = new DatabaseHelper(getActivity());
count = 0;
}
編輯:
什麼我已經意識到了由於片段尚未附加到活動本身,試圖找出如何附加它以便我可以調用活動......這是我在下面編輯中的新嘗試,因此getActivity爲null。 ..同樣的問題...
profileJoinedFrag = new ProfileJoinedFragment();
profileCompletedFrag = new ProfileCompletedFragment();
android.support.v4.app.FragmentManager fm = getSupportFragmentManager();
fm.beginTransaction()
.replace(R.id.frame_container, profileCompletedFrag).commit();
//Setting up fragment
String[] tabTitles = {"Posts", "Joins"};
adapter = new TabAdapter(fm, profileCompletedFrag, profileJoinedFrag, tabTitles);
// // Initialize the ViewPager and set an adapter
pager = (ViewPager) findViewById(R.id.profilePager);
pager.setAdapter(adapter);
// Bind the tabs to the ViewPager
tabs = (PagerSlidingTabStrip) findViewById(R.id.profileTabs);
tabs.setViewPager(pager);
//default place send
//
pager.setCurrentItem(0);
profileCompletedFrag.passDataToFragment(userId);
上下文是空的檢查,即 –