Android SharedPreferences不会保存数据

时间:2016-02-29 21:14:56

标签: java android sharedpreferences

所以我有两个活动,一个包含所有元素,如RadioButtons,EditText等,另一个只包含TextViews,将在其上显示传递的数据。

这很好用,当我尝试保存这些数据时问题就开始了。在StackOwerflow上关注了许多YouTube教程和例子,但它不会保存数据。

无论如何,这是第一个活动的代码:

RadioGroup radioGrupa;
    RadioButton imperial, metric;
    EditText visinaCM, visinaFT, visinaINC, tezina , bodyfat, tdee, bmi, bmr, ffmi;
    TextView rezultatTDEE, textVisinaCM, textVisinaFI, rezultatTezina, rezultatBMI, rezultatFFMI, rezultatBMR, rezultatBF;
    Button spremiRezultat;
    int onStartCount = 0;



    public void radioStatistikeInputMetric(View view){
        boolean checked = ((RadioButton) view).isChecked();
        switch (view.getId()){
            case R.id.radioStatistikeMetric:
                if (checked)
               // TU OVO SREDI!!!
                    //textVisinaCM.setVisibility(View.VISIBLE);
                   // visinaCM.setVisibility(View.VISIBLE);
                    //textVisinaFI.setVisibility(View.GONE);
                    //visinaFT.setVisibility(View.GONE);
                   // visinaINC.setVisibility(View.GONE);


                spremiRezultat.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {

                                Intent intent = new Intent(getApplicationContext(), AppLayoutMain.class);

                                    intent.putExtra("tdeeInput", tdee.getText().toString());
                                    intent.putExtra("bodyFatInput", bodyfat.getText().toString());
                                    intent.putExtra("tezinaMetricInput", tezina.getText().toString());
                                    intent.putExtra("visinaMetricInput", visinaCM.getText().toString());
                                    intent.putExtra("bmiInput", bmi.getText().toString());
                                    intent.putExtra("bmrInput", bmr.getText().toString());
                                    intent.putExtra("ffmiInput", ffmi.getText().toString());

                                startActivity(intent);
                        }
                });
                break;
        }
    }

    public void radioStatistikeInputImperial(View view){
        boolean checked = ((RadioButton) view).isChecked();
        switch (view.getId()){
            case R.id.radioStatistikeImperial:
                if (checked)
                    //textVisinaCM.setVisibility(View.GONE);
               // visinaCM.setVisibility(View.GONE);
              //  textVisinaFI.setVisibility(View.VISIBLE);
             //   visinaFT.setVisibility(View.VISIBLE);
             //   visinaINC.setVisibility(View.VISIBLE);

                    spremiRezultat.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                                Intent intent = new Intent(getApplicationContext(), AppLayoutMain.class);
                                intent.putExtra("tdeeInput", tdee.getText().toString());
                                intent.putExtra("bodyFatInput", bodyfat.getText().toString());
                                intent.putExtra("tezinaImperialInput", tezina.getText().toString());
                                intent.putExtra("visinaImperialInputFT", visinaFT.getText().toString());
                                intent.putExtra("visinaImperialInputINC", visinaINC.getText().toString());
                                intent.putExtra("bmiInput", bmi.getText().toString());
                                intent.putExtra("bmrInput", bmr.getText().toString());
                                intent.putExtra("ffmiInput", ffmi.getText().toString());
                                startActivity(intent);

                        }
                    });
                break;
        }
    }




    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_statistike_input_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);


        if (savedInstanceState != null){
            String inputi = savedInstanceState.getString("INPUTI");
            rezultatTDEE.setText(inputi);
        }

        onStartCount = 1;
        if (savedInstanceState == null)
        {
            this.overridePendingTransition(R.anim.anim_slide_in_left,
                    R.anim.anim_slide_out_left);
        } else {
            onStartCount = 2;
        }


// RADIO
        radioGrupa = (RadioGroup) findViewById(R.id.radioGrupaStatistike);
        imperial = (RadioButton) findViewById(R.id.radioStatistikeImperial);
        metric = (RadioButton) findViewById(R.id.radioStatistikeMetric);
//VISINA
        visinaCM = (EditText) findViewById(R.id.editTextStatistikeVisinaCM);
        visinaFT = (EditText) findViewById(R.id.editTextStatistikeVisinaFEET);
        visinaINC = (EditText) findViewById(R.id.editTextStatistikeVisinaINCH);
//TEŽINA
        tezina = (EditText) findViewById(R.id.editTextStatistikeTezina);
//BODYFAT
        bodyfat = (EditText) findViewById(R.id.editTextStatistikeBF);
//TDEE
        tdee = (EditText) findViewById(R.id.editTextStatistikeTDEE);
//BMI
        bmi = (EditText) findViewById(R.id.editTextStatistikeBMI);
//BMR
        bmr = (EditText) findViewById(R.id.editTextStatistikeBMR);
//FFMI
        ffmi = (EditText) findViewById(R.id.editTextStatistikeFFMI);
//BUTTON
        spremiRezultat = (Button) findViewById(R.id.buttonStatistikeInputSpremi);
//REZULTATI
        rezultatTDEE = (TextView) findViewById(R.id.textViewStatistikeRezultatTDEE);
        textVisinaCM = (TextView) findViewById(R.id.textViewStatistikeRezultatVisina);
        textVisinaFI = (TextView) findViewById(R.id.textViewStatistikeVisinaFeetInch);
        rezultatTezina = (TextView) findViewById(R.id.textViewStatistikeRezultatTezina);
        rezultatBMI = (TextView) findViewById(R.id.textViewStatistikeBMI);
        rezultatBMR = (TextView) findViewById(R.id.textViewStatistikeBMR);
        rezultatFFMI = (TextView) findViewById(R.id.textViewStatistikeFFMI);
        rezultatBF = (TextView) findViewById(R.id.textViewStatistikeRezultatBodyFat);

    }

    public void save(View view){
        SharedPreferences sharedPreferences = getSharedPreferences("MyData", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString("bmi", bmi.getText().toString());
        editor.putString("bmr", bmr.getText().toString());

        editor.commit();

    }


    @Override
    protected void onStart() {
        // TODO Auto-generated method stub
        super.onStart();
        if (onStartCount > 1) {
            this.overridePendingTransition(R.anim.anim_slide_in_right,
                    R.anim.anim_slide_out_right);

        } else if (onStartCount == 1) {
            onStartCount++;
        }

    }

共享偏好位于save方法。

现在这是第二项活动的代码:

private DrawerLayout mDrawer;
    private ActionBarDrawerToggle drawerToggle;
    private Toolbar toolbar;
    int onStartCount = 0;
    ProgressDialog progress;
    NavigationView nvDrawer;
    DrawerLayout dlDrawer;
    android.support.v7.widget.CardView karticaStatistike;
    TextView tdeeRezultat, bodyFatRezultat, bmiRezultat, bmrRezultat, ffmiRezultat, tezinaMetricRezultat, visinaMetricRezultat, tezinaImperialRezultat, visinaFTImperialRezultat, visinaINCImperialRezultat, ciljTreningRezultat, razinaTreningRezultat, preporukaTreningRezultat, oneRMPotisakSKlupeRezultat, oneRMCucanjRezultat, oneRMMrtvoDizanjeRezultat, ciljPrehranaRezultat;
    public static final String DEFAULT="N/A";


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_app_layout_main);
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);



        karticaStatistike = (android.support.v7.widget.CardView) findViewById(R.id.Statiske);


        //  STATISTIKE - PASSAN DATA

        Intent intent = getIntent();
        String tdee = intent.getStringExtra("tdeeInput");
        String bf = intent.getStringExtra("bodyFatInput");
        String bmi = intent.getStringExtra("bmiInput");
        String bmr = intent.getStringExtra("bmrInput");
        String ffmi = intent.getStringExtra("ffmiInput");
        String tezinaMetric = intent.getStringExtra("tezinaMetricInput");
        String visinaMetric = intent.getStringExtra("visinaMetricInput");
        String tezinaImperial = intent.getStringExtra("tezinaImperialInput");
        String visinaImperial1 = intent.getStringExtra("visinaImperialInputFT");
        String visinaImperial2 = intent.getStringExtra("visinaImperialInputINC");
        tdeeRezultat = (TextView) findViewById(R.id.textViewStatistikeRezultatTDEE);
        tdeeRezultat.setText(tdee);
        bodyFatRezultat = (TextView) findViewById(R.id.textViewStatistikeRezultatBodyFat);
        bodyFatRezultat.setText(bf);
        bmiRezultat = (TextView) findViewById(R.id.textViewStatistikeBMI);
        bmiRezultat.setText(bmi);
        bmrRezultat = (TextView) findViewById(R.id.textViewStatistikeBMR);
        bmrRezultat.setText(bmr);
        ffmiRezultat = (TextView) findViewById(R.id.textViewStatistikeFFMI);
        ffmiRezultat.setText(ffmi);
        tezinaMetricRezultat = (TextView) findViewById(R.id.textViewStatistikeRezultatTezina);
        tezinaMetricRezultat.setText(tezinaMetric);
        visinaMetricRezultat = (TextView) findViewById(R.id.textViewStatistikeRezultatVisina);
        visinaMetricRezultat.setText(visinaMetric);



// SMISLI ŠTA ĆEŠ S OVIM, IZAZIVA KONFLIKT U VISINI I TEŽINI, PROBAJ S NEKIM IFOM
       // tezinaImperialRezultat = (TextView) findViewById(R.id.textViewStatistikeRezultatTezina);
       // tezinaImperialRezultat.setText(tezinaImperial);
        //visinaFTImperialRezultat = (TextView) findViewById(R.id.textViewStatistikeRezultatVisina);
        //visinaFTImperialRezultat.setText(visinaImperial1 + "'" +  " " + visinaImperial2 + "''");
        //  STATISTIKE - KRAJ PASSANJA



// TRENING - PASSAN DATA
        String oneRMBench = intent.getStringExtra("oneRMBenchInput");
        String oneRMSquat = intent.getStringExtra("oneRMSquatInput");
        String oneRMDead = intent.getStringExtra("oneRMDeadInput");
        String ciljTreninga = intent.getStringExtra("vrijednostSpinneraCilj");
        String razinaIskustva = intent.getStringExtra("vrijednostSpinneraRazinaIskustva");

        oneRMPotisakSKlupeRezultat = (TextView) findViewById(R.id.textViewTreningRezultat1RMPotisakSKlupe);
        oneRMPotisakSKlupeRezultat.setText(oneRMBench);
        oneRMCucanjRezultat = (TextView) findViewById(R.id.textViewTreningRezultat1RMCucanj);
        oneRMCucanjRezultat.setText(oneRMSquat);
        oneRMMrtvoDizanjeRezultat = (TextView) findViewById(R.id.textViewTreningRezultat1RMMrtvoDizanje);
        oneRMMrtvoDizanjeRezultat.setText(oneRMDead);

        ciljTreningRezultat = (TextView) findViewById(R.id.textViewTreningRezultatCilj);
        ciljTreningRezultat.setText(ciljTreninga);
        razinaTreningRezultat = (TextView) findViewById(R.id.textViewTreningRezultatRazinaIskustva);
        razinaTreningRezultat.setText(razinaIskustva);


// PREHRANA - PASSAN DATA

        String prehrana = intent.getStringExtra("vrijednostSpinnera");

        ciljPrehranaRezultat = (TextView) findViewById(R.id.textViewPrehranaCiljRezultat);
        ciljPrehranaRezultat.setText(prehrana);
        tdeeRezultat = (TextView) findViewById(R.id.textViewPrehranaTDEE);
        tdeeRezultat.setText(tdee);




        dlDrawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawerToggle = setupDrawerToggle();

        dlDrawer.setDrawerListener((DrawerLayout.DrawerListener) drawerToggle);


        mDrawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        nvDrawer = (NavigationView) findViewById(R.id.nvView);
        setupDrawerContent(nvDrawer);

        onStartCount = 1;
        if (savedInstanceState == null)
        {
            this.overridePendingTransition(R.anim.anim_slide_in_left,
                    R.anim.anim_slide_out_left);
        } else {
            onStartCount = 2;
        }

    }

    public void load(View view){
        SharedPreferences sharedPreferences = getSharedPreferences("MyData", Context.MODE_PRIVATE);
        String bmiSaved = sharedPreferences.getString("bmi", "DEFAULT");
        String bmrSaved = sharedPreferences.getString("bmr", "DEFAULT");

        if (bmiSaved.equals(DEFAULT) || bmrSaved.equals(DEFAULT)){
            Toast.makeText(AppLayoutMain.this, "No Data Was Found", Toast.LENGTH_LONG).show();
        } else
            Toast.makeText(AppLayoutMain.this, "Data Loaded Sucessfully", Toast.LENGTH_LONG).show();
            bmiRezultat.setText(bmiSaved);
            bmrRezultat.setText(bmrSaved);
    }

共享偏好采用load方法。

我支持大量代码,但我需要显示和保存大量数据。

如果有人可以提供帮助,我会非常感激!

3 个答案:

答案 0 :(得分:0)

以下是它的工作原理:

....
String tel = editText.getText();
....

SharedPreferences etext = getPreferenceManager().getSharedPreferences();
SharedPreferences.Editor editor = etext.edit();
editor.putString("tel", tel);
editor.apply();

要撤退:

SharedPreferences etext = getPreferenceManager().getSharedPreferences();
String str = etext.getString("tel", "");

答案 1 :(得分:0)

PreferenceManager.getDefaultSharedPreferences(getApplicationContext()) .edit().putString("key", StringValue).apply();保存字符串。

PreferenceManager.getDefaultSharedPreferences(getApplicationContext()) .getString("key", defaultString);获取字符串。
至少对于默认首选项。

答案 2 :(得分:-1)

你有第二个代码:

    else
            Toast.makeText(AppLayoutMain.this, "Data Loaded Sucessfully", Toast.LENGTH_LONG).show();
            bmiRezultat.setText(bmiSaved);
            bmrRezultat.setText(bmrSaved);

我想它应该是这样你需要添加括号{}:

    else {
            Toast.makeText(AppLayoutMain.this, "Data Loaded Sucessfully", Toast.LENGTH_LONG).show();
            bmiRezultat.setText(bmiSaved);
            bmrRezultat.setText(bmrSaved); 
         }

为什么你在默认值中将“DEFAULT”添加为字符串,它不会被初始化为“N / A”,只需将其替换为

sharedPreferences.getString("bmr", DEFAULT);

*我假设您在设计中使用某种按钮从XML中单击调用保存功能。