簡體   English   中英

BaseAdapter 上下文中的自定義共享首選項 null

[英]Custom sharedpreferences in BaseAdapter Context null

我有自定義 SharedPreference 類,我嘗試從我的自定義 SharedPrefences 類中獲取字符串。 當“prf = new PrefManager(context);”時,我在 getView 方法中遇到錯誤

我能做什么,我一直在尋找 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  "";
}

}

我嘗試在適配器視圖中獲取 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);
    }

在這里初始化

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);

您可以將上下文從片段傳遞到構造函數中的適配器,然后將其從適配器傳遞到首選項類。

您可能沒有初始化變量context

只需嘗試更改行:

prf = new PrefManager(context);

到:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM