Android:类中的SharedPreferences PreferenceManager.getDefaultSharedPreferences

时间:2015-04-16 15:43:08

标签: java android class sharedpreferences android-preferences

我想从我的偏好片段中获取一个字符串到我的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 prefs = PreferenceManager.getDefaultSharedPreferences(this);

问题是(这个),但我不知道我需要选择哪种上下文

2 个答案:

答案 0 :(得分:2)

您应该将对象的实例化作为参数传递给构造函数,并从那里使用它

答案 1 :(得分:0)

将上下文传递给构造函数

public class VtplListContentItem implements VtplListItem  {

    private Context m_context;

    public VtplListContentItem(VtplEntry data, Context context) {
        m_data = data;
        m_context = context;
    }

    ...

    @Override
    public View getView(LayoutInflater inflater, View convertView) {
        ...
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(m_context);
        ...
    }

    ...

}