简体   繁体   English

BaseAdapter 上下文中的自定义共享首选项 null

[英]Custom sharedpreferences in BaseAdapter Context null

I have custom SharedPreference class and i try to get a string from my custom SharedPrefecenses class.我有自定义 SharedPreference 类,我尝试从我的自定义 SharedPrefences 类中获取字符串。 I got error in getView method when " prf = new PrefManager(context);"当“prf = new PrefManager(context);”时,我在 getView 方法中遇到错误

What can i do, i have been searching 2 days.我能做什么,我一直在寻找 2 天。

public class PrefManager {
SharedPreferences pref;
SharedPreferences.Editor editor;
Context _context;

int PRIVATE_MODE = 0;

private static final String PREF_NAME = "Secur-transact";

private static final String IS_FIRST_TIME_LAUNCH = "IsFirstTimeLaunch";

public PrefManager(Context context) {
    this._context = context;
    pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
    editor = pref.edit();
}

public String getString(String PREF_NAME) {
    if(pref.contains(PREF_NAME)){
        return pref.getString(PREF_NAME,null);
    }
    return  "";
}

} }

I try to get getString method in adapter view.我尝试在适配器视图中获取 getString 方法。

public class CustomListAdapter extends BaseAdapter {

PrefManager prf;

@Override
public View getView(final int position, View convertView, ViewGroup parent) {

    prf = new PrefManager(context); // I GOT ERROR IN HERE

    if (inflater == null)
        inflater = (LayoutInflater) activity
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    if (convertView == null)
        convertView = inflater.inflate(R.layout.list_row, null);


    TextView name = (TextView) convertView.findViewById(R.id.name);

    if (prf.getString("ColorName").equals("RED")) {
        name.setBackgroundResource(R.color.primaryLightColorRed);
        name.setTextColor(R.color.colorWhite);
    }

initializing here在这里初始化

public class SampleClass extends Fragment {

private List<ModelsProps> modelsPropsList = new ArrayList<ModelsProps>();
public SampleClass () {
    // Required empty public constructor
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_main, container, false);

    final ListView listView = (ListView) rootView.findViewById(R.id.list);

    final CustomListAdapter adapter = new CustomListAdapter(getActivity(), modelsPropsList);

    listView.setAdapter(adapter);

您可以将上下文从片段传递到构造函数中的适配器,然后将其从适配器传递到首选项类。

You are probably not initializing the variable context .您可能没有初始化变量context

Just try to change the line:只需尝试更改行:

prf = new PrefManager(context);

to:到:

prf = new PrefManager(parent.getContext());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM