繁体   English   中英

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

[英]App does not save data before activity closes, or not loading data after activity is created - SharedPreferences

主要活动数据无法使用SharedPreferences正确保存/加载

请参阅上面的链接,以了解其他人的原始问题和反馈...概括起来,SharedPreferences不是保存或没有正确加载数据...请参阅我的应用程序图片,它将更好地显示问题:

我的应用程序的屏幕截图

至于主要活动背后的代码,我尝试了不同人提出的不同建议,并且感谢任何曾经或愿意提供帮助的人:)这时,这是与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

我不确定自己是否知道自己想要什么,但是根据我的理解,您应该在已知会被调用的状态(例如onPause();加载和保存数据onPause(); 您还应该看看Android Activity生命周期

这是我应用中的一些相关片段

@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()做一些简单的检查,以找出丢失包/数据的位置

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

如果您想显式保存某些内容而无需等待,可以将其移至自己的方法并在需要时调用它(这是使用共享首选项而不是捆绑软件):

public void save(Context context, String text) {
    SharedPreferences settings;
    SharedPreferences.Editor editor;
    settings = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
    editor = settings.edit();

    editor.putString("someString", text);
    editor.commit();
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM