【发布时间】:2015-04-16 15:43:08
【问题描述】:
我想从我的偏好片段中获取一个字符串到我的 android 应用程序中的一个类,但我无法像往常那样获取它。
我班上的代码:
public class VtplListContentItem implements VtplListItem {
private VtplEntry m_data;
public VtplListContentItem(VtplEntry data) {
m_data = data;
}
@Override
public int getViewType() {
return RowType.LIST_ITEM.ordinal();
}
@Override
public View getView(LayoutInflater inflater, View convertView) {
View view;
if(convertView == null) {
view = inflater.inflate(R.layout.list_item, null);
}
else {
view = convertView;
}
[...]
// (this) is the error Context cannot be applied to this class
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
String myClass = prefs.getString("UserMyClass", "null");
// Mark
if (m_data.getSchoolClass().contains(myClass)) {
view.setBackgroundResource(R.color.accent);
} else {
view.setBackgroundResource(android.R.color.white);
}
return view;
}
@Override
public VtplEntry getData() {
return m_data;
}
}
我试过了:
public class VtplListContentItem extends Activity implements VtplListItem {
然后我得到错误:
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference
at com.philipp_mandler.android.vtpl.VtplListContentItem.getView(VtplListContentItem.java:52)
at com.philipp_mandler.android.vtpl.VtplListAdapter.getView(VtplListAdapter.java:38)
第 52 行是:
SharedPreferences 首选项 = PreferenceManager.getDefaultSharedPreferences(this);
问题是(this),但不知道需要选择哪个上下文
【问题讨论】:
标签: java android class sharedpreferences android-preferences