应用程序不会在活动关闭之前保存数据,也不会在创建活动后加载数据 - SharedPreferences

时间:2016-07-29 04:34:10

标签: java android sharedpreferences

Data on main activity doesn't save / load properly with SharedPreferences

请参阅以上链接原始问题和其他人的回复......总结一下,SharedPreferences要么没有保存,要么没有正确加载数据...看到我的应用程序的图片,它会更好地显示问题:

Screenshots of my app in progress

至于主要活动背后的代码,我尝试过不同的人建议的不同的东西,我感谢任何曾经或愿意帮助的人:)在这个时刻,这是与MainActivity中的问题相关的代码:(请注意:为了节省空间,我只展示了一个Bundle(getFromQuizOne),但我对所有10个测验都有相同类型的Bundle / Bundle代码。另外,我只放了一个测验按钮setOnClickListener,但同样的代码适用于所有其他测验按钮。)

            //Get points from Quiz One
            Bundle getFromQuizOne = getIntent().getExtras();
            if(getFromQuizOne != null)
            {
                //Get points from Quiz One
                numberQuizOnePoints = getFromQuizOne.getInt("PointsFromAllQuizOne");

                SharedPreferences shareInt = getApplicationContext().getSharedPreferences(QUIZ, MODE_PRIVATE);
                SharedPreferences.Editor editInt = shareInt.edit();

                //Save the value of points from Quiz One with SharedPreferences
                editInt.putInt("quizOnePointsYeah", numberQuizOnePoints);
                editInt.commit();

                //Call arrayMethod, which uses for loop to get and display value of points for each quiz
                arrayMethod();
            }//end if

            //My actual project has same kind of Bundle for all other quizzes, but to save space, i am just listing Bundle for quiz 1


            //Directs user to Quiz One, first screen
            quizOneButton.setOnClickListener(new View.OnClickListener()
            {
                @Override
                public void onClick(View v)
                {
                    //Subtract out any points that user already got for Quiz 1 from total...
                    //In case user wants to or has to re-take Quiz 1
                    totalPoints = totalPoints - numberQuizOnePoints;

                    //Subtract out any points that user already got for Quiz 1 from itself, equal 0
                    numberQuizOnePoints -= numberQuizOnePoints;

                    //Go to the Quiz One, first screen

                    Intent directToQuizOnePartOne = new Intent();
                    directToQuizOnePartOne.setClass(getBaseContext(), QuizOnePartOne.class);
                    startActivity(directToQuizOnePartOne);
                    finish();
                }//end void onClick quizOne
            });//end setOnClickListener quizOne

            //My project has button click listeners for all 10 quizzes, that look similar to quizOneButton onClick action listener, but to save on space, I didn't paste it here


        public void arrayMethod()
        {
            int[] points = {numberQuizOnePoints, numberQuizTwoPoints, numberQuizThreePoints,
            numberQuizFourPoints, numberQuizFivePoints, numberQuizSixPoints, numberQuizSevenPoints,
            numberQuizEightPoints, numberQuizNinePoints, numberQuizTenPoints};

            String[] prefKeys = {"quizOnePointsYeah", "quizTwoPointsYeah", "quizThreePointsYeah",
            "quizFourPointsYeah", "quizFivePointsYeah", "quizSixPointsYeah", "quizSevenPointsYeah",
            "quizEightPointsYeah", "quizNinePointsYeah", "quizTenPointsYeah"};

            SharedPreferences shareInt = getApplicationContext().getSharedPreferences(QUIZ, MODE_PRIVATE);

            for (int i = 0; i < 10; i++)
            {
                if (shareInt.getInt(prefKeys[i], 0) > 0)
                {
                    points[i] = shareInt.getInt(prefKeys[i], 0);
                }//end if
                else
                {
                    points[i] = 0;
                }//end else
            }//end for loop

            //Sum up points from each quiz, and put sum in totalPoints variable
            totalPoints = numberQuizOnePoints + numberQuizTwoPoints + numberQuizThreePoints
                    + numberQuizFourPoints + numberQuizFivePoints + numberQuizSixPoints
                    + numberQuizSevenPoints + numberQuizEightPoints + numberQuizNinePoints
                    + numberQuizTenPoints;


            quizOnePointsText.setText(String.format("%d", numberQuizOnePoints));
            quizTwoPointsText.setText(String.format("%d", numberQuizTwoPoints));
            quizThreePointsText.setText(String.format("%d", numberQuizThreePoints));
            quizFourPointsText.setText(String.format("%d", numberQuizFourPoints));
            quizFivePointsText.setText(String.format("%d", numberQuizFivePoints));
            quizSixPointsText.setText(String.format("%d", numberQuizSixPoints));
            quizSevenPointsText.setText(String.format("%d", numberQuizSevenPoints));
            quizEightPointsText.setText(String.format("%d", numberQuizEightPoints));
            quizNinePointsText.setText(String.format("%d", numberQuizNinePoints));
            quizTenPointsText.setText(String.format("%d", numberQuizTenPoints));
            actualPointsText.setText(String.format("%d", totalPoints));
        }//end void arrayMethod
    }//end class MainMenu

1 个答案:

答案 0 :(得分:0)

我不完全确定我知道你想要什么,但根据我的理解,你应该在你知道会被调用的状态(例如event.preventDefault())中加载并保存这些数据。您还应该查看Android Activity Lifecycle

这里有一个与我的应用程序相关的片段

onPause();

编辑:我现在正在查看您的其他相关问题,以便更好地了解您的问题。您可以使用@Override protected void onPause(){ super.onPause(); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); // the UI component values are saved here. outState.putStringArrayList("mList", new ArrayList<>(fretList)); Toast.makeText(this, "Activity state saved", Toast.LENGTH_SHORT).show(); } @Override protected void onRestoreInstanceState(Bundle inState) { super.onRestoreInstanceState(inState); // the UI component values are saved here. // if there is a non empty bundle, then pull arraylist from it, clear old list // just in case, and add all bundle items to it. if (inState != null) { ArrayList bundledList = inState.getStringArrayList("mList"); if (bundledList != null && bundledList.size() > 0) { fretList.clear(); fretList.addAll(bundledList); } } mAdapter.notifyDataSetChanged(); Toast.makeText(this, "Activity state restored", Toast.LENGTH_SHORT).show(); } 进行一些简单的检查,以找出丢失捆绑/数据的位置

Log.d()

如果你想在不等待的情况下明确保存某些内容,你可以将它移动到你自己的方法并随时调用它(这是使用共享的prefs而不是bundle):

if (getFromQuizOne != null)
    {
        Log.d("Test", "not null");
    } else {
        Log.d("Test", "null");
    }