默认共享首选项

时间:2014-03-30 10:20:05

标签: android sharedpreferences

在我的应用程序中,我想在共享偏好中预设一个默认值,如何在2014年设置此默认值,只在必要时进行更改?

package com.turniDB;

import turni.db.tab.R;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class Set_anno extends Activity {
    private final static String MY_PREFERENCES = "MyPref";
    private final static String ANNO = "anno";

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.set_anno);
        updatePreferencesData();
    }


    public void savePreferencesData(View view) {
        SharedPreferences prefs = getSharedPreferences(MY_PREFERENCES, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = prefs.edit();
        EditText outputAnno = (EditText) findViewById(R.id.inputanno);
        CharSequence anno = outputAnno.getText();
        if (anno != null) {
            editor.putString(ANNO, anno.toString());
            editor.commit();
        }
        updatePreferencesData();
    }

    private void updatePreferencesData(){
        SharedPreferences prefs = getSharedPreferences(MY_PREFERENCES, Context.MODE_PRIVATE);
        String anno = prefs.getString(ANNO, "Anno non inserito!");
        TextView outputAnno = (TextView) findViewById(R.id.outputAnno);
        outputAnno.setText(anno);


        final Intent startintent = new Intent(Set_anno.this,DBMain.class);
        Button button=(Button)findViewById(R.id.button1);
        button.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                startActivity(startintent);

        }
    });
}}

我应该添加什么才能使2014年成为违约年份?

1 个答案:

答案 0 :(得分:0)

<强> sharedPrefs.getInt("YEAR" , 2014);

将确保如果密钥"YEAR"的SharedPrefs中没有保存任何内容,则默认情况下它将返回值2014.