Question

In my application I would like to preset a default value in shared preference, how can I put such default the year 2014, only to be changed if necessary?

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

        }
    });
}}

What should I add to make 2014 the year of default?

Was it helpful?

Solution

sharedPrefs.getInt("YEAR" , 2014);

would make sure that if nothing is saved in the SharedPrefs for the key "YEAR", then it will return the value 2014 by default.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top