如何使用共享首选项

时间:2014-04-20 10:38:44

标签: android sharedpreferences

我需要在我的显示适配器中激活共享首选项,我这样说:

public View getView(int pos, View child, ViewGroup parent) {
        SharedPreferences prefs = getSharedPreferences(MY_PREFERENCES, Context.MODE_PRIVATE);
        String turno_1 = prefs.getString(TURNO_1, "M");
        Holder mHolder;
        LayoutInflater layoutInflater;
        //text in which you want to find "M"
        if (child == null) {
            layoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            child = layoutInflater.inflate(R.layout.row, null);
            mHolder = new Holder();
            mHolder.txt_giorni = (TextView) child.findViewById(R.id.txt_giorni);
            mHolder.txt_turno = (TextView) child.findViewById(R.id.txt_turno);
            mHolder.txt_ore = (TextView) child.findViewById(R.id.txt_ore);
            mHolder.txt_id = (TextView) child.findViewById(R.id.txt_id);
            child.setTag(mHolder);
        } else {
            mHolder = (Holder) child.getTag();
        }
        mHolder.txt_giorni.setText(giorniName.get(pos));
        mHolder.txt_turno.setText(turnoName.get(pos));
        mHolder.txt_ore.setText(oreName.get(pos));
        mHolder.txt_id.setText(dataName.get(pos));

        TextView text = (TextView) child.findViewById(R.id.txt_turno);
        if(text.getText().toString().contains("F")){
            child.setBackgroundResource(R.color.red);
        } else {
            mHolder = (Holder) child.getTag();
        }
        mHolder.txt_giorni.setText(giorniName.get(pos));
        mHolder.txt_turno.setText(turnoName.get(pos));
        mHolder.txt_ore.setText(oreName.get(pos));
        mHolder.txt_id.setText(dataName.get(pos));

        String Turni = turnoName.get(pos);
        if (Turni != null) 
        if (Turni.equals("M")){
            mHolder.txt_turno.setTextColor(Color.RED);
            mHolder.txt_ore.setTextColor(Color.RED);
        } else 
        if (Turni.equals("F")){
            mHolder.txt_turno.setTextColor(Color.YELLOW);
            mHolder.txt_ore.setTextColor(Color.YELLOW);
        } else
            mHolder.txt_turno.setTextColor(Color.WHITE);

我想在turno_1行中使用该变量:

if (Turni.equals("M")){

我的问题是,当我以这种方式放置共享时,它会在类上生成一个致命错误,这是由第54行引起的:

String turno_1 = prefs.getString(TURNO_1, "M");

1 个答案:

答案 0 :(得分:0)

请阅读此内容我希望能帮助您http://developer.android.com/guide/topics/data/data-storage.html

您可以使用SharedPreferences:

保存数据:

SharedPreferences.Editor editor = getPreferences(MODE_PRIVATE).edit();
 editor.putString("text", mSaved.getText().toString());
 editor.putInt("selection-start", mSaved.getSelectionStart());
 editor.putInt("selection-end", mSaved.getSelectionEnd());
 editor.commit();

要检索数据:

SharedPreferences prefs = getPreferences(MODE_PRIVATE); 
String restoredText = prefs.getString("text", null);
int selectionStart = prefs.getInt("selection-start", -1);
int selectionEnd = prefs.getInt("selection-end", -1);